Example #1
0
 public void Update(Version message)
 {
     ServerOS = message.os;
     ServerOSVersion = message.os;
     ServerRelease = message.release;
     ServerVersion = message.version;
 }
Example #2
0
    public static string GetUpdateInformation(string UserAgent, Version version)
    {
        if (UserAgent.Contains("Mac"))
        {
            return "It looks like you're running a Mac. There's no .NET Framework download from Microsoft for the Mac, but you might check out either <a href=\"http://www.microsoft.com/silverlight/resources/install.aspx\">Silverlight</a> which is a browser plugin that includes a small version of the .NET Framework. You could also check out <a href=\"http://www.go-mono.com/mono-downloads/download.html\">Mono</a>, which is an Open Source platform that can run .NET code on a Mac.";
        }

        if (UserAgent.Contains("nix"))
        {
            return "It looks like you're running a Unix machine. There's no .NET Framework download from Microsoft for Unix, but you might check out <a href=\"http://www.go-mono.com/mono-downloads/download.html\">Mono</a>, which is an Open Source platform that can run .NET code on Unix.";
        }

        if (UserAgent.Contains("fox"))
        {
            return MessageForBrowser("Firefox");
        }
        else if (UserAgent.Contains("Chrome"))
        {
            return MessageForBrowser("Chrome");
        }
        else if (UserAgent.Contains("Safari")) // Chrome also uses safari in the user agent so this check must come after
        {
            return MessageForBrowser("Safari");
        }
        else if(!UserAgent.Contains("MSIE"))
        {
            return UnknownBrowserMessage();
        }

        var windowsFactory = new WindowsVersionFactory();
        var latest = windowsFactory.GetLatestWindows();
        return latest.CheckOs(UserAgent);
    }
        internal void Update(Stream stream)
        {
            using (var binReader = new BinaryReader(stream))
            {
                binReader.ReadByte();

                Version = binReader.ReadByte();
                Model = binReader.ReadByte();
                Id = Encoding.UTF8.GetString(binReader.ReadBytes(2), 0, 2);
                BootloaderVersion = new Version(
                    binReader.ReadByte(),
                    binReader.ReadByte(),
                    binReader.ReadByte(),
                    binReader.ReadByte()
                    );
                FirmwareVersion = new Version(
                    binReader.ReadByte(),
                    binReader.ReadByte(),
                    binReader.ReadByte(),
                    default(byte)
                    );

                var macBuilder = new StringBuilder();
                macBuilder.Append(Convert.ToString(binReader.ReadByte(), 16));
                for (var i = 0; i < 5; i++)
                    macBuilder.Append("-").Append(Convert.ToString(binReader.ReadByte(), 16));
                MacAddress = macBuilder.ToString();

                var ssidLength = binReader.ReadByte();
                Ssid = Encoding.UTF8.GetString(binReader.ReadBytes(ssidLength), 0, ssidLength);
            }
        }
Example #4
0
        public TupleSpace(String host, int port, String userName, String password, String[] spaces)
        {
            try
            {
                server = new TcpClient(host, port);
                writer = new StreamWriter(server.GetStream());
                writer.AutoFlush = true;
                responseThread = new ResponseThread(new StreamReader(server.GetStream()));
                Thread rThread = new Thread(new ThreadStart(responseThread.run));
                rThread.IsBackground = true;
                rThread.Start();

                ConnectCommand cc = new ConnectCommand(userName, password, spaces);
                TSResponse response = SendReceive(cc);
                Tuple[] tuples = response.Tuples;
                this.spaces = new Space[tuples.Length];
                for (int i = 0; i < tuples.Length; i++)
                {
                    Field[] f = tuples[i].Fields;
                    Version v = new Version((int) f[2].Value, (int) f[3].Value,
                                            (int) f[4].Value, (int) f[5].Value, (string) f[6].Value,
                                            (int) f[7].Value);
                    int spaceId = (int) f[1].Value;
                    string spaceName = f[0].Value.ToString();
                    this.spaces[i] = new Space(spaceName, spaceId, v);
                }
            }
            catch (Exception e)
            {
                throw new TupleSpaceException(e.Message);
            }
        }
Example #5
0
    public bool PosTest2()
    {
        bool retVal = true;

        // Add your scenario description here
        TestLibrary.TestFramework.BeginScenario("PosTest2: Verify property Build with args ctor.");

        try
        {
            int intMajor = TestLibrary.Generator.GetInt32(-55);
            int intMinor = TestLibrary.Generator.GetInt32(-55);
            int intBuild = TestLibrary.Generator.GetInt32(-55);
            int intRevision = TestLibrary.Generator.GetInt32(-55);
            Version version = new Version(intMajor, intMinor, intBuild, intRevision);

            if (version.Build != intBuild)
            {
                Console.WriteLine("excepted value is :" + version.Build);
                Console.WriteLine("actual value is :" + intBuild);

                TestLibrary.TestFramework.LogError("002.1", "Property Build Err !");
                retVal = false;
                return retVal;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("002.2", "Unexpected exception: " + e);
            TestLibrary.TestFramework.LogInformation(e.StackTrace);
            retVal = false;
        }

        return retVal;
    }
        public Version Parse(string version)
        {
            if (string.IsNullOrEmpty(version))
                new System.ArgumentNullException("version", "Version was null or empty.");
            Version v = new Version();
            version = version.Trim();
            string[] parts = version.Split(' ');
            string versionInfo = parts[0];

            for (int i = 1; i < parts.Length; i++)
            {
                v.Description += parts[i] + " ";
            }
            if (v.Description != null) v.Description = v.Description.Trim();

            string[] vParts = versionInfo.Split('.');
            if (vParts.Length > 0) v.Major = ParsingTools.ParseIndex(vParts, 0);
            if (vParts.Length > 1) v.Minor = ParsingTools.ParseIndex(vParts, 1);
            if (vParts.Length > 2) v.Build = ParsingTools.ParseIndex(vParts, 2);
            int year = 0;
            if (vParts.Length > 3) year = ParsingTools.ParseIndex(vParts, 3);
            int month = 0;
            if (vParts.Length > 4) month = ParsingTools.ParseIndex(vParts, 4);
            int day = 0;
            if (vParts.Length > 5) day = ParsingTools.ParseIndex(vParts, 5);

            if (year > 0 && month > 0 && day > 0 && month < 13 && day < 32) v.DateTime = new DateTime(year, month, day);

            return v;
        }
Example #7
0
 public static uint GetSize(Version version)
 {
     uint magicSize = GetMagicSize(version);
     uint unknownSize = GetUnknownSize(version);
     uint firstBlockOffsetSize = GetUIntSize(version);
     return magicSize + unknownSize + firstBlockOffsetSize;
 }
Example #8
0
    public bool NegTest1()
    {
        bool retVal = true;

        TestLibrary.TestFramework.BeginScenario("NegTest1: ArgumentException is not thrown.");

        try
        {
            Version version = new Version(1, 3, 5);
            string str = version.ToString(4);

            TestLibrary.TestFramework.LogError("101.1", " ArgumentException is not thrown.");
            retVal = false;
        }
        catch (ArgumentException)
        { }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("101.2", "Unexpected exception: " + e);
            TestLibrary.TestFramework.LogInformation(e.StackTrace);
            retVal = false;
        }

        return retVal;
    }
Example #9
0
        public static void CommitVersion(Version version)
        {
            Log.Info(string.Format("Committing version #{0}", version.version));

            RunCommand("add", version.date, "--all", ".");

            List<string> commit_args = new List<string>();
            if (!string.IsNullOrWhiteSpace(version.comment))
            {
                commit_args.Add("-m");
                commit_args.Add("\"" + version.comment.Replace("\\", "\\\\") + "\"");
            }
            commit_args.Add("-m");
            commit_args.Add(string.Format(
                "\"Original Vault Commit: version {0} on {1:yyyy-MM-dd HH:mm:ss} by {2}\"",
                version.version,
                version.date,
                version.user));
            commit_args.Add(string.Format("--date=\"{0:yyyy-MM-ddTHH:mm:ss}\"", version.date));
            if (version.GitAuthor != null)
            {
                commit_args.Add(string.Format("--author=\"{0}\"", version.GitAuthor));
            }
            commit_args.Add("-a");
            RunCommand("commit", version.date, commit_args.ToArray());

            commit_count++;

            if (commit_count % 50 == 0)
            {
                RunCommand("gc", null);
            }
        }
        // Adds Parameter for unit tests
        internal static bool StartCore(Version testVersion = null) {
            var version = testVersion ?? WebPagesDeployment.GetVersion(HttpRuntime.AppDomainAppPath, WebConfigurationManager.AppSettings);

            bool loaded = false;
            if (version == AssemblyUtils.ThisAssemblyName.Version) {
                Debug.WriteLine("WebPages Bootstrapper v{0}: loading WebPages", AssemblyUtils.ThisAssemblyName.Version);

                loaded = true;
                if (testVersion == null) {
                    LoadWebPages();
                }
            }
            else if (version == null) {
                Debug.WriteLine("WebPages Bootstrapper v{0}: WebPages not enabled, registering for change notifications", AssemblyUtils.ThisAssemblyName.Version);

                // Register for change notifications under the application root
                // but do not register if webPages:Enabled has been explicitly set to false (Dev10 bug 913600)
                if (testVersion == null && !WebPagesDeployment.IsExplicitlyDisabled(WebConfigurationManager.AppSettings)) {
                    RegisterForChangeNotifications();
                }
            }
            else {
                Debug.WriteLine("WebPages Bootstrapper v{0}: site version is {1}, not loading WebPages", AssemblyUtils.ThisAssemblyName.Version, version);
            }
            return loaded;
        }
Example #11
0
 internal static CimInstance CreatePSNegotiationData(Version powerShellVersion)
 {
     CimInstance c = InternalMISerializer.CreateCimInstance("PS_NegotiationData");
     CimProperty versionproperty = InternalMISerializer.CreateCimProperty("PSVersion", powerShellVersion.ToString(), Microsoft.Management.Infrastructure.CimType.String);
     c.CimInstanceProperties.Add(versionproperty);
     return c;
 }
Example #12
0
	  /// <summary>
	  /// Creates NGramTokenFilter with given min and max n-grams. </summary>
	  /// <param name="version"> Lucene version to enable correct position increments.
	  ///                See <a href="#version">above</a> for details. </param>
	  /// <param name="input"> <seealso cref="TokenStream"/> holding the input to be tokenized </param>
	  /// <param name="minGram"> the smallest n-gram to generate </param>
	  /// <param name="maxGram"> the largest n-gram to generate </param>
	  public NGramTokenFilter(Version version, TokenStream input, int minGram, int maxGram) : base(new CodepointCountFilter(version, input, minGram, int.MaxValue))
	  {
		this.version = version;
		this.charUtils = version.onOrAfter(Version.LUCENE_44) ? CharacterUtils.getInstance(version) : CharacterUtils.Java4Instance;
		if (minGram < 1)
		{
		  throw new System.ArgumentException("minGram must be greater than zero");
		}
		if (minGram > maxGram)
		{
		  throw new System.ArgumentException("minGram must not be greater than maxGram");
		}
		this.minGram = minGram;
		this.maxGram = maxGram;
		if (version.onOrAfter(Version.LUCENE_44))
		{
		  posIncAtt = addAttribute(typeof(PositionIncrementAttribute));
		  posLenAtt = addAttribute(typeof(PositionLengthAttribute));
		}
		else
		{
		  posIncAtt = new PositionIncrementAttributeAnonymousInnerClassHelper(this);
		  posLenAtt = new PositionLengthAttributeAnonymousInnerClassHelper(this);
		}
	  }
Example #13
0
 /// <summary>
 /// Constructor for the <c>VersionLabel</c> object. This is
 /// used to create a label that can convert from a double to an
 /// XML attribute and vice versa. This requires the annotation and
 /// contact extracted from the XML schema class.
 /// </summary>
 /// <param name="contact">
 /// this is the field from the XML schema class
 /// </param>
 /// <param name="label">
 /// represents the annotation for the field
 /// </param>
 public VersionLabel(Contact contact, Version label) {
    this.detail = new Signature(contact, this);
    this.decorator = new Qualifier(contact);
    this.type = contact.Type;
    this.name = label.name();
    this.label = label;
 }
Example #14
0
        public static Version ParseRustcOutput(String output)
        {
            var outputParts = output.Split(' ');
            if (outputParts.Length != 4)
                return null;

            var releaseParts = outputParts[1].Split('.', '-');
            if (releaseParts.Length != 4)
                return null;

            var result = new Version();
            try
            {
                result.VersionMajor = Convert.ToUInt32(releaseParts[0]);
                result.VersionMinor = Convert.ToUInt32(releaseParts[1]);
                result.VersionPatch = Convert.ToUInt32(releaseParts[2]);
                result.VersionVariant = releaseParts[3].Trim().ToLowerInvariant();
            }
            catch (Exception ex)
            {
                return null;
            }

            return result;
        }
		public OperatingSystem(PlatformID platformID, Version version) {
			if (version == null) {
				throw new ArgumentNullException("version");
			}
			this.platformID = platformID;
			this.version = version;
		}
	public UpdatePresentResult2 IsUpdateAvailable2(
		UpdateCheckInfo2 info )
	{
		try
		{
			CheckThrowApiKey(info.ApiKey);

			var v1 = new Version(info.VersionNumber);
			var v2 = availableVersion;

			var url = v1 >= v2 ? string.Empty : ConfigurationManager.AppSettings[@"updateChecker.downloadUrl"];
			var web = v1 >= v2 ? string.Empty : ConfigurationManager.AppSettings[@"updateChecker.websiteUrl"];

			var result =
				new UpdatePresentResult2
					{
						IsPresent = v1 < v2, 
						DownloadWebsiteUrl = web
					};

			LogCentral.Current.LogInfo(string.Format(@"Returning download URL '{0}'.", url));
			return result;
		}
		catch (Exception x)
		{
			LogCentral.Current.LogError(@"Error checking whether an update is available.", x);
			throw;
		}
	}
Example #17
0
        public static void CheckVersion(String coreVersion, String configVersion, String type, int mode = 0)
        {
            try
            {
                Version ver = new Version(configVersion);

                if (String.IsNullOrEmpty(coreVersion))
                    throw new UnsupportedCoreException(String.Format("Unsupported {0}. Version '{1}' or greater is required", type, configVersion));

                Version cv = new Version(coreVersion);

                if (mode == 0)
                {
                    if (ver.CompareTo(cv) > 0)
                        throw new UnsupportedCoreException(String.Format("Unsupported {0} '{1}'. Version '{2}' or greater is required", type, coreVersion, configVersion));

                    if (cv.Major != ver.Major)
                        throw new UnsupportedCoreException(String.Format("Unsupported {0} '{1}'. Major version is incompatible with server version '{2}'", type, coreVersion, configVersion));
                }

                if (mode == 1)
                {
                    if (!(ver.Major.Equals(cv.Major) && ver.Minor.Equals(cv.Minor) && ver.Build.Equals(cv.Build)))
                        throw new UnsupportedCoreException(String.Format("Unsupported {0} '{1}'. Version '{2}' is required", type, coreVersion, configVersion));
                }

            }
            catch (FormatException)
            {
                throw new System.FormatException(String.Format("Invalid {0} version format", type));
            }

        }
Example #18
0
 void GetFrameworkVersion(XDocument xDocument)
 {
     FrameworkVersionAsString = xDocument.Descendants("TargetFrameworkVersion")
         .Select(c => c.Value)
         .First();
     FrameworkVersionAsNumber = Version.Parse(FrameworkVersionAsString.Remove(0, 1));
 }
Example #19
0
 public static Version Create()
 {
     Version vs = new Version();
     vs.ID = Guid.NewGuid();
     vs.Published = false;
     return vs;
 }
 public DatabaseVersion(Version version)
 {
     Major = version.Major;
     Minor = version.Minor;
     Build = version.Build;
     Revision = version.Revision;
 }
Example #21
0
    public bool PosTest2()
    {
        bool retVal = true;
        TestLibrary.TestFramework.BeginScenario("PosTest2: Ensure Equals(System.Object) return false when the current Version object and obj are both Version objects but not every component of the current Version object matches the corresponding component of obj.");

        try
        {
            Version TestVersion1 = new Version("2.3.4.5");
			Object TestObject1 = (Object)TestVersion1; 
			Version TestVersion2 = new Version("1.2.3.4");
			if (TestVersion2.Equals(TestObject1))
            {
                TestLibrary.TestFramework.LogError("P02.1", "Equals(System.Object) failed when the current Version object and obj are both Version objects but not every component of the current Version object matches the corresponding component of obj!");
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("P02.2", "Unexpected exception: " + e);
            TestLibrary.TestFramework.LogInformation(e.StackTrace);
            retVal = false;
        }

        return retVal;
    }
      protected override Item GetItem(ID itemId, Language language, Version version, Database database)
      {
         Assert.ArgumentNotNull(itemId, "itemId");
         Assert.ArgumentNotNull(language, "language");
         Assert.ArgumentNotNull(version, "version");
         Assert.ArgumentNotNull(database, "database");

         if (Switcher<bool, IntegrationDisabler>.CurrentValue) return base.GetItem(itemId, language, version, database);

         if (Context.Site == null || !Context.Site.Name.Equals("shell") || Config.ContentDatabase == null)
            return base.GetItem(itemId, language, version, database);

         // checking for the database validity. we don't want to run this for core db for ex.
         if (!Config.SupportedDatabases.Any(d => d.Equals(database.Name)))
            return base.GetItem(itemId, language, version, database);

         var item = base.GetItem(itemId, language, version, database);

         // checking if the item implements IRepository
         bool isRepository = item.IsRepository();

         if (item == null || !isRepository || item.Name.Equals(Constants.StandardValuesItemName))
         {
            //if we are not a repository, then leave
            return item;
         }

         var args = new GenericItemProviderArgs(item);
         CorePipeline.Run("genericItemProvider", args);

         return args.RootItem;
      }
 public void EnsureNonNegativeComponents_3Values()
 {
     var version = new Version(1, 2, 3).EnsureNonNegativeComponents();
     Assert.Equal(1, version.Major);
     Assert.Equal(2, version.Minor);
     Assert.Equal(3, version.Build);
     Assert.Equal(0, version.Revision);
 }
		/// <summary>
		/// Initializes a new instance of the <see cref="HttpRequestMessage" /> class
		/// with an HTTP method and a request System.Uri.
		/// </summary>
		/// <param name="method">The HTTP method.</param>
		/// <param name="requestUri">The System.Uri to request.</param>
		public HttpRequestMessage(HttpMethod method, Uri requestUri)
		{
			RequestUri = requestUri;
			Properties = new Dictionary<string, object>();
			Version = new Version("1.1");
			Method = method;
			Headers = new HttpRequestHeaders(new WebHeaderCollection());
		}
Example #25
0
 public void TestServices2()
 {
     var p = shake.CommandLine.Properties;
     var b = p.BuildNumber;
     var v = new Version(0, 1, b ?? 0);
     Console.WriteLine("v{0}", v);
     Console.WriteLine("{0} v{1}", shake.CommandLine.Properties.Title ?? "TestApp", v);
 }
 public DatabaseVersion(string version)
 {
     Version systemVersion = new Version(version);
     Major = systemVersion.Major;
     Minor = systemVersion.Minor;
     Build = systemVersion.Build;
     Revision = systemVersion.Revision;
 }
Example #27
0
        public override void AfterMigrationFile(Version version, SqlFileInfo file)
        {
            // GO is needed for applying multiple DDL statements in one transaction
            streamWriter.WriteLine("GO");

            base.AfterMigrationFile(version, file);
            streamWriter.WriteLine("GO");
        }
Example #28
0
 public void creates_valid_version_from_valid_version_string()
 {
     Version version = new Version("12.34.56.78");
     Assert.AreEqual(12, version.Major, "Major number is not correctly parsed");
     Assert.AreEqual(34, version.Minor, "Minor number is not correctly parsed");
     Assert.AreEqual(56, version.Build, "Build number is not correctly parsed");
     Assert.AreEqual(78, version.Revision, "Major number is not correctly parsed");
 }
Example #29
0
        /// <summary>
        /// Class constructor
        /// </summary>
        /// <param name="culture">culture info</param>
        /// <param name="version">version info</param>
        internal CultureSpecificUpdatableHelp(CultureInfo culture, Version version)
        {
            Debug.Assert(version != null);
            Debug.Assert(culture != null);

            Culture = culture;
            Version = version;
        }
        public WindowsOperatingSystem()
        {
            // Get OS Info
            GetOSInfo();

            // Get .NET Framework version + SP
            this._frameworkVersion = new Version(); // 0.0
            this._frameworkSP      = 0;

            try
            {
                RegistryKey regNet = Registry.LocalMachine.OpenSubKey(@"Software\Microsoft\NET Framework Setup\NDP");

                if (regNet != null)
                {
                    if (regNet.OpenSubKey("v4") != null)
                    {
                        this._frameworkVersion = new Version(4, 0);
                    }
                    else if (regNet.OpenSubKey("v3.5") != null)
                    {
                        this._frameworkVersion = new Version(3, 5);
                        this._frameworkSP      = (int)regNet.GetValue("SP", 0);
                    }
                    else if (regNet.OpenSubKey("v3.0") != null)
                    {
                        this._frameworkVersion = new Version(3, 0);
                        this._frameworkSP      = (int)regNet.GetValue("SP", 0);
                    }
                    else if (regNet.OpenSubKey("v2.0.50727") != null)
                    {
                        this._frameworkVersion = new Version(2, 0, 50727);
                        this._frameworkSP      = (int)regNet.GetValue("SP", 0);
                    }
                    else if (regNet.OpenSubKey("v1.1.4322") != null)
                    {
                        this._frameworkVersion = new Version(1, 1, 4322);
                        this._frameworkSP      = (int)regNet.GetValue("SP", 0);
                    }
                    else if (regNet.OpenSubKey("v1.0") != null)
                    {
                        this._frameworkVersion = new Version(1, 0);
                        this._frameworkSP      = (int)regNet.GetValue("SP", 0);
                    }

                    regNet.Close();
                }
            }
            catch { }

            // Get Java version
            this._javaVersion = new Version();

            try
            {
                string javaVersion;

                if (this.Architecture == 32)
                {
                    javaVersion = (string)Utils.GetRegistryValue(Registry.LocalMachine, @"Software\JavaSoft\Java Runtime Environment", "CurrentVersion", "");
                }
                else
                {
                    javaVersion = (string)Utils.GetRegistryValue(Registry.LocalMachine, @"Software\Wow6432Node\JavaSoft\Java Runtime Environment", "CurrentVersion", "");
                }

                this._javaVersion = new Version(javaVersion);
            }
            catch { }
        }
 public Updater(IObjectSpace objectSpace, Version currentDBVersion) : base(objectSpace, currentDBVersion) { }
Example #32
0
 public Updater(Session session, Version currentDBVersion) : base(session, currentDBVersion)
 {
 }
Example #33
0
        /// <summary>
        /// Load the state of an existing map from xml (current state of locations, where the crew is now, etc).
        /// </summary>
        public void LoadState(XElement element, bool showNotifications)
        {
            ClearAnimQueue();
            SetLocation(element.GetAttributeInt("currentlocation", 0));

            if (!Version.TryParse(element.GetAttributeString("version", ""), out _))
            {
                DebugConsole.ThrowError("Incompatible map save file, loading the game failed.");
                return;
            }

            foreach (XElement subElement in element.Elements())
            {
                switch (subElement.Name.ToString().ToLowerInvariant())
                {
                case "location":
                    Location location = Locations[subElement.GetAttributeInt("i", 0)];

                    location.TypeChangeTimer = subElement.GetAttributeInt("changetimer", 0);
                    location.Discovered      = subElement.GetAttributeBool("discovered", false);
                    if (location.Discovered)
                    {
#if CLIENT
                        RemoveFogOfWar(StartLocation);
#endif
                        if (furthestDiscoveredLocation == null || location.MapPosition.X > furthestDiscoveredLocation.MapPosition.X)
                        {
                            furthestDiscoveredLocation = location;
                        }
                    }


                    string       locationType     = subElement.GetAttributeString("type", "");
                    string       prevLocationName = location.Name;
                    LocationType prevLocationType = location.Type;
                    LocationType newLocationType  = LocationType.List.Find(lt => lt.Identifier.Equals(locationType, StringComparison.OrdinalIgnoreCase)) ?? LocationType.List.First();
                    location.ChangeType(newLocationType);
                    if (showNotifications && prevLocationType != location.Type)
                    {
                        var change = prevLocationType.CanChangeTo.Find(c => c.ChangeToType.Equals(location.Type.Identifier, StringComparison.OrdinalIgnoreCase));
                        if (change != null)
                        {
                            ChangeLocationType(location, prevLocationName, change);
                        }
                    }
                    location.LoadMissions(subElement);
                    break;

                case "connection":
                    int connectionIndex = subElement.GetAttributeInt("i", 0);
                    Connections[connectionIndex].Passed = subElement.GetAttributeBool("passed", false);
                    break;
                }
            }

            foreach (Location location in Locations)
            {
                location?.InstantiateLoadedMissions(this);
            }

            int currentLocationConnection = element.GetAttributeInt("currentlocationconnection", -1);
            if (currentLocationConnection >= 0)
            {
                SelectLocation(Connections[currentLocationConnection].OtherLocation(CurrentLocation));
            }
            else
            {
                //this should not be possible, you can't enter non-outpost locations (= natural formations)
                if (CurrentLocation != null && !CurrentLocation.Type.HasOutpost && SelectedConnection == null)
                {
                    DebugConsole.AddWarning($"Error while loading campaign map state. Submarine in a location with no outpost ({CurrentLocation.Name}). Loading the first adjacent connection...");
                    SelectLocation(CurrentLocation.Connections[0].OtherLocation(CurrentLocation));
                }
            }
        }
Example #34
0
 public abstract bool IsPackageExist(string appId, PackageType packageType, PackageLevel packageLevel, Version version);
Example #35
0
 public static extern void GetVersion(out Version version);
Example #36
0
 /// <summary>
 /// 3.5.0 and greater and Release
 /// </summary>
 public static bool HasDependentAssets(Version version, TransferInstructionFlags flags) => version.IsGreaterEqual(3, 5) && flags.IsRelease();
Example #37
0
        // ====================================================== Packaging

        public abstract ApplicationInfo CreateInitialSenseNetVersion(string name, string edition, Version version, string description);
Example #38
0
        private void Page_Loaded(object sender, RoutedEventArgs e)
        {
            // Устанавливаем заголовок в зависимости от типа версии
            try
            {
                lType.Content = Lang.Set("PageGeneral", (string)MainWindow.JsonSettingsGet("multipack.type"), lang) + " #" +
                                Version.Parse((string)MainWindow.JsonSettingsGet("multipack.version")).Revision;
            }
            catch (Exception) { lType.Content = Lang.Set("PageGeneral", "base", lang); }

            // Загружаем список видео и новостей
            try
            {
                Task.Factory.StartNew(() => StatusBarSet(false, 1, true, true)).Wait();

                Task.WaitAll(new Task[] {
                    Task.Factory.StartNew(() => YoutubeClass.Start()),
                    Task.Factory.StartNew(() => WargamingClass.Start())
                });

                Task.WaitAll(new Task[] {
                    Task.Factory.StartNew(() => ViewNews()),
                    Task.Factory.StartNew(() => ViewNews(false))
                });

                Task.Factory.StartNew(() => StatusBarSet(false, 1, true, true, true));
                Task.Factory.StartNew(() => Notify()); // Выводим уведомления видео
            }
            catch (Exception ex) { Task.Factory.StartNew(() => Debugging.Save("General.xaml", "Page_Loaded()", ex.Message, ex.StackTrace)); }

            Task.Factory.StartNew(() =>
            {
                try
                {
                    if ((bool)MainWindow.JsonSettingsGet("multipack.update") && MainWindow.JsonSettingsGet("multipack.update") != null)
                    {
                        Dispatcher.BeginInvoke(new ThreadStart(delegate
                        {
                            lStatus.Text = Lang.Set("PageGeneral", "UpdatesMultipack", (string)MainWindow.JsonSettingsGet("info.language"), (string)MainWindow.JsonSettingsGet("multipack.new_version"));

                            bNotification.Visibility = System.Windows.Visibility.Visible;
                            bUpdate.Visibility       = System.Windows.Visibility.Visible;
                        }));
                    }
                    else
                    {
                        Dispatcher.BeginInvoke(new ThreadStart(delegate
                        {
                            bNotification.Visibility = System.Windows.Visibility.Hidden;
                            bUpdate.Visibility       = System.Windows.Visibility.Hidden;
                        }));
                    }

                    if ((bool)MainWindow.JsonSettingsGet("game.update") && MainWindow.JsonSettingsGet("game.update") != null)
                    {
                        Dispatcher.BeginInvoke(new ThreadStart(delegate { lStatus.Text = Lang.Set("PageGeneral", "UpdatesGame", lang, (string)MainWindow.JsonSettingsGet("game.new_version")); }));
                    }
                }
                catch (Exception ex) { Task.Factory.StartNew(() => Debugging.Save("General.xaml", "Page_Loaded()", "multipack.update", ex.Message, ex.StackTrace)); }
            });

            try { StatusBarSet(false, 1, true, true, true); }
            catch (Exception ex) { Task.Factory.StartNew(() => Debugging.Save("General.xaml", "Page_Loaded()", ex.Message, ex.StackTrace)); }

            Dispatcher.BeginInvoke(new ThreadStart(delegate
            {
                try { MainWindow.LoadPage.Visibility = Visibility.Hidden; }
                catch (Exception) { }
            }));
        }
Example #39
0
        public override IEnumerable <ModuleUpdater> GetModuleUpdaters(IObjectSpace objectSpace, Version versionFromDB)
        {
            ModuleUpdater            updater = new DatabaseUpdate.Updater(objectSpace, versionFromDB);
            PredefinedReportsUpdater predefinedReportsUpdater = new PredefinedReportsUpdater(Application, objectSpace, versionFromDB);

            predefinedReportsUpdater.AddPredefinedReport <ContactsReport>("Contacts Report", typeof(Contact), true);
            return(new ModuleUpdater[] { updater, predefinedReportsUpdater });
        }
        private void StatusUserControl_Loaded(object sender, RoutedEventArgs e)
        {
            if (!CommonFunctions.CurrentPrincipal.IsInRole("Administrator"))
            {
                ButtonRestart.IsEnabled = false;
            }

            if (!CommonFunctions.CurrentPrincipal.IsInRole("Administrator,Editor"))
            {
                ButtonInputWizard.IsEnabled = false;
            }

            m_windowsServiceClient = CommonFunctions.GetWindowsServiceClient();

            if (m_windowsServiceClient == null || m_windowsServiceClient.Helper.RemotingClient.CurrentState != ClientState.Connected)
            {
                ButtonRestart.IsEnabled = false;
            }
            else
            {
                m_windowsServiceClient.Helper.ReceivedServiceResponse += Helper_ReceivedServiceResponse;
                CommonFunctions.SendCommandToService("Version -actionable");
                CommonFunctions.SendCommandToService("Time -actionable");
                CommonFunctions.SendCommandToService("ReportingConfig completeness -actionable");
                m_eventHandlerRegistered = true;
            }

            m_refreshTimer          = new DispatcherTimer();
            m_refreshTimer.Interval = TimeSpan.FromSeconds(5);
            m_refreshTimer.Tick    += RefreshTimer_Tick;
            m_refreshTimer.Start();

            if (IntPtr.Size == 8)
            {
                TextBlockInstance.Text = "64-bit";
            }
            else
            {
                TextBlockInstance.Text = "32-bit";
            }

            TextBlockLocalTime.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");

            Version appVersion = AssemblyInfo.EntryAssembly.Version;

            TextBlockManagerVersion.Text = appVersion.Major + "." + appVersion.Minor + "." + appVersion.Build + ".0";

            try
            {
                using (AdoDataConnection database = new AdoDataConnection(CommonFunctions.DefaultSettingsCategory))
                {
                    TextBlockDatabaseType.Text = database.DatabaseType.ToString();

                    try
                    {
                        if (database.IsSqlite || database.IsJetEngine)
                        {
                            // Extract database file name from connection string for file centric databases
                            TextBlockDatabaseName.Text = FilePath.GetFileName(database.Connection.ConnectionString.ParseKeyValuePairs()["Data Source"]);
                        }
                        else if (database.IsOracle)
                        {
                            // Extract user name from connection string for Oracle databases
                            TextBlockDatabaseName.Text = database.Connection.ConnectionString.ParseKeyValuePairs()["User Id"];
                        }
                        else
                        {
                            TextBlockDatabaseName.Text = database.Connection.Database;
                        }
                    }
                    catch
                    {
                        // Fall back on database name if file anything fails
                        TextBlockDatabaseName.Text = database.Connection.Database;
                    }
                }
            }
            catch
            {
                TextBlockDatabaseName.Text = "Not Available";
            }

            try
            {
                using (UserInfo info = new UserInfo(CommonFunctions.CurrentUser))
                {
                    if (info.Exists)
                    {
                        TextBlockUser.Text = info.LoginID;
                    }
                    else
                    {
                        TextBlockUser.Text = CommonFunctions.CurrentUser;
                    }
                }
            }
            catch
            {
                TextBlockUser.Text = CommonFunctions.CurrentUser;
            }

            CreateGridTextItem(0, 1, HorizontalAlignment.Right, (DateTime.Today - TimeSpan.FromDays(1)).ToString("MM/dd"), CompletenessGrid);
            CreateGridTextItem(0, 2, HorizontalAlignment.Right, DateTime.Now.ToString("MM/dd"), CompletenessGrid);

            CreateGridTextItem(1, 0, HorizontalAlignment.Left, "L4: Good", CompletenessGrid);
            CreateGridTextItem(2, 0, HorizontalAlignment.Left, "L3: Fair", CompletenessGrid);
            CreateGridTextItem(3, 0, HorizontalAlignment.Left, "L2: Poor", CompletenessGrid);
            CreateGridTextItem(4, 0, HorizontalAlignment.Left, "L1: Offline", CompletenessGrid);
            CreateGridTextItem(5, 0, HorizontalAlignment.Left, "L0: Failed", CompletenessGrid);
            CreateGridTextItem(6, 0, HorizontalAlignment.Left, "", CompletenessGrid);
            CreateGridTextItem(7, 0, HorizontalAlignment.Left, "Total", CompletenessGrid);

            CreateGridTextItem(0, 1, HorizontalAlignment.Right, (DateTime.Today - TimeSpan.FromDays(1)).ToString("MM/dd"), CorrectnesssGrid);
            CreateGridTextItem(0, 2, HorizontalAlignment.Right, DateTime.Now.ToString("MM/dd"), CorrectnesssGrid);

            CreateGridTextItem(1, 0, HorizontalAlignment.Left, "Good", CorrectnesssGrid);
            CreateGridTextItem(2, 0, HorizontalAlignment.Left, "Latched", CorrectnesssGrid);
            CreateGridTextItem(3, 0, HorizontalAlignment.Left, "Unreasonable", CorrectnesssGrid);
        }
Example #41
0
        private static void UpdateCheckerOld(string ip)
        {
            Clear();
            Dialog.MessageBox("Checking For Updates...", "Please Wait...", ConsoleColor.Blue);
            var appdata         = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
            var appdataFolder   = $"{appdata}\\MinecraftModUpdater\\";
            var applicationPath = $"{appdata}\\MinecraftModUpdater\\Application_Updater.exe";

            if (!Directory.Exists(appdataFolder))
            {
                Directory.CreateDirectory(appdataFolder);
            }

            if (!File.Exists(applicationPath))
            {
                var client = new WebClient();
                client.Credentials = new NetworkCredential("server", "abc");
                var data = client.DownloadData(
                    $"ftp://{ip}:21/projectFolder/Application_Updater/Application_Updater.exe");
                var stream = File.Create(applicationPath);
                stream.Write(data, 0, data.Length);
                stream.Close();
            }

            FtpWebRequest request =
                (FtpWebRequest)WebRequest.Create($"ftp://{ip}:21/projectFolder/MinecraftModUpdater2/versionData/");

            request.Credentials = new NetworkCredential("server", "abc");
            request.Method      = WebRequestMethods.Ftp.ListDirectory;
            FtpWebResponse response = (FtpWebResponse)request.GetResponse();
            StreamReader   reader   =
                new StreamReader(response.GetResponseStream() ?? throw new InvalidOperationException());
            string line   = reader.ReadLine();
            string result = "";

            while (!string.IsNullOrEmpty(line))
            {
                if (line.Contains(".data"))
                {
                    result = line;
                }

                line = reader.ReadLine();
            }

            reader.Close();
            response.Close();
            string folderPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) +
                                "\\MinecraftModUpdater\\temp";

            using (WebClient client = new WebClient())
            {
                client.Credentials = new NetworkCredential("server", "abc");
                if (!Directory.Exists(folderPath))
                {
                    Directory.CreateDirectory(folderPath);
                }
                string filePath = folderPath + "\\verData.data";
                if (File.Exists(filePath))
                {
                    File.Delete(filePath);
                }
                byte[] data =
                    client.DownloadData($"ftp://{ip}:21/projectFolder/MinecraftModUpdater2/versionData/{result}");
                FileStream stream = File.Create(filePath);
                stream.Write(data, 0, data.Length);
                stream.Close();
            }

            Version currentVersion = Assembly.GetExecutingAssembly().GetName().Version;
            Version serverVersion  = ReadFromBinaryFile <Version>("temp\\verData.data");
            var     version        = serverVersion.CompareTo(currentVersion);

            if (version > 0)
            {
                var p = new Process
                {
                    StartInfo =
                    {
                        Arguments       =
                            $"\"{Assembly.GetExecutingAssembly().Location}\" \"{Path.GetFileName(Assembly.GetExecutingAssembly().Location)}\" \"{ip}\" \"{version}\"",
                        FileName        = applicationPath,
                        UseShellExecute = false
                    }
                };
                p.Start();
                Clear();
                Dialog.MessageBox("Restarting", "Please Wait", ConsoleColor.Red);
                Environment.Exit(0);
            }
        }
Example #42
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ExtensionBase"/> class.
 /// </summary>
 /// <param name="version">The version of the extension.</param>
 /// <param name="typeUri">The type URI to use in the OpenID message.</param>
 /// <param name="additionalSupportedTypeUris">The additional supported type URIs by which this extension might be recognized.  May be null.</param>
 protected ExtensionBase(Version version, string typeUri, IEnumerable <string> additionalSupportedTypeUris)
 {
     this.Version = version;
     this.typeUri = typeUri;
     this.additionalSupportedTypeUris = additionalSupportedTypeUris ?? EmptyList <string> .Instance;
 }
        /// <summary>
        /// Given a strong name, find its path in the GAC.
        /// </summary>
        /// <param name="strongName">The strong name.</param>
        /// <param name="targetProcessorArchitecture">Like x86 or IA64\AMD64.</param>
        /// <param name="getRuntimeVersion">Delegate to get the runtime version from a file path</param>
        /// <param name="targetedRuntimeVersion">What version of the runtime are we targeting</param>
        /// <param name="fullFusionName">Are we guranteed to have a full fusion name. This really can only happen if we have already resolved the assembly</param>
        /// <returns>The path to the assembly. Empty if none exists.</returns>
        internal static string GetLocation
        (
            IBuildEngine4 buildEngine,
            AssemblyNameExtension strongName,
            ProcessorArchitecture targetProcessorArchitecture,
            GetAssemblyRuntimeVersion getRuntimeVersion,
            Version targetedRuntimeVersion,
            bool fullFusionName,
            FileExists fileExists,
            GetPathFromFusionName getPathFromFusionName,
            GetGacEnumerator getGacEnumerator,
            bool specificVersion
        )
        {
            ConcurrentDictionary <AssemblyNameExtension, string> fusionNameToResolvedPath = null;
            bool useGacRarCache = Environment.GetEnvironmentVariable("MSBUILDDISABLEGACRARCACHE") == null;

            if (buildEngine != null && useGacRarCache)
            {
                string key = "44d78b60-3bbe-48fe-9493-04119ebf515f" + "|" + targetProcessorArchitecture.ToString() + "|" + targetedRuntimeVersion.ToString() + "|" + fullFusionName.ToString() + "|" + specificVersion.ToString();
                fusionNameToResolvedPath = buildEngine.GetRegisteredTaskObject(key, RegisteredTaskObjectLifetime.Build) as ConcurrentDictionary <AssemblyNameExtension, string>;
                if (fusionNameToResolvedPath == null)
                {
                    fusionNameToResolvedPath = new ConcurrentDictionary <AssemblyNameExtension, string>(AssemblyNameComparer.GenericComparer);
                    buildEngine.RegisterTaskObject(key, fusionNameToResolvedPath, RegisteredTaskObjectLifetime.Build, true /* dispose early ok*/);
                }
                else
                {
                    if (fusionNameToResolvedPath.ContainsKey(strongName))
                    {
                        fusionNameToResolvedPath.TryGetValue(strongName, out string fusionName);
                        return(fusionName);
                    }
                }
            }

            // Optimize out the case where the public key token is null, if it is null it is not a strongly named assembly and CANNOT be in the gac.
            // also passing it would cause the gac enumeration method to throw an exception indicating the assembly is not a strongnamed assembly.

            // If the publickeyToken is null and the publickeytoken is in the fusion name then this means we are passing in a null or empty PublicKeyToken and then this cannot possibly be in the gac.
            if ((strongName.GetPublicKeyToken() == null || strongName.GetPublicKeyToken().Length == 0) && strongName.FullName.IndexOf("PublicKeyToken", StringComparison.OrdinalIgnoreCase) != -1)
            {
                fusionNameToResolvedPath?.TryAdd(strongName, null);
                return(null);
            }

            // A delegate was not passed in to use the default one
            getPathFromFusionName = getPathFromFusionName ?? pathFromFusionName;

            // A delegate was not passed in to use the default one
            getGacEnumerator = getGacEnumerator ?? gacEnumerator;

            // If we have no processor architecture set then we can tryout a number of processor architectures.
            string location;

            if (!strongName.HasProcessorArchitectureInFusionName)
            {
                if (targetProcessorArchitecture != ProcessorArchitecture.MSIL && targetProcessorArchitecture != ProcessorArchitecture.None)
                {
                    string processorArchitecture = ResolveAssemblyReference.ProcessorArchitectureToString(targetProcessorArchitecture);
                    // Try processor specific first.
                    if (fullFusionName)
                    {
                        location = CheckForFullFusionNameInGac(strongName, processorArchitecture, getPathFromFusionName);
                    }
                    else
                    {
                        location = GetLocationImpl(strongName, processorArchitecture, getRuntimeVersion, targetedRuntimeVersion, fileExists, getPathFromFusionName, getGacEnumerator, specificVersion);
                    }

                    if (!string.IsNullOrEmpty(location))
                    {
                        fusionNameToResolvedPath?.TryAdd(strongName, location);
                        return(location);
                    }
                }

                // Next, try MSIL
                if (fullFusionName)
                {
                    location = CheckForFullFusionNameInGac(strongName, "MSIL", getPathFromFusionName);
                }
                else
                {
                    location = GetLocationImpl(strongName, "MSIL", getRuntimeVersion, targetedRuntimeVersion, fileExists, getPathFromFusionName, getGacEnumerator, specificVersion);
                }
                if (!string.IsNullOrEmpty(location))
                {
                    fusionNameToResolvedPath?.TryAdd(strongName, location);
                    return(location);
                }
            }

            // Next, try no processor architecure
            if (fullFusionName)
            {
                location = CheckForFullFusionNameInGac(strongName, null, getPathFromFusionName);
            }
            else
            {
                location = GetLocationImpl(strongName, null, getRuntimeVersion, targetedRuntimeVersion, fileExists, getPathFromFusionName, getGacEnumerator, specificVersion);
            }

            if (!string.IsNullOrEmpty(location))
            {
                fusionNameToResolvedPath?.TryAdd(strongName, location);
                return(location);
            }

            fusionNameToResolvedPath?.TryAdd(strongName, null);

            return(null);
        }
Example #44
0
        private async Task StartContainerAsync(IExecutionContext executionContext)
        {
            Trace.Entering();
            ArgUtil.NotNull(executionContext, nameof(executionContext));
            ArgUtil.NotNullOrEmpty(executionContext.Container.ContainerImage, nameof(executionContext.Container.ContainerImage));

            // Check docker client/server version
            DockerVersion dockerVersion = await _dockerManger.DockerVersion(executionContext);
            ArgUtil.NotNull(dockerVersion.ServerVersion, nameof(dockerVersion.ServerVersion));
            ArgUtil.NotNull(dockerVersion.ClientVersion, nameof(dockerVersion.ClientVersion));
            Version requiredDockerVersion = new Version(17, 3);
            if (dockerVersion.ServerVersion < requiredDockerVersion)
            {
                throw new NotSupportedException(StringUtil.Loc("MinRequiredDockerServerVersion", requiredDockerVersion, _dockerManger.DockerPath, dockerVersion.ServerVersion));
            }
            if (dockerVersion.ClientVersion < requiredDockerVersion)
            {
                throw new NotSupportedException(StringUtil.Loc("MinRequiredDockerClientVersion", requiredDockerVersion, _dockerManger.DockerPath, dockerVersion.ClientVersion));
            }

            // Pull down docker image
            int pullExitCode = await _dockerManger.DockerPull(executionContext, executionContext.Container.ContainerImage);
            if (pullExitCode != 0)
            {
                throw new InvalidOperationException($"Docker pull fail with exit code {pullExitCode}");
            }

            // Mount folder into container
            executionContext.Container.MountVolumes.Add(new MountVolume(Path.GetDirectoryName(executionContext.Variables.System_DefaultWorkingDirectory.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar))));
            executionContext.Container.MountVolumes.Add(new MountVolume(executionContext.Variables.Agent_TempDirectory));
            executionContext.Container.MountVolumes.Add(new MountVolume(executionContext.Variables.Agent_ToolsDirectory));
            executionContext.Container.MountVolumes.Add(new MountVolume(HostContext.GetDirectory(WellKnownDirectory.Externals), true));
            executionContext.Container.MountVolumes.Add(new MountVolume(HostContext.GetDirectory(WellKnownDirectory.Tasks), true));

            // Ensure .taskkey file exist so we can mount it.
            string taskKeyFile = Path.Combine(HostContext.GetDirectory(WellKnownDirectory.Work), ".taskkey");
            if (!File.Exists(taskKeyFile))
            {
                File.WriteAllText(taskKeyFile, string.Empty);
            }
            executionContext.Container.MountVolumes.Add(new MountVolume(taskKeyFile));

            executionContext.Container.ContainerId = await _dockerManger.DockerCreate(executionContext, executionContext.Container.ContainerImage, executionContext.Container.MountVolumes);
            ArgUtil.NotNullOrEmpty(executionContext.Container.ContainerId, nameof(executionContext.Container.ContainerId));

            // Get current username
            executionContext.Container.CurrentUserName = (await ExecuteCommandAsync(executionContext, "whoami", string.Empty)).FirstOrDefault();
            ArgUtil.NotNullOrEmpty(executionContext.Container.CurrentUserName, nameof(executionContext.Container.CurrentUserName));

            // Get current userId
            executionContext.Container.CurrentUserId = (await ExecuteCommandAsync(executionContext, "id", $"-u {executionContext.Container.CurrentUserName}")).FirstOrDefault();
            ArgUtil.NotNullOrEmpty(executionContext.Container.CurrentUserId, nameof(executionContext.Container.CurrentUserId));

            int startExitCode = await _dockerManger.DockerStart(executionContext, executionContext.Container.ContainerId);
            if (startExitCode != 0)
            {
                throw new InvalidOperationException($"Docker start fail with exit code {startExitCode}");
            }

            // Ensure bash exist in the image
            int execWhichBashExitCode = await _dockerManger.DockerExec(executionContext, executionContext.Container.ContainerId, string.Empty, $"which bash");
            if (execWhichBashExitCode != 0)
            {
                throw new InvalidOperationException($"Docker exec fail with exit code {execWhichBashExitCode}");
            }

            // Create an user with same uid as the agent run as user inside the container.
            // All command execute in docker will run as Root by default, 
            // this will cause the agent on the host machine doesn't have permission to any new file/folder created inside the container.
            // So, we create a user account with same UID inside the container and let all docker exec command run as that user.
            int execUseraddExitCode = await _dockerManger.DockerExec(executionContext, executionContext.Container.ContainerId, string.Empty, $"useradd -m -o -u {executionContext.Container.CurrentUserId} {executionContext.Container.CurrentUserName}_VSTSContainer");
            if (execUseraddExitCode != 0)
            {
                throw new InvalidOperationException($"Docker exec fail with exit code {execUseraddExitCode}");
            }
        }
Example #45
0
        public bool InstallPlugin(PluginDefinition definition, bool enableAfterInstall = true, bool isUpdate = false, bool fromTesting = false)
        {
            try {
                using var client = new WebClient();

                var outputDir    = new DirectoryInfo(Path.Combine(this.pluginDirectory, definition.InternalName, fromTesting ? definition.TestingAssemblyVersion : definition.AssemblyVersion));
                var dllFile      = new FileInfo(Path.Combine(outputDir.FullName, $"{definition.InternalName}.dll"));
                var disabledFile = new FileInfo(Path.Combine(outputDir.FullName, ".disabled"));
                var testingFile  = new FileInfo(Path.Combine(outputDir.FullName, ".testing"));
                var wasDisabled  = disabledFile.Exists;

                if (dllFile.Exists && enableAfterInstall)
                {
                    if (disabledFile.Exists)
                    {
                        disabledFile.Delete();
                    }

                    return(this.dalamud.PluginManager.LoadPluginFromAssembly(dllFile, false, PluginLoadReason.Installer));
                }

                if (dllFile.Exists && !enableAfterInstall)
                {
                    return(true);
                }

                try {
                    if (outputDir.Exists)
                    {
                        outputDir.Delete(true);
                    }
                    outputDir.Create();
                } catch {
                    // ignored, since the plugin may be loaded already
                }

                var path = Path.GetTempFileName();

                var doTestingDownload = false;
                if ((Version.TryParse(definition.TestingAssemblyVersion, out var testingAssemblyVer) || definition.IsTestingExclusive) &&
                    fromTesting)
                {
                    doTestingDownload = testingAssemblyVer > Version.Parse(definition.AssemblyVersion) || definition.IsTestingExclusive;
                }

                var url = definition.DownloadLinkInstall;
                if (doTestingDownload)
                {
                    url = definition.DownloadLinkTesting;
                }
                else if (isUpdate)
                {
                    url = definition.DownloadLinkUpdate;
                }

                Log.Information("Downloading plugin to {0} from {1} doTestingDownload:{2} isTestingExclusive:{3}", path, url, doTestingDownload, definition.IsTestingExclusive);

                client.DownloadFile(url, path);

                Log.Information("Extracting to {0}", outputDir);

                ZipFile.ExtractToDirectory(path, outputDir.FullName);

                if (wasDisabled || !enableAfterInstall)
                {
                    disabledFile.Create().Close();
                    return(true);
                }

                if (doTestingDownload)
                {
                    testingFile.Create().Close();
                }
                else
                {
                    if (testingFile.Exists)
                    {
                        testingFile.Delete();
                    }
                }

                return(this.dalamud.PluginManager.LoadPluginFromAssembly(dllFile, false, PluginLoadReason.Installer));
            }
            catch (Exception e) {
                Log.Error(e, "Plugin download failed hard.");
                return(false);
            }
        }
 public void SetMigrationVersion(string migrationName, Version version)
 {
     Database.Save(new CurrentVersionEntry { MigrationName = migrationName, Version = version });
 }
Example #47
0
 public UpdateAvailableArgs(Version version)
 {
     Version = version;
 }
Example #48
0
        internal AddSoftware GetSWProperties(RegistryKey oRegkey)
        {
            AddSoftware oResult  = new AddSoftware();
            Version     oVer     = null;
            bool        bVersion = false;

            oResult.PSPreReq = "$true";

            if (oRegkey.View == RegistryView.Registry32)
            {
                oResult.Architecture = "X86";
            }
            else
            {
                oResult.Architecture = "X64";
                oResult.PSPreReq     = "[Environment]::Is64BitProcess";
            }



            string sMSI = oRegkey.Name.Split('\\').Last();

            string EncKey = "";

            if (sMSI.StartsWith("{") && sMSI.EndsWith("}"))
            {
                bool bIsMSI = true;
                EncKey = descramble(sMSI.Substring(1, 36).Replace("-", ""));
                try
                {
                    RegistryKey oBase = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, oRegkey.View);
                    RegistryKey oKey  = oBase.OpenSubKey(@"SOFTWARE\Classes\Installer\Products\" + EncKey, false);
                    if (oKey == null)
                    {
                        bIsMSI = false;
                    }
                }
                catch { bIsMSI = false; }

                if (bIsMSI)
                {
                    oResult.MSIProductID = sMSI;
                    oResult.PSUninstall  = "$proc = (Start-Process -FilePath \"msiexec.exe\" -ArgumentList \"/x " + sMSI + " /qn REBOOT=REALLYSUPPRESS \" -Wait -PassThru);$proc.WaitForExit();$ExitCode = $proc.ExitCode";


                    oResult.PSDetection = @"Test-Path 'HKLM:\SOFTWARE\Classes\Installer\Products\" + EncKey + "'";

                    try
                    {
                        RegistryKey oSource = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Classes\Installer\Products\" + EncKey + "\\SourceList");
                        if (oSource != null)
                        {
                            oResult.PSInstall = "$proc = (Start-Process -FilePath \"msiexec.exe\" -ArgumentList \"/i `\"" + oSource.GetValue("PackageName") + "`\" /qn ALLUSERS=2 REBOOT=REALLYSUPPRESS\" -Wait -PassThru);$proc.WaitForExit();$ExitCode = $proc.ExitCode";
                        }
                    }
                    catch
                    {
                        try
                        {
                            string sVer = oRegkey.GetValue("DisplayVersion", "").ToString();
                            if (Version.TryParse(sVer, out oVer))
                            {
                                oResult.PSDetection = @"if(([version](Get-ItemPropertyValue -path '" + oRegkey.Name.Replace("HKEY_LOCAL_MACHINE", "HKLM:") + "' -Name DisplayVersion -ea SilentlyContinue)) -ge '" + sVer + "') { $true } else { $false }";
                            }
                            else
                            {
                                oResult.PSDetection = @"if((Get-ItemPropertyValue -path '" + oRegkey.Name.Replace("HKEY_LOCAL_MACHINE", "HKLM:") + "' -Name DisplayVersion -ea SilentlyContinue) -eq '" + sVer + "') { $true } else { $false }";
                            }
                        }
                        catch { }

                        oResult.PSInstall = "$proc = (Start-Process -FilePath \"msiexec.exe\" -ArgumentList \"/i `\"<PackageName.msi>`\" /qn ALLUSERS=2 REBOOT=REALLYSUPPRESS\" -Wait -PassThru);$proc.WaitForExit();$ExitCode = $proc.ExitCode";
                    }
                }
                else
                {
                    oResult.PSInstall = "$proc = (Start-Process -FilePath \"setup.exe\" -ArgumentList \"/?\" -Wait -PassThru);$proc.WaitForExit();$ExitCode = $proc.ExitCode";

                    string sVer = oRegkey.GetValue("DisplayVersion", "").ToString();
                    if (Version.TryParse(sVer, out oVer)) //check if its a Version
                    {
                        bVersion = true;
                    }

                    if (Environment.Is64BitOperatingSystem && oRegkey.View == RegistryView.Registry32)
                    {
                        if (bVersion)
                        {
                            oResult.PSDetection = @"if(([version](Get-ItemPropertyValue -path '" + oRegkey.Name.ToUpper().Replace("HKEY_LOCAL_MACHINE", "HKLM:").Replace("SOFTWARE\\", "SOFTWARE\\WOW6432NODE\\") + "' -Name DisplayVersion -ea SilentlyContinue)) -ge '" + sVer + "') { $true } else { $false }";
                        }
                        else
                        {
                            oResult.PSDetection = @"if((Get-ItemPropertyValue -path '" + oRegkey.Name.ToUpper().Replace("HKEY_LOCAL_MACHINE", "HKLM:").Replace("SOFTWARE\\", "SOFTWARE\\WOW6432NODE\\") + "' -Name DisplayVersion -ea SilentlyContinue) -eq '" + sVer + "') { $true } else { $false }";
                        }
                    }
                    else
                    {
                        if (bVersion)
                        {
                            oResult.PSDetection = @"if(([version](Get-ItemPropertyValue -path '" + oRegkey.Name.ToUpper().Replace("HKEY_LOCAL_MACHINE", "HKLM:") + "' -Name DisplayVersion -ea SilentlyContinue)) -ge '" + sVer + "') { $true } else { $false }";
                        }
                        else
                        {
                            oResult.PSDetection = @"if((Get-ItemPropertyValue -path '" + oRegkey.Name.ToUpper().Replace("HKEY_LOCAL_MACHINE", "HKLM:") + "' -Name DisplayVersion -ea SilentlyContinue) -eq '" + sVer + "') { $true } else { $false }";
                        }
                    }
                }
            }
            else
            {
                string sVer = oRegkey.GetValue("DisplayVersion", "").ToString();
                if (Version.TryParse(sVer, out oVer)) //check if its a Version
                {
                    bVersion = true;
                }

                oResult.PSInstall = "$proc = (Start-Process -FilePath \"setup.exe\" -ArgumentList \"/?\" -Wait -PassThru);$proc.WaitForExit();$ExitCode = $proc.ExitCode";
                if (Environment.Is64BitOperatingSystem && oRegkey.View == RegistryView.Registry32)
                {
                    if (bVersion)
                    {
                        oResult.PSDetection = @"if(([version](Get-ItemPropertyValue -path '" + oRegkey.Name.ToUpper().Replace("HKEY_LOCAL_MACHINE", "HKLM:").Replace("SOFTWARE\\", "SOFTWARE\\WOW6432NODE\\") + "' -Name DisplayVersion -ea SilentlyContinue)) -ge '" + sVer + "') { $true } else { $false }";
                    }
                    else
                    {
                        oResult.PSDetection = @"if((Get-ItemPropertyValue -path '" + oRegkey.Name.ToUpper().Replace("HKEY_LOCAL_MACHINE", "HKLM:").Replace("SOFTWARE\\", "SOFTWARE\\WOW6432NODE\\") + "' -Name DisplayVersion -ea SilentlyContinue) -eq '" + sVer + "') { $true } else { $false }";
                    }
                }
                else
                {
                    if (bVersion)
                    {
                        oResult.PSDetection = @"if(([version](Get-ItemPropertyValue -path '" + oRegkey.Name.ToUpper().Replace("HKEY_LOCAL_MACHINE", "HKLM:") + "' -Name DisplayVersion -ea SilentlyContinue)) -ge '" + sVer + "') { $true } else { $false }";
                    }
                    else
                    {
                        oResult.PSDetection = @"if((Get-ItemPropertyValue -path '" + oRegkey.Name.ToUpper().Replace("HKEY_LOCAL_MACHINE", "HKLM:") + "' -Name DisplayVersion -ea SilentlyContinue) -eq '" + sVer + "') { $true } else { $false }";
                    }
                }
            }

            oResult.PSDetection = oResult.PSDetection.Replace("HKEY_LOCAL_MACHINE", "HKLM:");
            oResult.PSDetection = oResult.PSDetection.Replace("HKEY_CURRENT_USER", "HKCU:");

            oResult.ProductName    = oRegkey.GetValue("DisplayName", "").ToString();
            oResult.ProductVersion = oRegkey.GetValue("DisplayVersion", "").ToString();
            oResult.Manufacturer   = oRegkey.GetValue("Publisher", "").ToString();

            //If not an MSI try to get Uninstall command from Registry
            if (string.IsNullOrEmpty(oResult.MSIProductID))
            {
                try
                {
                    string sUninst = oRegkey.GetValue("QuietUninstallString", "").ToString().Replace("\"", "");
                    if (!string.IsNullOrEmpty(sUninst))
                    {
                        try
                        {
                            if (sUninst.IndexOf('/') >= 0)
                            {
                                oResult.PSUninstall = "$proc = (Start-Process -FilePath \"" + sUninst.Split('/')[0] + "\" -ArgumentList \"" + sUninst.Substring(sUninst.IndexOf('/')) + "\" -Wait -PassThru);$proc.WaitForExit();$ExitCode = $proc.ExitCode";
                            }
                            else
                            {
                                oResult.PSUninstall = "$proc = (Start-Process -FilePath \"" + sUninst + "\" -ArgumentList \"/?\" -Wait -PassThru);$proc.WaitForExit();$ExitCode = $proc.ExitCode";
                            }
                            //$proc = (Start-Process -FilePath "zps17_en.exe" -ArgumentList "/Silent" -PassThru);$proc.WaitForExit();$ExitCode = $proc.ExitCode
                        }
                        catch
                        {
                            oResult.PSUninstall = "$proc = (Start-Process -FilePath \"" + sUninst + "\" -ArgumentList \"/?\" -Wait -PassThru);$proc.WaitForExit();$ExitCode = $proc.ExitCode";
                        }
                    }
                }
                catch { }
            }
            //If no silent uninstall is provided, use the normal uninstall string
            if (string.IsNullOrEmpty(oResult.PSUninstall))
            {
                if (string.IsNullOrEmpty(oResult.MSIProductID))
                {
                    string sUninst = oRegkey.GetValue("UninstallString", "").ToString().Replace("\"", "");
                    oResult.PSUninstall = "$proc  = (Start-Process -FilePath \"" + sUninst + "\" -ArgumentList \"/?\" -Wait -PassThru);$proc.WaitForExit();$ExitCode = $proc.ExitCode";
                }
            }

            //get Version String
            if (string.IsNullOrEmpty(oResult.ProductVersion))
            {
                string sVersion = oRegkey.GetValue("Version", "").ToString();
                if (!string.IsNullOrEmpty(sVersion))
                {
                    try
                    {
                        Int32  iVersion = Convert.ToInt32(sVersion);
                        string sfullval = iVersion.ToString("X8");
                        sVersion = Convert.ToInt32(sfullval.Substring(0, 2), 16).ToString();
                        sVersion = sVersion + "." + Convert.ToInt32(sfullval.Substring(2, 2), 16).ToString();
                        sVersion = sVersion + "." + Convert.ToInt32(sfullval.Substring(4, 4), 16).ToString();

                        oResult.ProductVersion = sVersion;
                    }
                    catch
                    {
                    }
                }
            }

            //Get Image
            string sDisplayIcon = oRegkey.GetValue("DisplayIcon", "").ToString().Split(',')[0];

            if (!string.IsNullOrEmpty(EncKey))
            {
                try
                {
                    RegistryKey oKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Classes\Installer\Products\" + EncKey, false);
                    if (oKey != null)
                    {
                        string sIcon = oKey.GetValue("ProductIcon", "") as string;

                        if (!string.IsNullOrEmpty(sIcon))
                        {
                            sDisplayIcon = sIcon;
                        }
                    }
                }
                catch { }
            }

            //Add default Icon
            if (string.IsNullOrEmpty(sDisplayIcon))
            {
                sDisplayIcon = @"C:\windows\system32\msiexec.exe";
            }

            if (!sDisplayIcon.Contains(":\\"))
            {
                sDisplayIcon = @"C:\windows\system32\" + sDisplayIcon;
            }

            sDisplayIcon = sDisplayIcon.Replace("\"", "");
            sDisplayIcon = sDisplayIcon.Split(',')[0];

            if (!File.Exists(sDisplayIcon))
            {
                if (File.Exists(sDisplayIcon.Replace(" (x86)", "")))
                {
                    sDisplayIcon = sDisplayIcon.Replace(" (x86)", "");
                }
                else
                {
                    sDisplayIcon = "";
                }
            }

            if (!string.IsNullOrEmpty(sDisplayIcon))
            {
                oResult.Image = imageToByteArray(GetImageFromExe(sDisplayIcon.Replace("\"", "")));
            }

            oResult.Architecture = "X64";

            return(oResult);
        }
Example #49
0
        public static int Main(string[] args)
        {
            try {
                Version v       = Assembly.GetExecutingAssembly().GetName().Version;
                string  version = v.Major + "." + v.Minor + "." + v.Build;
                Console.WriteLine("While.NET Compiler v" + version);
                Console.WriteLine("Copyright (C) Einar Egilsson 2009. All rights reserved.");
                Console.WriteLine();

                CommandLineOptions options = new CommandLineOptions(args);
                if (options.Empty)
                {
                    System.Console.Error.WriteLine("ERROR: No inputs specified");
                    return(1);
                }
                else if (options.Help)
                {
                    System.Console.Error.WriteLine("Usage: wc.exe [options] filename");
                    CommandLineOptions.Print();
                    return(2);
                }
                else if (!options.ReadStdIn && !File.Exists(options.InputFilename))
                {
                    System.Console.Error.WriteLine("ERROR: File '{0}' does not exist", options.InputFilename);
                    return(3);
                }

                Parser parser;
                if (options.ReadStdIn)
                {
                    //Passing the StdIn stream directly to the scanner doesn't work well
                    //so we do it this way instead
                    string       source = Console.In.ReadToEnd();
                    StreamWriter writer = new StreamWriter(new MemoryStream());
                    writer.Write(source);
                    writer.Flush();
                    writer.BaseStream.Seek(0, SeekOrigin.Begin);
                    parser = new Parser(new Scanner(writer.BaseStream), options);
                }
                else
                {
                    parser = new Parser(new Scanner(new FileStream(options.InputFilename, FileMode.Open)), options);
                }
                parser.Parse();
                if (parser.errors.count > 0)
                {
                    return(1);
                }
                WhileProgram.SymbolTable.Clear();
                PluginLoader pluginLoader = new PluginLoader();
                pluginLoader.Load(options.Plugins);

                foreach (ICompilerPlugin plugin in pluginLoader.LoadedPlugins)
                {
                    Console.WriteLine("Executing the '{0}' plugin...", plugin.Name);
                    plugin.ProcessSyntaxTree(WhileProgram.Instance);
                }

                WhileProgram.Instance.Compile(options.OutputFilename);
                Console.WriteLine();
                Console.WriteLine("Compiled program to '{0}'", options.OutputFilename);
                return(0);
            } catch (Exception ex) {
                Console.Error.WriteLine("ERROR: " + ex.Message);
                Console.Error.WriteLine(ex.StackTrace);
                return(1);
            }
        }
Example #50
0
        public LevelDBBlockchain(string path)
        {
            header_index.Add(GenesisBlock.Hash);
            Version version;
            Slice   value;

            db = DB.Open(path, new Options {
                CreateIfMissing = true
            });
            if (db.TryGet(ReadOptions.Default, SliceBuilder.Begin(DataEntryPrefix.SYS_Version), out value) && Version.TryParse(value.ToString(), out version) && version >= Version.Parse("1.5"))
            {
                ReadOptions options = new ReadOptions {
                    FillCache = false
                };
                value = db.Get(options, SliceBuilder.Begin(DataEntryPrefix.SYS_CurrentBlock));
                UInt256 current_header_hash = new UInt256(value.ToArray().Take(32).ToArray());
                this.current_block_height = value.ToArray().ToUInt32(32);
                uint current_header_height = current_block_height;
                if (db.TryGet(options, SliceBuilder.Begin(DataEntryPrefix.SYS_CurrentHeader), out value))
                {
                    current_header_hash   = new UInt256(value.ToArray().Take(32).ToArray());
                    current_header_height = value.ToArray().ToUInt32(32);
                }
                foreach (UInt256 hash in db.Find(options, SliceBuilder.Begin(DataEntryPrefix.IX_HeaderHashList), (k, v) =>
                {
                    using (MemoryStream ms = new MemoryStream(v.ToArray(), false))
                        using (BinaryReader r = new BinaryReader(ms))
                        {
                            return(new
                            {
                                Index = k.ToArray().ToUInt32(1),
                                Hashes = r.ReadSerializableArray <UInt256>()
                            });
                        }
                }).OrderBy(p => p.Index).SelectMany(p => p.Hashes).ToArray())
                {
                    if (!hash.Equals(GenesisBlock.Hash))
                    {
                        header_index.Add(hash);
                    }
                    stored_header_count++;
                }
                if (stored_header_count == 0)
                {
                    Header[] headers = db.Find(options, SliceBuilder.Begin(DataEntryPrefix.DATA_Block), (k, v) => Header.FromTrimmedData(v.ToArray(), sizeof(long))).OrderBy(p => p.Index).ToArray();
                    for (int i = 1; i < headers.Length; i++)
                    {
                        header_index.Add(headers[i].Hash);
                    }
                }
                else if (current_header_height >= stored_header_count)
                {
                    for (UInt256 hash = current_header_hash; hash != header_index[(int)stored_header_count - 1];)
                    {
                        Header header = Header.FromTrimmedData(db.Get(options, SliceBuilder.Begin(DataEntryPrefix.DATA_Block).Add(hash)).ToArray(), sizeof(long));
                        header_index.Insert((int)stored_header_count, hash);
                        hash = header.PrevHash;
                    }
                }
            }
            else
            {
                WriteBatch  batch   = new WriteBatch();
                ReadOptions options = new ReadOptions {
                    FillCache = false
                };
                using (Iterator it = db.NewIterator(options))
                {
                    for (it.SeekToFirst(); it.Valid(); it.Next())
                    {
                        batch.Delete(it.Key());
                    }
                }
                db.Write(WriteOptions.Default, batch);
                Persist(GenesisBlock);
                db.Put(WriteOptions.Default, SliceBuilder.Begin(DataEntryPrefix.SYS_Version), GetType().GetTypeInfo().Assembly.GetName().Version.ToString());
            }
            thread_persistence      = new Thread(PersistBlocks);
            thread_persistence.Name = "LevelDBBlockchain.PersistBlocks";
            thread_persistence.Start();
        }
 public HasTemporaryLawfulStatusParser(IdentificationCard idCard, Version version, Country country) : base(idCard, version, country)
 {
 }
        /// <summary>
        /// Enumerate the gac and generate a list of assemblies which match the strongname by runtime.
        /// </summary>
        private static SortedDictionary <Version, SortedDictionary <AssemblyNameExtension, string> > GenerateListOfAssembliesByRuntime(string strongName, GetAssemblyRuntimeVersion getRuntimeVersion, Version targetedRuntime, FileExists fileExists, GetPathFromFusionName getPathFromFusionName, GetGacEnumerator getGacEnumerator, bool specificVersion)
        {
            ErrorUtilities.VerifyThrowArgumentNull(targetedRuntime, nameof(targetedRuntime));

            IEnumerable <AssemblyNameExtension> gacEnum = getGacEnumerator(strongName);

            // Dictionary of Runtime version (sorted in reverse order) to a list of assemblies which are part of that runtime. This will allow us to pick the highest runtime and version first.
            SortedDictionary <Version, SortedDictionary <AssemblyNameExtension, string> > assembliesWithValidRuntimes = new SortedDictionary <Version, SortedDictionary <AssemblyNameExtension, string> >(ReverseVersionGenericComparer.Comparer);

            // Enumerate the gac values returned based on the partial or full fusion name.
            if (gacEnum != null)
            {
                foreach (AssemblyNameExtension gacAssembly in gacEnum)
                {
                    // We only have a fusion name from the IAssemblyName interface we need to get the path to the assembly to resolve it and to check its runtime.
                    string assemblyPath = getPathFromFusionName(gacAssembly.FullName);

                    // Make sure we could get the path from the Fusion name and make sure the file actually exists.
                    if (!String.IsNullOrEmpty(assemblyPath) && fileExists(assemblyPath))
                    {
                        // Get the runtime version from the found assembly.
                        string runtimeVersionRaw = getRuntimeVersion(assemblyPath);

                        // Convert the runtime string to a version so we can properly compare them as per version object comparison rules.
                        // We will accept version which are less than or equal to the targeted runtime.
                        Version runtimeVersion = VersionUtilities.ConvertToVersion(runtimeVersionRaw);

                        // Make sure the targeted runtime is greater than or equal to the runtime version of the assembly we got from the gac.
                        if (runtimeVersion != null)
                        {
                            if (targetedRuntime.CompareTo(runtimeVersion) >= 0 || specificVersion)
                            {
                                SortedDictionary <AssemblyNameExtension, string> assembliesWithRuntime = null;
                                assembliesWithValidRuntimes.TryGetValue(runtimeVersion, out assembliesWithRuntime);

                                // Create a new list if one does not exist.
                                if (assembliesWithRuntime == null)
                                {
                                    assembliesWithRuntime = new SortedDictionary <AssemblyNameExtension, string>(AssemblyNameReverseVersionComparer.GenericComparer);
                                    assembliesWithValidRuntimes.Add(runtimeVersion, assembliesWithRuntime);
                                }

                                if (!assembliesWithRuntime.ContainsKey(gacAssembly))
                                {
                                    // Add the assembly to the list
                                    assembliesWithRuntime.Add(gacAssembly, assemblyPath);
                                }
                            }
                        }
                    }
                }
            }

            return(assembliesWithValidRuntimes);
        }
Example #53
0
 public override IEnumerable <ModuleUpdater> GetModuleUpdaters(IObjectSpace objectSpace, Version versionFromDB)
 {
     return(ModuleUpdater.EmptyModuleUpdaters);
 }
        /// <summary>
        /// Given a strong name, find its path in the GAC.
        /// </summary>
        /// <param name="assemblyName">The assembly name.</param>
        /// <param name="targetProcessorArchitecture">Like x86 or IA64\AMD64.</param>
        /// <returns>The path to the assembly. Empty if none exists.</returns>
        private static string GetLocationImpl(AssemblyNameExtension assemblyName, string targetProcessorArchitecture, GetAssemblyRuntimeVersion getRuntimeVersion, Version targetedRuntime, FileExists fileExists, GetPathFromFusionName getPathFromFusionName, GetGacEnumerator getGacEnumerator, bool specificVersion)
        {
            // Extra checks for PInvoke-destined data.
            ErrorUtilities.VerifyThrowArgumentNull(assemblyName, nameof(assemblyName));
            ErrorUtilities.VerifyThrow(assemblyName.FullName != null, "Got a null assembly name fullname.");

            string strongName = assemblyName.FullName;

            if (targetProcessorArchitecture != null && !assemblyName.HasProcessorArchitectureInFusionName)
            {
                strongName += ", ProcessorArchitecture=" + targetProcessorArchitecture;
            }

            string assemblyPath = String.Empty;

            // Dictionary sorted by Version in reverse order, this will give the values enumeration the highest runtime version first.
            SortedDictionary <Version, SortedDictionary <AssemblyNameExtension, string> > assembliesByRuntime = GenerateListOfAssembliesByRuntime(strongName, getRuntimeVersion, targetedRuntime, fileExists, getPathFromFusionName, getGacEnumerator, specificVersion);

            if (assembliesByRuntime != null)
            {
                foreach (SortedDictionary <AssemblyNameExtension, string> runtimeBucket in assembliesByRuntime.Values)
                {
                    // Grab the first element if there are one or more elements. This will give us the highest version assembly name.
                    if (runtimeBucket.Count > 0)
                    {
                        foreach (KeyValuePair <AssemblyNameExtension, string> kvp in runtimeBucket)
                        {
                            assemblyPath = kvp.Value;
                            break;
                        }

                        if (!String.IsNullOrEmpty(assemblyPath))
                        {
                            break;
                        }
                    }
                }
            }

            return(assemblyPath);
        }
Example #55
0
    static MsQuicApi()
    {
        if (OperatingSystem.IsWindows())
        {
            if (!IsWindowsVersionSupported())
            {
                if (NetEventSource.Log.IsEnabled())
                {
                    NetEventSource.Info(null, $"Current Windows version ({Environment.OSVersion}) is not supported by QUIC. Minimal supported version is {MinWindowsVersion}");
                }

                return;
            }

            Tls13ServerMayBeDisabled = IsTls13Disabled(true);
            Tls13ClientMayBeDisabled = IsTls13Disabled(false);
        }

        IntPtr msQuicHandle;

        if (NativeLibrary.TryLoad($"{Interop.Libraries.MsQuic}.{MsQuicVersion.Major}", typeof(MsQuicApi).Assembly, DllImportSearchPath.AssemblyDirectory, out msQuicHandle) ||
            NativeLibrary.TryLoad(Interop.Libraries.MsQuic, typeof(MsQuicApi).Assembly, DllImportSearchPath.AssemblyDirectory, out msQuicHandle))
        {
            try
            {
                if (NativeLibrary.TryGetExport(msQuicHandle, "MsQuicOpenVersion", out IntPtr msQuicOpenVersionAddress))
                {
                    QUIC_API_TABLE *apiTable;
                    delegate * unmanaged[Cdecl] < uint, QUIC_API_TABLE **, int > msQuicOpenVersion = (delegate * unmanaged[Cdecl] < uint, QUIC_API_TABLE **, int >)msQuicOpenVersionAddress;
                    if (StatusSucceeded(msQuicOpenVersion((uint)MsQuicVersion.Major, &apiTable)))
                    {
                        int   arraySize  = 4;
                        uint *libVersion = stackalloc uint[arraySize];
                        uint  size       = (uint)arraySize * sizeof(uint);
                        if (StatusSucceeded(apiTable->GetParam(null, QUIC_PARAM_GLOBAL_LIBRARY_VERSION, &size, libVersion)))
                        {
                            var version = new Version((int)libVersion[0], (int)libVersion[1], (int)libVersion[2], (int)libVersion[3]);
                            if (version >= MsQuicVersion)
                            {
                                Api             = new MsQuicApi(apiTable);
                                IsQuicSupported = true;
                            }
                            else
                            {
                                if (NetEventSource.Log.IsEnabled())
                                {
                                    NetEventSource.Info(null, $"Incompatible MsQuic library version '{version}', expecting '{MsQuicVersion}'");
                                }
                            }
                        }
                    }
                }
            }
            finally
            {
                if (!IsQuicSupported)
                {
                    NativeLibrary.Free(msQuicHandle);
                }
            }
        }
    }
Example #56
0
        /// <inheritdoc/>
        public StartServerResult StartServer(string adbPath, bool restartServerIfNewer)
        {
            var     serverStatus       = this.GetStatus();
            Version commandLineVersion = null;

            var commandLineClient = Factories.AdbCommandLineClientFactory(adbPath);

            if (commandLineClient.IsValidAdbFile(adbPath))
            {
                cachedAdbPath      = adbPath;
                commandLineVersion = commandLineClient.GetVersion();
            }

            // If the server is running, and no adb path is provided, check if we have the minimum
            // version
            if (adbPath == null)
            {
                if (!serverStatus.IsRunning)
                {
                    throw new AdbException("The adb server is not running, but no valid path to the adb.exe executable was provided. The adb server cannot be started.");
                }

                if (serverStatus.Version >= RequiredAdbVersion)
                {
                    return(StartServerResult.AlreadyRunning);
                }
                else
                {
                    throw new AdbException($"The adb deamon is running an outdated version ${commandLineVersion}, but not valid path to the adb.exe executable was provided. A more recent version of the adb server cannot be started.");
                }
            }

            if (serverStatus.IsRunning &&
                ((serverStatus.Version < RequiredAdbVersion) ||
                 ((serverStatus.Version < commandLineVersion) && restartServerIfNewer)))
            {
                if (adbPath == null)
                {
                    throw new ArgumentNullException(nameof(adbPath));
                }

                AdbClient.Instance.KillAdb();
                serverStatus.IsRunning = false;
                serverStatus.Version   = null;

                commandLineClient.StartServer();
                return(StartServerResult.RestartedOutdatedDaemon);
            }
            else if (!serverStatus.IsRunning)
            {
                if (adbPath == null)
                {
                    throw new ArgumentNullException(nameof(adbPath));
                }

                commandLineClient.StartServer();
                return(StartServerResult.Started);
            }
            else
            {
                return(StartServerResult.AlreadyRunning);
            }
        }
Example #57
0
        public (bool Success, List <PluginUpdateStatus> UpdatedPlugins) UpdatePlugins(bool dryRun = false)
        {
            Log.Information("Starting plugin update... dry:{0}", dryRun);

            var updatedList = new List <PluginUpdateStatus>();
            var hasError    = false;

            try {
                var pluginsDirectory = new DirectoryInfo(this.pluginDirectory);
                foreach (var installed in pluginsDirectory.GetDirectories())
                {
                    try {
                        var versions = installed.GetDirectories();

                        if (versions.Length == 0)
                        {
                            Log.Information("Has no versions: {0}", installed.FullName);
                            continue;
                        }

                        var sortedVersions = versions.OrderBy(dirInfo => {
                            var success = Version.TryParse(dirInfo.Name, out Version version);
                            if (!success)
                            {
                                Log.Debug("Unparseable version: {0}", dirInfo.Name);
                            }
                            return(version);
                        });
                        var latest = sortedVersions.Last();

                        var localInfoFile = new FileInfo(Path.Combine(latest.FullName, $"{installed.Name}.json"));

                        if (!localInfoFile.Exists)
                        {
                            Log.Information("Has no definition: {0}", localInfoFile.FullName);
                            continue;
                        }

                        var info = JsonConvert.DeserializeObject <PluginDefinition>(
                            File.ReadAllText(localInfoFile.FullName));

                        var remoteInfo = this.PluginMaster.FirstOrDefault(x => x.Name == info.Name);

                        if (remoteInfo == null)
                        {
                            Log.Information("Is not in pluginmaster: {0}", info.Name);
                            continue;
                        }

                        if (remoteInfo.DalamudApiLevel < PluginManager.DALAMUD_API_LEVEL)
                        {
                            Log.Information("Has not applicable API level: {0}", info.Name);
                            continue;
                        }

                        Version.TryParse(remoteInfo.AssemblyVersion, out Version remoteAssemblyVer);
                        Version.TryParse(info.AssemblyVersion, out Version localAssemblyVer);

                        var testingAvailable = false;
                        if (!string.IsNullOrEmpty(remoteInfo.TestingAssemblyVersion))
                        {
                            Version.TryParse(remoteInfo.TestingAssemblyVersion, out var testingAssemblyVer);
                            testingAvailable = testingAssemblyVer > localAssemblyVer && this.dalamud.Configuration.DoPluginTest;
                        }

                        if (remoteAssemblyVer > localAssemblyVer || testingAvailable)
                        {
                            Log.Information("Eligible for update: {0}", remoteInfo.InternalName);

                            // DisablePlugin() below immediately creates a .disabled file anyway, but will fail
                            // with an exception if we try to do it twice in row like this

                            if (!dryRun)
                            {
                                var wasEnabled =
                                    this.dalamud.PluginManager.Plugins.Where(x => x.Definition != null).Any(
                                        x => x.Definition.InternalName == info.InternalName);
                                ;

                                Log.Verbose("wasEnabled: {0}", wasEnabled);

                                // Try to disable plugin if it is loaded
                                if (wasEnabled)
                                {
                                    try {
                                        this.dalamud.PluginManager.DisablePlugin(info);
                                    }
                                    catch (Exception ex) {
                                        Log.Error(ex, "Plugin disable failed");
                                        //hasError = true;
                                    }
                                }

                                try {
                                    // Just to be safe
                                    foreach (var sortedVersion in sortedVersions)
                                    {
                                        var disabledFile =
                                            new FileInfo(Path.Combine(sortedVersion.FullName, ".disabled"));
                                        if (!disabledFile.Exists)
                                        {
                                            disabledFile.Create().Close();
                                        }
                                    }
                                } catch (Exception ex) {
                                    Log.Error(ex, "Plugin disable old versions failed");
                                }

                                var installSuccess = InstallPlugin(remoteInfo, wasEnabled, true, testingAvailable);

                                if (!installSuccess)
                                {
                                    Log.Error("InstallPlugin failed.");
                                    hasError = true;
                                }

                                updatedList.Add(new PluginUpdateStatus {
                                    InternalName = remoteInfo.InternalName,
                                    Name         = remoteInfo.Name,
                                    Version      = testingAvailable ? remoteInfo.TestingAssemblyVersion : remoteInfo.AssemblyVersion,
                                    WasUpdated   = installSuccess
                                });
                            }
                            else
                            {
                                updatedList.Add(new PluginUpdateStatus {
                                    InternalName = remoteInfo.InternalName,
                                    Name         = remoteInfo.Name,
                                    Version      = testingAvailable ? remoteInfo.TestingAssemblyVersion : remoteInfo.AssemblyVersion,
                                    WasUpdated   = true
                                });
                            }
                        }
                        else
                        {
                            Log.Information("Up to date: {0}", remoteInfo.InternalName);
                        }
                    } catch (Exception ex) {
                        Log.Error(ex, "Could not update plugin: {0}", installed.FullName);
                    }
                }
            }
            catch (Exception e) {
                Log.Error(e, "Plugin update failed.");
                hasError = true;
            }

            Log.Information("Plugin update OK.");

            return(!hasError, updatedList);
        }
Example #58
0
 /// <summary>
 ///     Write response status
 /// </summary>
 /// <param name="version">The Http version.</param>
 /// <param name="code">The HTTP status code.</param>
 /// <param name="description">The HTTP status description.</param>
 /// <param name="cancellationToken">Optional cancellation token for this async task.</param>
 /// <returns>The Task.</returns>
 internal Task WriteResponseStatusAsync(Version version, int code, string description,
                                        CancellationToken cancellationToken)
 {
     return(WriteLineAsync(Response.CreateResponseLine(version, code, description), cancellationToken));
 }
Example #59
0
        private static int GetFileFormatVersion(Version version)
        {
#warning TODO: file version acording to read version (current 2017.3.0f3)
            return(2);
        }
		internal HttpListenerRequest (HttpListenerContext context)
		{
			this.context = context;
			headers = new WebHeaderCollection ();
			input_stream = Stream.Null;
			version = HttpVersion.Version10;
		}