private static AbstractPersistentData Deserialize(string filePath, string importedBuildPath)
 {
     var deserializer = new IPersistentDataDeserializer[]
     {
         new PersistentDataDeserializerUpTo230(), new PersistentDataDeserializerCurrent()
     };
     var xmlString = File.ReadAllText(filePath);
     var version = SerializationUtils.XmlDeserializeString<XmlPersistentDataVersion>(xmlString).AppVersion;
     IPersistentDataDeserializer suitableDeserializer;
     if (version == null)
     {
         suitableDeserializer = deserializer.FirstOrDefault(c => c.MinimumDeserializableVersion == null);
     }
     else
     {
         var v = new Version(version);
         suitableDeserializer = deserializer.FirstOrDefault(c =>
             v.CompareTo(c.MinimumDeserializableVersion) >= 0
             && v.CompareTo(c.MaximumDeserializableVersion) <= 0);
     }
     if (suitableDeserializer == null)
     {
         throw new Exception(
             $"No converter available that can deserialize a PersistentData file with version {version}");
     }
     var data = new PersistentData(suitableDeserializer, importedBuildPath);
     suitableDeserializer.DeserializePersistentDataFile(xmlString);
     return data;
 }
Example #2
0
        /// <summary>
        /// Conditional function to determine whether the supplied version is greater than the one found online.
        /// </summary>
        /// <param name="Type">Translation file type. Can also be for the App itself.</param>
        /// <param name="LocalVersionString">Version string of the local file to check against</param>
        /// <returns></returns>
        public bool IsOnlineVersionGreater(TranslationType Type, string LocalVersionString)
        {
            if (VersionXML == null)
                return true;

            IEnumerable<XElement> Versions = VersionXML.Root.Descendants("Item");
            string ElementName = "Version";
            Version LocalVersion = new Version(LocalVersionString);

            switch (Type)
            {
                case TranslationType.App:
                    return LocalVersion.CompareTo(new Version(Versions.Where(x => x.Element("Name").Value.Equals("App")).FirstOrDefault().Element(ElementName).Value)) < 0;
                case TranslationType.Equipment:
                    return LocalVersion.CompareTo(new Version(Versions.Where(x => x.Element("Name").Value.Equals("Equipment")).FirstOrDefault().Element(ElementName).Value)) < 0;
                case TranslationType.Operations:
                case TranslationType.OperationSortie:
                case TranslationType.OperationMaps:
                    return LocalVersion.CompareTo(new Version(Versions.Where(x => x.Element("Name").Value.Equals("Operations")).FirstOrDefault().Element(ElementName).Value)) < 0;
                case TranslationType.Quests:
                case TranslationType.QuestDetail:
                case TranslationType.QuestTitle:
                    return LocalVersion.CompareTo(new Version(Versions.Where(x => x.Element("Name").Value.Equals("Quests")).FirstOrDefault().Element(ElementName).Value)) < 0;
                case TranslationType.Ships:
                    return LocalVersion.CompareTo(new Version(Versions.Where(x => x.Element("Name").Value.Equals("Ships")).FirstOrDefault().Element(ElementName).Value)) < 0;
                case TranslationType.ShipTypes:
                    return LocalVersion.CompareTo(new Version(Versions.Where(x => x.Element("Name").Value.Equals("ShipTypes")).FirstOrDefault().Element(ElementName).Value)) < 0;

            }

            return false;
        }
Example #3
0
        public static void TestCloneCompare(Assert assert)
        {
            assert.Expect(13);

            var v1 = new Version(1, 2, 3, (4 << 16) + 5);

            var o = v1.Clone();
            assert.Ok(o != null, "v1 Cloned");

            var v2 = o as Version;
            assert.Ok(v2 != null, "v1 Cloned as Version");

            assert.Equal(v2.Major, 1, "v2.Major 1");
            assert.Equal(v2.Minor, 2, "v2.Minor 2");
            assert.Equal(v2.Build, 3, "v2.Build 3");
            assert.Equal(v2.Revision, 262149, "v2.Revision  (4 << 16) + 5 = 262149");
            assert.Equal(v2.MajorRevision, 4, "v2.MajorRevision 4");
            assert.Equal(v2.MinorRevision, 5, "v2.MinorRevision 5");

            var v3 = new Version(1, 2, 2, (4 << 16) + 5);
            assert.Equal(v1.CompareTo(v3), 1, "v1.CompareTo(v3)");

            var v4 = new Version(1, 3, 3, (4 << 16) + 5);
            assert.Equal(v1.CompareTo(v4), -1, "v1.CompareTo(v4)");

            assert.Equal(v1.CompareTo(o), 0, "v1.CompareTo(o)");
            assert.Equal(v1.CompareTo(v2), 0, "v1.CompareTo(v2)");
            assert.NotEqual(v1.CompareTo(null), 0, "v1.CompareTo(null)");
        }
 public override bool IsSupportedVersion(Version version)
 {
     if (version == null) { return false; }
     var min = new Version("8.0");
     var max = new Version("8.1");
     if (version.CompareTo(min) != -1 && version.CompareTo(max) == -1)
     {
         return true;
     }
     return base.IsSupportedVersion(version);
 }
Example #5
0
    IEnumerator CheckForUpdate()
    {
        cfuStatus = "Checking for updates...";
        UnityWebRequest www = UnityWebRequest.Get("https://tripleaxis.net/test/psfxversion/");

        yield return(www.SendWebRequest());

        if (www.isNetworkError || www.isHttpError)
        {
            Debug.Log(www.error);
        }
        else
        {
            System.Version onlineVer  = new System.Version(www.downloadHandler.text);
            int            comparison = onlineVer.CompareTo(version);

            if (comparison < 0)
            {
                cfuStatus = "PSXEffects v" + version.ToString() + " - version ahead?!";
            }
            else if (comparison == 0)
            {
                cfuStatus = "PSXEffects v" + version.ToString() + " - up to date.";
            }
            else
            {
                cfuStatus = "PSXEffects v" + version.ToString() + " - update available (click to update).";
            }
        }
    }
Example #6
0
		private void FormCentralManager_Load(object sender,EventArgs e) {
			if(!GetConfigAndConnect()){
				return;
			}
			Cache.Refresh(InvalidType.Prefs);
			Version storedVersion=new Version(PrefC.GetString(PrefName.ProgramVersion));
			Version currentVersion=Assembly.GetAssembly(typeof(Db)).GetName().Version;
			if(storedVersion.CompareTo(currentVersion)!=0){
				MessageBox.Show(Lan.g(this,"Program version")+": "+currentVersion.ToString()+"\r\n"
					+Lan.g(this,"Database version")+": "+storedVersion.ToString()+"\r\n"
					+Lan.g(this,"Versions must match.  Please manually connect to the database through the main program in order to update the version."));
				Application.Exit();
				return;
			}
			if(PrefC.GetString(PrefName.CentralManagerPassHash)!=""){
				FormCentralPasswordCheck FormCPC=new FormCentralPasswordCheck();
				FormCPC.ShowDialog();
				if(FormCPC.DialogResult!=DialogResult.OK){
					Application.Exit();
					return;
				}
			}
			_listConnectionGroups=ConnectionGroups.GetListt();
			comboConnectionGroups.Items.Clear();
			comboConnectionGroups.Items.Add("All");
			for(int i=0;i<_listConnectionGroups.Count;i++) {
				comboConnectionGroups.Items.Add(_listConnectionGroups[i].Description);
			}
			comboConnectionGroups.SelectedIndex=0;//Select 'All' on load.
			FillGrid();
		}
Example #7
0
        public static string CompabilityText(Type type, string PluginToInstall, string PluginCompatible, string PluginName, System.Version currVersion, System.Version minVersion)
        {
            string result = string.Format(PluginToInstall, minVersion.ToString(), PluginName);

            try
            {
                if (type != null)
                {
                    if (currVersion.CompareTo(minVersion) >= 0)
                    {
                        result = string.Format(OtherPluginVersion, currVersion.ToString(), PluginName) + " " +
                                 PluginCompatible;
                    }
                    else
                    {
                        result = string.Format(OtherPluginVersion, currVersion.ToString(), PluginName) + " " +
                                 string.Format(PluginToInstall, minVersion.ToString(), PluginName);
                    }
                }
            }
            catch (Exception)
            {
            }
            return(result);
        }
 internal static void CompareToLatestVersion(Version CurrentVersionNumber)
 {
     if (CurrentVersionNumber.CompareTo(_LatestVersionNumber) < 0)
     {
         _NewerVersionAvailable = true;
     }
 }
        public static bool VerifyDotNet(out string message, Version assemblyDotNETVersion)
        {
            if (assemblyDotNETVersion == null)
            {
                message = "Invalid executing assembly.";
                return false;
            }

            message = "";
            try
            {
                Version maxVersion = GetMaxVersion();
                int compare = assemblyDotNETVersion.CompareTo(maxVersion);
                if (compare > 0)
                {
                    message = String.Format("You have an outdated version of the .NET framework (v{0}).\nPlease update to version {1}.",
                                            maxVersion, assemblyDotNETVersion);
                    return false;
                }
                return true;
            }
            catch (Exception ex)
            {
                message = ex.Message;
                return false;
            }
        }
		public static int CompareVersionsString(this string strA, string strB)
		{
			var vA = new Version(strA.Replace(",", "."));
			var vB = new Version(strB.Replace(",", "."));

			return vA.CompareTo(vB);
		}
Example #11
0
        public static bool HasNewerVersion(out string p_CurrentVersion, out string p_Version, out string p_ReleaseURL, out bool p_PreRelease)
        {
            var s_Assembly = Assembly.GetExecutingAssembly();
            var s_VersionInfo = FileVersionInfo.GetVersionInfo(s_Assembly.Location);
            p_CurrentVersion = s_VersionInfo.FileVersion.Trim();

            p_Version = p_CurrentVersion;
            p_ReleaseURL = null;
            p_PreRelease = false;

            var s_ReleaseData = GetLatestReleaseData();

            if (string.IsNullOrWhiteSpace(s_ReleaseData))
                return false;

            string s_LatestVersionString;
            if (!ParseReleaseData(s_ReleaseData, out s_LatestVersionString, out p_ReleaseURL, out p_PreRelease))
                return false;

            try
            {
                var s_CurrentVersion = new Version(p_CurrentVersion);
                var s_LatestVersion = new Version(s_LatestVersionString);

                p_Version = s_LatestVersionString;

                return s_LatestVersion.CompareTo(s_CurrentVersion) > 0;
            }
            catch (Exception)
            {
                return false;
            }
        }
        /// <summary>
        /// Returns whether the given constraint matches the desired version
        /// for the mod we're processing.
        /// </summary>
        private static bool ConstraintPasses(string op, Version version, Version desiredVersion)
        {
            switch (op)
            {
                case "":
                case "=":
                    return version.IsEqualTo(desiredVersion);

                case "<":
                    return version.IsLessThan(desiredVersion);

                case ">":
                    return version.IsGreaterThan(desiredVersion);

                case "<=":
                    return version.CompareTo(desiredVersion) <= 0;

                case ">=":
                    return version.CompareTo(desiredVersion) >= 0;

                default:
                    throw new Kraken(
                        string.Format("Unknown x_netkan_override comparator: {0}", op));
            }
        }
        // If you have an error here it is likely that you need to bulid your project with Platform Target x86.
        public MyGLControl(int bitDepth, int setencilDepth)
		//: base(new GraphicsMode(new ColorFormat(32), 32, 0, 4))
		{
            if (!checkedCapabilities)
            {
				try
				{
					IntPtr address = (this.Context as OpenTK.Graphics.IGraphicsContextInternal).GetAddress("glGenBuffers");

					string versionString = GL.GetString(StringName.Version);
					int firstSpace = versionString.IndexOf(' ');
					if (firstSpace != -1)
					{
						versionString = versionString.Substring(0, firstSpace);
					}

					Version openGLVersion = new Version(versionString);
					string glExtensionsString = GL.GetString(StringName.Extensions);
					bool extensionSupport = glExtensionsString.Contains("GL_ARB_vertex_attrib_binding");

					if (openGLVersion.CompareTo(new Version(2, 1)) < 0 && !extensionSupport)
					{
						MatterHackers.RenderOpenGl.OpenGl.GL.DisableGlBuffers();
					}
				}
				catch
				{
					MatterHackers.RenderOpenGl.OpenGl.GL.DisableGlBuffers();
				}

				checkedCapabilities = true;
            }
			Id = nextId++;
		}
		private string extractVersion(XmlDocument doc)
		{
			if (doc != null)
			{				
				XmlNamespaceManager nsManager = new XmlNamespaceManager(doc.NameTable);
				XmlNodeList nodes = doc.GetElementsByTagName("title");
				Version version = new Version();
				foreach (XmlNode node in nodes)
				{
					Regex versionRe = new Regex(@"d?nGREP\s+(?<version>[\d\.]+)\.\w+");

					if (versionRe.IsMatch(node.InnerText))
					{
						Version tempVersion = new Version(versionRe.Match(node.InnerText).Groups["version"].Value);
						if (version == null || version.CompareTo(tempVersion) < 0)
							version = tempVersion;
					}
				}
				return version.ToString();
			}
			else
			{
				return null;
			}
		}
Example #15
0
        /// <summary>
        /// Compare versions of form "1,2,3,4" or "1.2.3.4". Throws FormatException
        /// in case of invalid version.
        /// </summary>
        /// <param name="strA">the first version</param>
        /// <param name="strB">the second version</param>
        /// <returns>less than zero if strA is less than strB, equal to zero if
        /// strA equals strB, and greater than zero if strA is greater than strB</returns>
        public static int CompareVersions(String strA, String strB)
        {
            Version vA = new Version(strA.Replace(",", "."));
            Version vB = new Version(strB.Replace(",", "."));

            return vA.CompareTo(vB);
        }
		private void FormCentralManager_Load(object sender,EventArgs e) {
			IsStartingUp=true;
			if(!GetConfigAndConnect()){
				return;
			}
			Cache.Refresh(InvalidType.Prefs);
			Version storedVersion=new Version(PrefC.GetString(PrefName.ProgramVersion));
			Version currentVersion=Assembly.GetAssembly(typeof(Db)).GetName().Version;
			if(storedVersion.CompareTo(currentVersion)!=0){
				MessageBox.Show("Program version: "+currentVersion.ToString()+"\r\n"
					+"Database version: "+storedVersion.ToString()+"\r\n"
					+"Versions must match.  Please manually connect to the database through the main program in order to update the version.");
				Application.Exit();
				return;
			}
			if(PrefC.GetString(PrefName.CentralManagerPassHash)!=""){
				FormCentralPasswordCheck formC=new FormCentralPasswordCheck();
				formC.ShowDialog();
				if(formC.DialogResult!=DialogResult.OK){
					Application.Exit();
					return;
				}
			}
			FillGrid();
			IsStartingUp=false;
		}
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
        protected override void Work()
        {
            HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(_updateUrl);
            webReq.Method = "GET";

            webReq.ContentType = "text/plain; encoding='utf-8'";
            webReq.Proxy = base.WebProxy;

            IgnoreSSL();
            _response = (HttpWebResponse)webReq.GetResponse();
            _readStream = new StreamReader(_response.GetResponseStream());

            string responseVersion = _readStream.ReadLine();
            string responseUrl = _readStream.ReadLine();

            Version currentVersion = new Version(_version);
            Version updateVersion = new Version(responseVersion);

            int latestVersion = currentVersion.CompareTo(updateVersion);

            var updateArgs = (latestVersion < 0)
                ? new wsdlProcess.WebSvcAsync.EventParams.UpdateAsyncArgs(responseVersion, responseUrl)
                : new wsdlProcess.WebSvcAsync.EventParams.UpdateAsyncArgs();

            if (OnComplete != null) {
                OnComplete(this, updateArgs);
            }
        }
 private static SortedDictionary<Version, SortedDictionary<AssemblyNameExtension, string>> GenerateListOfAssembliesByRuntime(string strongName, GetAssemblyRuntimeVersion getRuntimeVersion, Version targetedRuntime, Microsoft.Build.Shared.FileExists fileExists, GetPathFromFusionName getPathFromFusionName, GetGacEnumerator getGacEnumerator, bool specificVersion)
 {
     Microsoft.Build.Shared.ErrorUtilities.VerifyThrowArgumentNull(targetedRuntime, "targetedRuntime");
     IEnumerable<AssemblyNameExtension> enumerable = getGacEnumerator(strongName);
     SortedDictionary<Version, SortedDictionary<AssemblyNameExtension, string>> dictionary = new SortedDictionary<Version, SortedDictionary<AssemblyNameExtension, string>>(ReverseVersionGenericComparer.Comparer);
     if (enumerable != null)
     {
         foreach (AssemblyNameExtension extension in enumerable)
         {
             string str = getPathFromFusionName(extension.FullName);
             if (!string.IsNullOrEmpty(str) && fileExists(str))
             {
                 Version version = VersionUtilities.ConvertToVersion(getRuntimeVersion(str));
                 if ((version != null) && ((targetedRuntime.CompareTo(version) >= 0) || specificVersion))
                 {
                     SortedDictionary<AssemblyNameExtension, string> dictionary2 = null;
                     dictionary.TryGetValue(version, out dictionary2);
                     if (dictionary2 == null)
                     {
                         dictionary2 = new SortedDictionary<AssemblyNameExtension, string>(AssemblyNameReverseVersionComparer.GenericComparer);
                         dictionary.Add(version, dictionary2);
                     }
                     if (!dictionary2.ContainsKey(extension))
                     {
                         dictionary2.Add(extension, str);
                     }
                 }
             }
         }
     }
     return dictionary;
 }
Example #20
0
        private void EmulatorLastVersionInfoRetrieved(object sender, EventArgs e)
        {
            Version currentEmulatorVersion = null;
            Version lastEmulatorVersion = null;

            menuItemUpdateEmulator.Enabled = true;
            progressCheckingLastVersion.Visible = false;

            if (Global.CurrentEmulatorVersion.Equals("N/A"))
            {
                labelNewVersionAvailable.BackColor = Color.Red;
                labelNewVersionAvailable.Text = "No se encontró el emulador WinUAE. Es neceario actualizar.";
            }
            else
            {
                currentEmulatorVersion = new Version(Global.CurrentEmulatorVersion);
                lastEmulatorVersion = new Version(Global.LastEmulatorVersion);

                if (currentEmulatorVersion.CompareTo(lastEmulatorVersion) < 0)
                {
                    labelNewVersionAvailable.BackColor = Color.LightGreen;
                    labelNewVersionAvailable.Text = "Hay una versión más actual del emulador.";
                }
                else
                {
                    labelNewVersionAvailable.Text = "El emulador está actualizado.";
                }
            }
        }
Example #21
0
        static void Main()
        {
            if (!SysUtils.IsSingleInstance(Config.Mutex))
            {
                foreach (Process p in Process.GetProcessesByName(Process.GetCurrentProcess().ProcessName))
                {
                    FileVersionInfo myFileVersionInfo = FileVersionInfo.GetVersionInfo(p.MainModule.FileName);
                    Version v1 = new Version(myFileVersionInfo.FileVersion.ToString());
                    Version v2 = new Version(Config.Version);

                    int result = v1.CompareTo(v2);

                    //if already running version is greater than this, exit this app
                    if (result > 0) Environment.Exit(-1);

                    if (result < 0)
                    {
                        p.Kill();
                        //new Installation(Config.FileName, Config.RegistryName).Install();
                        CmdHandler.Run();
                    }
                }
            }
            else
            {
                //this run for the first instance of the program
                CmdHandler.Run();
            }
        }
        static void displayUpdateInfo(string remoteVersionString, string localVersionString) {
            var remoteVersion = new Version(remoteVersionString);
            var localVersion = new Version(localVersionString);

            switch (remoteVersion.CompareTo(localVersion)) {
                case 1:
                    if (EditorUtility.DisplayDialog("Entitas Update",
                            string.Format("A newer version of Entitas is available!\n\n" +
                            "Currently installed version: {0}\n" +
                            "New version: {1}", localVersion, remoteVersion),
                            "Show release",
                            "Cancel"
                        )) {
                        Application.OpenURL(URL_GITHUB_RELEASES);
                    }
                    break;
                case 0:
                    EditorUtility.DisplayDialog("Entitas Update",
                        "Entitas is up to date (" + localVersionString + ")",
                        "Ok"
                    );
                    break;
                case -1:
                    if (EditorUtility.DisplayDialog("Entitas Update",
                            string.Format("Your Entitas version seems to be newer than the latest release?!?\n\n" +
                            "Currently installed version: {0}\n" +
                            "Latest release: {1}", localVersion, remoteVersion),
                            "Show release",
                            "Cancel"
                        )) {
                        Application.OpenURL(URL_GITHUB_RELEASES);
                    }
                    break;
            }
        }
Example #23
0
        public static void Check(string oldVersionStr)
        {
            try
            {
                var newVersionStr = new WebClient().DownloadString(new Uri(versionUrl));

                var newVersion = new Version(newVersionStr);
                var oldVersion = new Version(oldVersionStr);

                if(newVersion.CompareTo(oldVersion) > 0)
                {
                    var result = MessageBox.Show(
                        string.Format(
                            "Version {0} is available for download. You are running version {1}." +
                            Environment.NewLine + "Would you like to be sent to the download page?",
                            newVersion, oldVersion
                        ),

                        "New Version Available", MessageBoxButtons.YesNo, MessageBoxIcon.Question
                    );

                    if(result == DialogResult.Yes)
                        Process.Start(downloadPageUrl);
                }
            }
            catch
            {
                /* Suppress */
            }
        }
Example #24
0
        private void checkForUpdates()
        {
            List<String> folders = new List<String>();
            var latestVersion = new Version("0.0");
            latestVersion = new Version(Math.Max(0, latestVersion.Major), Math.Max(0, latestVersion.Minor), Math.Max(0, latestVersion.Build), Math.Max(0, latestVersion.Revision));

            foreach (string subFolderPath in Directory.GetDirectories(launcherDirPath, "*", SearchOption.TopDirectoryOnly))
            {
                Console.WriteLine(subFolderPath);
                string fullPath = Path.GetFullPath(subFolderPath).TrimEnd(Path.DirectorySeparatorChar);
                string subFolderName = Path.GetFileName(fullPath);
                Console.WriteLine(subFolderName);

                var subFolderVersion = new Version(subFolderName);
                subFolderVersion = new Version(Math.Max(0, subFolderVersion.Major), Math.Max(0, subFolderVersion.Minor), Math.Max(0, subFolderVersion.Build), Math.Max(0, subFolderVersion.Revision));

                var result = latestVersion.CompareTo(subFolderVersion);
                if (result > 0)
                {
                    Console.WriteLine("latestVersion is greater");
                }
                else if (result < 0)
                {
                    Console.WriteLine("subFolderName is greater");
                    latestVersion = subFolderVersion;
                }
                else
                {
                    Console.WriteLine("versions are equal");
                }
            }
            Console.WriteLine(latestVersion);
        }
Example #25
0
        /// <summary>
        /// Updates the init button description and functionality.
        /// </summary>
        private void initUpdateButton()
        {
            if (this.dkimSignerInstalled != null && this.dkimSignerAvailable != null)
            {
                if (dkimSignerInstalled.CompareTo(dkimSignerAvailable.Version) > 0)
                {
                    updateButtonType       = UpdateButtonType.Downgrade;
                    btUpateInstall.Text    = "Downgrade";
                    btUpateInstall.Enabled = true;
                }
                else if (dkimSignerInstalled.CompareTo(dkimSignerAvailable.Version) == 0)
                {
                    updateButtonType       = UpdateButtonType.Install;
                    btUpateInstall.Text    = "Reinstall";
                    btUpateInstall.Enabled = true;
                }
                else
                {
                    updateButtonType       = UpdateButtonType.Upgrade;
                    btUpateInstall.Text    = "Upgrade";
                    btUpateInstall.Enabled = true;
                }
            }
            else if (this.dkimSignerInstalled == null && this.dkimSignerAvailable != null)
            {
                updateButtonType       = UpdateButtonType.Install;
                btUpateInstall.Text    = "Install";
                btUpateInstall.Enabled = true;
            }
            else
            {
                updateButtonType       = UpdateButtonType.Disabled;
                btUpateInstall.Text    = "Update";
                btUpateInstall.Enabled = false;
            }

            if (this.dkimSignerInstalled != null)
            {
                btUninstall.Enabled = true;
                btUninstall.Text    = "Uninstall";
            }
            else
            {
                btUninstall.Enabled = false;
                btUninstall.Text    = "Uninstall";
            }
        }
        public Dictionary<string, object> CheckForUpdates(Version currentVersion)
        {
            var results = new Dictionary<string, object> {{"Available", false}, {"DownloadLink", null}};
            var downloalUrl = "";
            Version newVersion = null;
            const string xmlUrl = "C://VebBrowserUpdates//update.xml";
            var reader = new XmlTextReader(xmlUrl);
            try
            {
                reader.MoveToContent();
                var elementName = "";
                if ((reader.NodeType == XmlNodeType.Element) && (reader.Name == "VoiceBrowser"))
                {
                    while (reader.Read())
                    {
                        if (reader.NodeType == XmlNodeType.Element)
                            elementName = reader.Name;
                        else if ((reader.NodeType == XmlNodeType.Text) && (reader.HasValue))
                        {
                            switch (elementName)
                            {
                                case "version":
                                    {
                                        newVersion = new Version(reader.Value);
                                        break;
                                    }
                                case "url":
                                    {
                                        downloalUrl = reader.Value;
                                        break;
                                    }
                            }
                        }
                    }
                }
                // how to get the version of an application
                //Version currentVersion = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;

                if (currentVersion.CompareTo(newVersion) < 0)
                {
                    results["Available"] = true;
                    results["url"] = downloalUrl;
                }
                else
                {
                    results["Available"] = false;
                    results["url"] = "";
                }
            }
            catch
            {
                throw;
            }
            finally
            {
                reader.Close();
            }
            return results;
        }
 public static bool IsGreaterThanCu10()
 {
     var minimumVersion = new Version("11.2.4409.10");
     var assembly = Assembly.LoadFile(string.Format(@"{0}\{1}", AppDomain.CurrentDomain.BaseDirectory, "SDLTradosStudio.exe"));
     var versionInfo = FileVersionInfo.GetVersionInfo(assembly.Location);
     var currentVersion = new Version(versionInfo.FileVersion);
     return currentVersion.CompareTo(minimumVersion) >= 0;
 }
Example #28
0
 private static bool NeedsUpdate(string versionURL, Version runningVersion)
 {
     using (XmlTextReader reader = new XmlTextReader(versionURL)) {
         XmlDocument xmlDoc = new XmlDocument();
         xmlDoc.Load(reader);
         Version newestVersion = new Version(xmlDoc.ChildNodes[1].ChildNodes[0].Value);
         return newestVersion.CompareTo(runningVersion) > 0;
     }
 }
Example #29
0
        /// <summary>
        /// Locates the installed Java version and loads a JVM.  If no suitable JVM can be found
        /// a MajalaExeption will be thrown.
        /// </summary>
        /// <param name="minVersion">Minimum Java Version required.</param>
        /// <param name="maxVersion">Maximum Java Version allowed (or an empty String).</param>
        /// <returns>Jvm object with a suitable loaded JVM.</returns>
        private static Jvm LocateAndLoadInstalledJvm(string minVersion, string maxVersion)
        {
            JvmCollection jvmCollection = new JvmCollection();
            Version minRequiredVersion = new Version(minVersion);
            Version maxRequiredVersion = maxVersion.Length > 0 ? new Version(maxVersion) : null;

            if (maxVersion.Length == 0)
                Logger.Log(string.Format(CultureInfo.CurrentCulture, Resources.LogRequiredJvmV1, minVersion));
            else
                Logger.Log(string.Format(CultureInfo.CurrentCulture, Resources.LogRequiredJvmV2, maxVersion));

            int bits = SystemHelper.ProcessBitness();
            if (jvmCollection.InstalledVersions.Count == 0)
                throw new MajalaException(string.Format(CultureInfo.CurrentCulture, Resources.NoSuitableJavaFoundV1, bits));

            foreach (KeyValuePair<string, string> p in jvmCollection.InstalledVersions)
            {
                string path = p.Key;
                string version = p.Value;
                Version currentVersion = new Version(version);

                if (currentVersion.CompareTo(minRequiredVersion) >= 0)
                {
                    if (maxVersion.Length == 0 || currentVersion.CompareTo(maxRequiredVersion) <= 0)
                    {
                        Logger.Log(string.Format(CultureInfo.CurrentCulture, Resources.LogJvmIsOk, currentVersion));
                        return new Jvm(path);
                    }
                    else
                    {
                        Logger.Log(string.Format(CultureInfo.CurrentCulture, Resources.LogJvmIsTooYoung, currentVersion));
                    }
                }
                else
                {
                    Logger.Log(string.Format(CultureInfo.CurrentCulture, Resources.LogJvmIsTooOld, currentVersion));
                }
            }

            if (maxVersion.Length == 0)
                throw new MajalaException(string.Format(CultureInfo.CurrentCulture, Resources.NoSuitableJavaFoundV2, bits, minVersion));
            else
                throw new MajalaException(string.Format(CultureInfo.CurrentCulture, Resources.NoSuitableJavaFoundV3, bits, minVersion, maxVersion));
        }
Example #30
0
        public async Task<APPXVersion> CheckForUpdates()
        {
            try
            {
                string localVersion = Properties.Settings.Default.CurrentVersion;
                string localRelease = Properties.Settings.Default.CurrentRelease;

                HttpClient client = new HttpClient();
                string response = await client.GetStringAsync(uri);
                var newAPPXVersion = JsonConvert.DeserializeObject<APPXVersion>(response);

                Version current = new Version(localVersion);
                Version recent = new Version(newAPPXVersion.VersionNumber);

                if (recent.CompareTo(current) < 0)
                {
                    //No new Versions Available
                    return null;
                }
                else if (recent.CompareTo(current) == 0)
                {
                    //If Zero, it may be the same version, but different Release.
                    ReleaseType localRS = (ReleaseType)Enum.Parse(typeof(ReleaseType), localRelease, true);
                    ReleaseType remoteRS = (ReleaseType)Enum.Parse(typeof(ReleaseType), newAPPXVersion.Release, true);
                    //Check if it's greater than our release type
                    if (localRS >= remoteRS)
                    {
                        //The same version
                        //Do we have the local file?.
                        if (File.Exists($"Res\\{newAPPXVersion.FileName}"))
                            return null; //Yup
                        //Nope, continue and download the file.
                    }
                }

                //Passes all the checks NEW VERSION AVAILABLE!
                return newAPPXVersion; // return the new object.
            }
            catch (Exception)
            {
                return null;
            }
        }
Example #31
0
        public void CompareTo_SimpleString()
        {
            DbVersion lowDbVersion = new DbVersion(0, 0, 0, 0);
            DbVersion highDbVersion = new DbVersion(0, 0, 0, 1);

            Version lowVersion = new Version(lowDbVersion.VersionString);
            Version highVersion = new Version(highDbVersion.VersionString);

            Assert.IsTrue(lowVersion.CompareTo(highVersion) < 0);
        }
Example #32
0
        public Boolean UpdateSuccessful()
        {
            Version currentVersion = new Version( _currentVersionProvider.GetVersion());
            Version serverVersion = new Version(_serverVersionProvider.GetVersion());

            if (currentVersion.CompareTo(serverVersion) < 0)
            {
                return _updateResolver.ResolveUpdate();
            }
            else
            {
                return true;
            }
        }
        public static ActionResult RegisterAscomDriver(Session session)
        {
            try
            {
            #if DEBUG
                System.Windows.Forms.MessageBox.Show("Starting ASCOM Registration");
            #endif
                session.Log("Begin RegisterAscomDriver");
                EventLogger.LoggingLevel = TraceLevel.Info;
                EventLogger.LogMessage("Begin RegisterAscomDriver", TraceLevel.Info);
                Trace.WriteLine("Begin RegisterAscomDriver custom action");

                // Check for platform 5.5 or greater
                EventLogger.LogMessage("Searching for ASCOM Platform 5.5 or later", TraceLevel.Info);
                bool platformFound = false;
                string utilitiesFilePath = System.Environment.GetFolderPath(Environment.SpecialFolder.CommonProgramFiles)
                     + "\\ASCOM\\.net\\ASCOM.Utilities.dll";
                if(File.Exists(utilitiesFilePath))
                {
                    string utilVersionS = FileVersionInfo.GetVersionInfo(utilitiesFilePath).ProductVersion;
                    Trace.WriteLine("ASCOM.Utilities.dll version is " + utilVersionS);
                    Version utilVersion = new Version(utilVersionS);
                    platformFound = (utilVersion.CompareTo(new Version("5.5.0.0")) >= 0) ? true : false;
                }

                if (!platformFound)
                {
                    EventLogger.LogMessage("ASCOM Platform 5.5 or later was not found on target machine.", TraceLevel.Info);
                    System.Windows.Forms.MessageBox.Show("The installation of this software cannot continue because " +
                        "the ASCOM Platform 5.5 or later is not installed. Please install it from www.ascom-standards.org and " +
                        "try again. Optionally, you can run the installation with the ASCOM driver feature disabled.", "ASCOM Platform Not Found");
                    return ActionResult.Failure;    // This will roll-back the install
                }
                EventLogger.LogMessage("ASCOM Platform 5.5 or later found on target machine.", TraceLevel.Info);
                Type type = typeof(ASCOM.OptecTCF_S.Focuser);
                ASCOM.OptecTCF_S.Focuser.RegisterASCOM(type);
                Trace.WriteLine("RegisterAscomDriver Succeeded!");
                return ActionResult.Success;
            }
            catch (Exception ex)
            {
               Trace.WriteLine("RegisterAscomDriver failed: " + ex.Message);
            #if DEBUG
                ActionResult.Failure;           // FAIL when debugging only
            #else
                return ActionResult.Success;    // ALWAYS return success so that program can be uninstalled
            #endif
            }
        }
Example #34
0
        public IEnumerable <DependenciesResponse> Get()
        {
            List <DependenciesResponse> response = new List <DependenciesResponse>();

            var dependencies = SquidStore.Dependencies.Values;

            foreach (var dep in dependencies)
            {
                DependenciesResponse depResponse = new DependenciesResponse();
                depResponse.Repository          = dep.Repository;
                depResponse.PackageDependencies = dep.PackageDependencies;
                depResponse.Updates             = new List <Update>();

                foreach (var dependency in depResponse.PackageDependencies)
                {
                    if (SquidStore.Packages.ContainsKey(dependency.PackageId))
                    {
                        var package = SquidStore.Packages[dependency.PackageId];
                        dependency.LatestVersion = package.version;
                        dependency.FeedId        = package.FeedId;
                        dependency.FeedName      = package.FeedName;

                        var cleanCurrentVersion = dependency.Version.Split('-').First();
                        var cleanLatestVersion  = dependency.Version.Split('-').First();

                        var currentVersion = new System.Version(cleanCurrentVersion);
                        var latestVersion  = new System.Version(cleanLatestVersion);

                        if (currentVersion.CompareTo(latestVersion) > 0)
                        {
                            depResponse.Updates.Add(new Update()
                            {
                                PackageId = package.id,
                                Version   = package.version
                            });
                        }
                    }
                }

                response.Add(depResponse);
            }

            return(response);
        }
Example #35
0
        public int CompareTo(AbstractVersion other)
        {
            bool otherIsNull = (object)other == null || (object)other.version == null;
            bool thisIsNull  = (object)version == null;

            if (otherIsNull && thisIsNull)
            {
                return(0);
            }
            if (otherIsNull)
            {
                return(1);
            }
            if (thisIsNull)
            {
                return(-1);
            }
            return(version.CompareTo(other.version));
        }
Example #36
0
        private async void CheckUpdate()
        {
            var p = await AppVersion.GetVersionOnServer();

            if (p == null)
            {
                return;
            }
            var serverVersion = new System.Version(Encoding.UTF8.GetString(p));
            var localVersion  = new System.Version(Application.ProductVersion);

            if (serverVersion.CompareTo(localVersion) > 0)
            {
                tsUpdate.BeginInvoke(new Action(() => {
                    labLastVersion.Text = string.Format(labLastVersion.Text, serverVersion.ToString());
                    tsUpdate.Visible    = true;
                }));
            }
        }
Example #37
0
        private void VerifyRequiredAGSVersion(Type mainClass)
        {
            object[] attributes = mainClass.GetCustomAttributes(typeof(RequiredAGSVersionAttribute), true);
            if (attributes.Length != 1)
            {
                throw new AGSEditorException("Plugin class does not have RequiredAGSVersion attribute");
            }
            string pluginVersionNumber = ((RequiredAGSVersionAttribute)attributes[0]).RequiredVersion;

            if (!Regex.IsMatch(pluginVersionNumber, Settings.REGEX_FOUR_PART_VERSION))
            {
                throw new AGSEditorException("Plugin returned invalid version number: must be in format  a.b.c.d");
            }

            System.Version pluginVersion = new System.Version(pluginVersionNumber);
            System.Version editorVersion = new System.Version(AGS.Types.Version.AGS_EDITOR_VERSION);
            if (pluginVersion.CompareTo(editorVersion) > 0)
            {
                throw new AGSEditorException("Plugin requires a newer version of AGS (" + pluginVersion.ToString() + ")");
            }
        }
Example #38
0
        static void CheckForUpdate()
        {
            string repoURL = "https://api.github.com/repos/prashant-singh/project-wizard/releases";
            WWW    www     = new WWW(repoURL);

            while (!www.isDone)
            {
                ;
            }
            if (www.isDone)
            {
                var        modifiedResponse = "{\"repos\":" + www.text + "}";
                GitReponse m_gitRepo        = JsonUtility.FromJson <GitReponse>(modifiedResponse);
                bool       hasUpdate        = false;
                string     newVersion       = "";
                string     downloadURL      = "";
                for (int count = 0; count < m_gitRepo.repos.Count; count++)
                {
                    var version1 = new System.Version(m_gitRepo.repos[count].tag_name);
                    var version2 = new System.Version(toolVersion);

                    var result = version1.CompareTo(version2);
                    if (result > 0)
                    {
                        newVersion = m_gitRepo.repos[count].tag_name;
                        hasUpdate  = true;
                        break;
                    }
                }
                if (hasUpdate)
                {
                    bool selectedOp = EditorUtility.DisplayDialog("Update Available!", "Version " + newVersion + " available to download.", "Update", "Cancel");
                    if (selectedOp)
                    {
                        downloadURL = "https://github.com/googleads/googleads-mobile-unity/releases/download/v3.15.1/GoogleMobileAds.unitypackage";
                        DownloadNewPackage(downloadURL, newVersion);
                    }
                }
            }
        }
Example #39
0
    /// <summary>
    /// Compares the versions of the feature on server and installed
    /// </summary>
    /// <param name="serverVersion"></param>
    /// <param name="currentVersion"></param>
    /// <returns></returns>
    bool VersionCheck(string serverVersion, string currentVersion)
    {
        try
        {
            var app_ver      = new System.Version(serverVersion);
            var curr_app_ver = new System.Version(currentVersion);

            var result = app_ver.CompareTo(curr_app_ver);
            if (result > 0)
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
        catch (Exception e) {
            Debug.LogException(e);
            return(false);
        }
    }
Example #40
0
    //自信のVerと指定したVerを比較。異なればtrue。
    bool VersionComparative(string storeVersionText)
    {
        if (string.IsNullOrEmpty(storeVersionText))
        {
            return(false);
        }
        try
        {
            var storeVersion   = new System.Version(storeVersionText);
            var currentVersion = new System.Version(Application.version);

            if (storeVersion.CompareTo(currentVersion) > 0)
            {
                return(true);
            }
        }
        catch (Exception e)
        {
            Debug.LogErrorFormat("{0} VersionComparative Exception caught.", e);
        }

        return(false);
    }
Example #41
0
        /// <summary>
        /// VersionInformation.LatestVersionが通知スキップ対象バージョンかどうかチェックする。trueならスキップ対象バージョン。
        /// </summary>
        /// <param name="settings"></param>
        /// <param name="versionInformation"></param>
        private static bool CheckIfSkipUpdate(PluginUpdateNotifierSettings settings, VersionInformation versionInformation)
        {
            // SkipVersionの値が空白の時はスキップしない。
            if (string.IsNullOrEmpty(settings.SkipVersion))
            {
                return(false);
            }

            // なんらかの理由でSkipVersionが不適切な値だった場合はスキップしない。
            if (!Utility.IsVersionString(settings.SkipVersion))
            {
                return(false);
            }

            System.Version skipVersion   = new System.Version(settings.SkipVersion);
            System.Version latestVersion = new System.Version(versionInformation.LatestVersion);
            // LatestVersionとSkipVersionが同一でないならスキップしない。
            if (skipVersion.CompareTo(latestVersion) != 0)
            {
                return(false);
            }

            return(true);
        }
Example #42
0
    public void ShowMessage(string gameName, string currentVersion, System.Action <bool, string> callback)
    {
        restApi.ResourceAt(SConstants.CheckVersionUrl + gameName)
        .Get(response => {
            if (response != null && !response.HasError)
            {
                if (response.Resource != null)
                {
//						Hashtable data = (Hashtable)response.Resource["data"];

                    SMessageResult result = new SMessageResult(response.Resource);
                    if (result.ShouldShow)
                    {
                        switch (result.Condition)
                        {
                        case SMessageCondition.CheckVersion:
                            var ver1 = new System.Version(currentVersion);
                            var ver2 = new System.Version(result.Version);

                            var compareResult = ver2.CompareTo(ver1);


                            if (compareResult > 0)
                            {
                                MobileNativeDialog dialog = new MobileNativeDialog(result.Title, result.MessageDialog, "OK", "Cancel");
                                dialog.OnComplete        += OnDialogClose;

                                                                        #if UNITY_IOS
                                this.ActionURL = result.iOSAction;
                                                                        #elif UNITY_ANDROID
                                this.ActionURL = result.AndroidAction;
                                                                        #elif UNITY_WP8 || UNITY_WP8_1
                                this.ActionURL = result.WPAction;
                                                                        #endif

                                callback(true, "Show Message");
                            }
                            break;

                        case SMessageCondition.UnCheckVersion:

                            MobileNativeDialog dialogMessage = new MobileNativeDialog(result.Title, result.MessageDialog, "OK", "Cancel");
                            dialogMessage.OnComplete        += OnDialogClose;

                                                                #if UNITY_IOS
                            this.ActionURL = result.iOSAction;
                                                                #elif UNITY_ANDROID
                            this.ActionURL = result.AndroidAction;
                                                                #elif UNITY_WP8 || UNITY_WP8_1
                            this.ActionURL = result.WPAction;
                                                                #endif

                            callback(true, "Show Message");
                            break;
                        }
                    }
                    else
                    {
                        callback(false, "Not show popup.");
                    }
                }
                else
                {
                    callback(false, "Null response.");
                }
            }
            else
            {
                callback(false, "Cannot handle response.");
            }
        });
    }
Example #43
0
        private static string GetPythonPath(string requiredVersion = "", string maxVersion = "")
        {
            string[] possiblePythonLocations = new string[3] {
                @"HKLM\SOFTWARE\Python\PythonCore\",
                @"HKCU\SOFTWARE\Python\PythonCore\",
                @"HKLM\SOFTWARE\Wow6432Node\Python\PythonCore\"
            };


            Dictionary <string, string> pythonLocations = new Dictionary <string, string>();

            foreach (string possibleLocation in possiblePythonLocations)
            {
                string regKey = possibleLocation.Substring(0, 4), actualPath = possibleLocation.Substring(5);

                using (var theKey = RegistryKey.OpenBaseKey(regKey == "HKLM" ? RegistryHive.LocalMachine : RegistryHive.CurrentUser, RegistryView.Registry64))
                {
                    RegistryKey theValue = theKey.OpenSubKey(actualPath);

                    foreach (var v in theValue.GetSubKeyNames())
                    {
                        RegistryKey productKey = theValue.OpenSubKey(v);
                        if (productKey != null)
                        {
                            try
                            {
                                if (productKey.OpenSubKey("InstallPath") != null && productKey.OpenSubKey("InstallPath").GetValue("ExecutablePath") != null)
                                {
                                    string pythonExePath = productKey.OpenSubKey("InstallPath").GetValue("ExecutablePath").ToString();
                                    if (pythonExePath != null && pythonExePath != "")
                                    {
                                        pythonLocations.Add(v.ToString(), pythonExePath);
                                    }
                                }
                            }
                            catch
                            {
                            }
                        }
                    }
                }
            }
            if (pythonLocations.Count > 0)
            {
                System.Version desiredVersion = new System.Version(requiredVersion == "" ? "0.0.1" : requiredVersion),
                               maxPVersion    = new System.Version(maxVersion == "" ? "999.999.999" : maxVersion);

                string highestVersion = "", highestVersionPath = "";

                foreach (KeyValuePair <string, string> pVersion in pythonLocations)
                {
                    int    index            = pVersion.Key.IndexOf("-");
                    string formattedVersion = index > 0 ? pVersion.Key.Substring(0, index) : pVersion.Key;

                    System.Version thisVersion   = new System.Version(formattedVersion);
                    int            comparison    = desiredVersion.CompareTo(thisVersion),
                                   maxComparison = maxPVersion.CompareTo(thisVersion);

                    if (comparison <= 0)
                    {
                        if (maxComparison >= 0)
                        {
                            desiredVersion = thisVersion;

                            highestVersion     = pVersion.Key;
                            highestVersionPath = pVersion.Value;
                        }
                        else
                        {
                        }
                    }
                    else
                    {
                    }
                }

                return(highestVersionPath);
            }

            return("");
        }
        public static void Versioncheck2(bool aktuelhinweis = true)
        {
            // in newVersion variable we will store the version info from xml file
            System.Version newVersion = null;
            string         updateUrl  = "";

            XmlDocument doc = new XmlDocument();

            try
            {
                // provide the XmlTextReader with the URL of our xml document
                string         xmlURL = "http://web.FreeScoreBoard.org/download/version.xml";
                HttpWebRequest rq     = (HttpWebRequest)WebRequest.Create(xmlURL);
                rq.Timeout = 5000;
                HttpWebResponse response = rq.GetResponse() as HttpWebResponse;

                using (Stream responseStream = response.GetResponseStream())
                {
                    XmlTextReader reader = new XmlTextReader(responseStream);
                    doc.Load(reader);
                }

                XmlElement root = doc.DocumentElement;

                foreach (XmlNode node in root.ChildNodes)
                {
                    switch (node.Name)
                    {
                    case "version":
                        // thats why we keep the version info
                        // in xxx.xxx.xxx.xxx format
                        // the Version class does the parsing for us
                        newVersion = new System.Version(node.InnerText);
                        break;

                    case "url":
                        updateUrl = node.InnerText;
                        break;
                    }
                }

                // get the running version
                System.Version curVersion = Assembly.GetExecutingAssembly().GetName().Version;
                // compare the versions
                if (curVersion.CompareTo(newVersion) < 0)
                {
                    // ask the user if he would like to download the new version
                    ////if (ClsTranslateControls.AskMessage("M0011", "Versionscheck", new object[] { "\n", newVersion.ToString() }, MessageBoxButtons.YesNo) == DialogResult.Yes)
                    {
                        // navigate the default web browser to our app
                        // homepage (the url comes from the xml content)
                        System.Diagnostics.Process.Start(updateUrl);
                    }
                }
                else
                {
                    if (aktuelhinweis == true)
                    {
                        ////ClsTranslateControls.ShowMessage("M0012", "Versionscheck", new object[] { "\n" }, MessageBoxButtons.OK);
                        // MessageBox.Show("Die Software ist auf dem neusten Stand.", "Versionscheck...");
                    }
                }
            }
            catch (Exception)
            {
                if (aktuelhinweis == true)
                {
                    ////ClsTranslateControls.ShowMessage("M0013", "Versionscheck", new object[] { "\n" }, MessageBoxButtons.OK);
                    // MessageBox.Show("Bei der Versionsprüfung ist ein Fehler aufgetreten.\nPrüfen Sie Ihre Internetverbindung.", "Versionscheck...");
                }
            }
        }
Example #45
0
 /// <summary>
 /// Determines if the minimum IIS version is installed on the machine.
 /// </summary>
 /// <param name="machineName">Machine to test if IIS version is installed.</param>
 /// <returns>True if installed, false if not.</returns>
 public static bool IsMinimumIISVersionInstalled(string machineName, int iisMajorVersion, int iisMinorVersion)
 {
     System.Version installedVersion = GetInstalledIISVersion(machineName);
     return(installedVersion.CompareTo(new System.Version(iisMajorVersion, iisMinorVersion)) >= 0);
 }
Example #46
0
        ///<summary>Return false to indicate exit app.  Only called when program first starts up at the beginning of FormOpenDental.PrefsStartup.</summary>
        public bool Convert(string fromVersion, string toVersion, bool silent)
        {
            FromVersion = new Version(fromVersion);
            ToVersion   = new Version(toVersion);        //Application.ProductVersion);
            if (FromVersion == ToVersion)
            {
                return(true);               //no conversion necessary
            }
            if (FromVersion >= new Version("3.4.0") && PrefC.GetBool(PrefName.CorruptedDatabase))
            {
                MsgBox.Show(this, "Your database is corrupted because a conversion failed.  Please contact us.  This database is unusable and you will need to restore from a backup.");
                return(false);                        //shuts program down.
            }
            if (FromVersion.CompareTo(ToVersion) > 0) //"Cannot convert database to an older version."
            //no longer necessary to catch it here.  It will be handled soon enough in CheckProgramVersion
            {
                return(true);
            }
            if (FromVersion < new Version("2.8.0"))
            {
                MsgBox.Show(this, "This database is too old to easily convert in one step. Please upgrade to 2.1 if necessary, then to 2.8.  Then you will be able to upgrade to this version. We apologize for the inconvenience.");
                return(false);
            }
            if (FromVersion < new Version("6.6.2"))
            {
                MsgBox.Show(this, "This database is too old to easily convert in one step. Please upgrade to 11.1 first.  Then you will be able to upgrade to this version. We apologize for the inconvenience.");
                return(false);
            }
            if (FromVersion < new Version("3.0.1"))
            {
                MsgBox.Show(this, "This is an old database.  The conversion must be done using MySQL 4.1 (not MySQL 5.0) or it will fail.");
            }
            if (FromVersion.ToString() == "2.9.0.0" || FromVersion.ToString() == "3.0.0.0" || FromVersion.ToString() == "4.7.0.0")
            {
                MsgBox.Show(this, "Cannot convert this database version which was only for development purposes.");
                return(false);
            }
            if (FromVersion > new Version("4.7.0") && FromVersion.Build == 0)
            {
                MsgBox.Show(this, "Cannot convert this database version which was only for development purposes.");
                return(false);
            }
            if (FromVersion >= ConvertDatabases.LatestVersion)
            {
                return(true);               //no conversion necessary
            }
            if (RemotingClient.RemotingRole == RemotingRole.ClientWeb)
            {
                MsgBox.Show(this, "Web client cannot convert database.  Must be using a direct connection.");
                return(false);
            }
            if (ReplicationServers.ServerIsBlocked())
            {
                MsgBox.Show(this, "This replication server is blocked from performing updates.");
                return(false);
            }
            if (PrefC.GetString(PrefName.WebServiceServerName) != "" &&       //using web service
                !ODEnvironment.IdIsThisComputer(PrefC.GetString(PrefName.WebServiceServerName).ToLower()))                   //and not on web server
            {
                MessageBox.Show(Lan.g(this, "Updates are only allowed from the web server: ") + PrefC.GetString(PrefName.WebServiceServerName));
                return(false);
            }
            //If MyISAM and InnoDb mix, then try to fix
            if (DataConnection.DBtype == DatabaseType.MySql)                    //not for Oracle
            {
                string namesInnodb = DatabaseMaintenance.GetInnodbTableNames(); //Or possibly some other format.
                int    numMyisam   = DatabaseMaintenance.GetMyisamTableCount();
                if (namesInnodb != "" && numMyisam > 0)
                {
                    MessageBox.Show(Lan.g(this, "A mixture of database tables in InnoDB and MyISAM format were found.  A database backup will now be made, and then the following InnoDB tables will be converted to MyISAM format: ") + namesInnodb);
                    try {
                        MiscData.MakeABackup();                        //Does not work for Oracle, due to some MySQL specific commands inside.
                    }
                    catch (Exception e) {
                        Cursor.Current = Cursors.Default;
                        if (e.Message != "")
                        {
                            MessageBox.Show(e.Message);
                        }
                        MsgBox.Show(this, "Backup failed. Your database has not been altered.");
                        return(false);
                    }
                    if (!DatabaseMaintenance.ConvertTablesToMyisam())
                    {
                        MessageBox.Show(Lan.g(this, "Failed to convert InnoDB tables to MyISAM format. Please contact support."));
                        return(false);
                    }
                    MessageBox.Show(Lan.g(this, "All tables converted to MyISAM format successfully."));
                    namesInnodb = "";
                }
                if (namesInnodb == "" && numMyisam > 0)             //if all tables are myisam
                //but default storage engine is innodb, then kick them out.
                {
                    if (DatabaseMaintenance.GetStorageEngineDefaultName().ToUpper() != "MYISAM")                    //Probably InnoDB but could be another format.
                    {
                        MessageBox.Show(Lan.g(this, "The database tables are in MyISAM format, but the default database engine format is InnoDB. You must change the default storage engine within the my.ini (or my.cnf) file on the database server and restart MySQL in order to fix this problem. Exiting."));
                        return(false);
                    }
                }
            }
#if DEBUG
            if (!silent && MessageBox.Show("You are in Debug mode.  Your database can now be converted" + "\r"
                                           + "from version" + " " + FromVersion.ToString() + "\r"
                                           + "to version" + " " + ToVersion.ToString() + "\r"
                                           + "You can click Cancel to skip conversion and attempt to the newer code against the older database."
                                           , "", MessageBoxButtons.OKCancel) != DialogResult.OK)
            {
                return(true);               //If user clicks cancel, then do nothing
            }
#else
            if (!silent && MessageBox.Show(Lan.g(this, "Your database will now be converted") + "\r"
                                           + Lan.g(this, "from version") + " " + FromVersion.ToString() + "\r"
                                           + Lan.g(this, "to version") + " " + ToVersion.ToString() + "\r"
                                           + Lan.g(this, "The conversion works best if you are on the server.  Depending on the speed of your computer, it can be as fast as a few seconds, or it can take as long as 10 minutes.")
                                           , "", MessageBoxButtons.OKCancel) != DialogResult.OK)
            {
                return(false);               //If user clicks cancel, then close the program
            }
#endif
            Cursor.Current = Cursors.WaitCursor;
#if !DEBUG
            if (DataConnection.DBtype != DatabaseType.MySql &&
                !MsgBox.Show(this, true, "If you have not made a backup, please Cancel and backup before continuing.  Continue?"))
            {
                return(false);
            }
            try{
                if (DataConnection.DBtype == DatabaseType.MySql)
                {
                    MiscData.MakeABackup();                    //Does not work for Oracle, due to some MySQL specific commands inside.
                }
            }
            catch (Exception e) {
                Cursor.Current = Cursors.Default;
                if (e.Message != "")
                {
                    MessageBox.Show(e.Message);
                }
                MsgBox.Show(this, "Backup failed. Your database has not been altered.");
                return(false);
            }
            try{
#endif
            if (FromVersion < new Version("7.5.17"))
            {
                Cursor.Current = Cursors.Default;
                YN InsPlanConverstion_7_5_17_AutoMergeYN = YN.Unknown;
                if (FromVersion < new Version("7.5.1"))
                {
                    FormInsPlanConvert_7_5_17 form = new FormInsPlanConvert_7_5_17();
                    if (PrefC.GetBoolSilent(PrefName.InsurancePlansShared, true))
                    {
                        form.InsPlanConverstion_7_5_17_AutoMergeYN = YN.Yes;
                    }
                    else
                    {
                        form.InsPlanConverstion_7_5_17_AutoMergeYN = YN.No;
                    }
                    form.ShowDialog();
                    if (form.DialogResult == DialogResult.Cancel)
                    {
                        MessageBox.Show("Your database has not been altered.");
                        return(false);
                    }
                    InsPlanConverstion_7_5_17_AutoMergeYN = form.InsPlanConverstion_7_5_17_AutoMergeYN;
                }
                ConvertDatabases.Set_7_5_17_AutoMerge(InsPlanConverstion_7_5_17_AutoMergeYN);                //does nothing if this pref is already present for some reason.
                Cursor.Current = Cursors.WaitCursor;
            }
            if (FromVersion >= new Version("3.4.0"))
            {
                Prefs.UpdateBool(PrefName.CorruptedDatabase, true);
            }
            ConvertDatabases.FromVersion = FromVersion;
            ConvertDatabases.To2_8_2();            //begins going through the chain of conversion steps
            Cursor.Current = Cursors.Default;
            if (!silent)
            {
                MsgBox.Show(this, "Conversion successful");
            }
            if (FromVersion >= new Version("3.4.0"))
            {
                //CacheL.Refresh(InvalidType.Prefs);//or it won't know it has to update in the next line.
                Prefs.UpdateBool(PrefName.CorruptedDatabase, false, true);              //more forceful refresh in order to properly change flag
            }
            Cache.Refresh(InvalidType.Prefs);
            return(true);

#if !DEBUG
        }

        catch (System.IO.FileNotFoundException e) {
            MessageBox.Show(e.FileName + " " + Lan.g(this, "could not be found. Your database has not been altered and is still usable if you uninstall this version, then reinstall the previous version."));
            if (FromVersion >= new Version("3.4.0"))
            {
                Prefs.UpdateBool(PrefName.CorruptedDatabase, false);
            }
            //Prefs.Refresh();
            return(false);
        }
        catch (System.IO.DirectoryNotFoundException) {
            MessageBox.Show(Lan.g(this, "ConversionFiles folder could not be found. Your database has not been altered and is still usable if you uninstall this version, then reinstall the previous version."));
            if (FromVersion >= new Version("3.4.0"))
            {
                Prefs.UpdateBool(PrefName.CorruptedDatabase, false);
            }
            //Prefs.Refresh();
            return(false);
        }
        catch (Exception ex) {
            //	MessageBox.Show();
            MessageBox.Show(ex.Message + "\r\n\r\n"
                            + Lan.g(this, "Conversion unsuccessful. Your database is now corrupted and you cannot use it.  Please contact us."));
            //Then, application will exit, and database will remain tagged as corrupted.
            return(false);
        }
#endif
        }
Example #47
0
        ///<summary>Return false to indicate exit app.  Only called when program first starts up at the beginning of FormOpenDental.PrefsStartup.</summary>
        public bool Convert(string fromVersion, string toVersion, bool isSilent, Form currentForm = null)
        {
            FromVersion = new Version(fromVersion);
            ToVersion   = new Version(toVersion);        //Application.ProductVersion);
            if (FromVersion >= new Version("3.4.0") && PrefC.GetBool(PrefName.CorruptedDatabase))
            {
                FormOpenDental.ExitCode = 201;              //Database was corrupted due to an update failure
                if (!isSilent)
                {
                    MsgBox.Show(this, "Your database is corrupted because an update failed.  Please contact us.  This database is unusable and you will need to restore from a backup.");
                }
                return(false);               //shuts program down.
            }
            if (FromVersion == ToVersion)
            {
                return(true);                         //no conversion necessary
            }
            if (FromVersion.CompareTo(ToVersion) > 0) //"Cannot convert database to an older version."
            //no longer necessary to catch it here.  It will be handled soon enough in CheckProgramVersion
            {
                return(true);
            }
            if (FromVersion < new Version("2.8.0"))
            {
                FormOpenDental.ExitCode = 130;              //Database must be upgraded to 2.8 to continue
                if (!isSilent)
                {
                    MsgBox.Show(this, "This database is too old to easily convert in one step. Please upgrade to 2.1 if necessary, then to 2.8.  Then you will be able to upgrade to this version. We apologize for the inconvenience.");
                }
                return(false);
            }
            if (FromVersion < new Version("6.6.2"))
            {
                FormOpenDental.ExitCode = 131;              //Database must be upgraded to 11.1 to continue
                if (!isSilent)
                {
                    MsgBox.Show(this, "This database is too old to easily convert in one step. Please upgrade to 11.1 first.  Then you will be able to upgrade to this version. We apologize for the inconvenience.");
                }
                return(false);
            }
            if (FromVersion < new Version("3.0.1"))
            {
                if (!isSilent)
                {
                    MsgBox.Show(this, "This is an old database.  The conversion must be done using MySQL 4.1 (not MySQL 5.0) or it will fail.");
                }
            }
            if (FromVersion.ToString() == "2.9.0.0" || FromVersion.ToString() == "3.0.0.0" || FromVersion.ToString() == "4.7.0.0")
            {
                FormOpenDental.ExitCode = 190;              //Cannot convert this database version which was only for development purposes
                if (!isSilent)
                {
                    MsgBox.Show(this, "Cannot convert this database version which was only for development purposes.");
                }
                return(false);
            }
            if (FromVersion > new Version("4.7.0") && FromVersion.Build == 0)
            {
                FormOpenDental.ExitCode = 190;              //Cannot convert this database version which was only for development purposes
                if (!isSilent)
                {
                    MsgBox.Show(this, "Cannot convert this database version which was only for development purposes.");
                }
                return(false);
            }
            if (FromVersion >= LatestVersion)
            {
                return(true);               //no conversion necessary
            }
            if (RemotingClient.RemotingRole == RemotingRole.ClientWeb)
            {
                FormOpenDental.ExitCode = 140;              //Web client cannot convert database
                if (!isSilent)
                {
                    MsgBox.Show(this, "Web client cannot convert database.  Must be using a direct connection.");
                }
                return(false);
            }
            if (ReplicationServers.ServerIsBlocked())
            {
                FormOpenDental.ExitCode = 150;              //Replication server is blocked from performing updates
                if (!isSilent)
                {
                    MsgBox.Show(this, "This replication server is blocked from performing updates.");
                }
                return(false);
            }
#if TRIALONLY
            //Trial users should never be able to update a database.
            if (PrefC.GetString(PrefName.RegistrationKey) != "") //Allow databases with no reg key to update.  Needed by our conversion department.
            {
                FormOpenDental.ExitCode = 191;                   //Trial versions cannot connect to live databases
                if (!isSilent)
                {
                    MsgBox.Show(this, "Trial versions cannot connect to live databases.  Please run the Setup.exe in the AtoZ folder to reinstall your original version.");
                }
                return(false);
            }
#endif
            if (PrefC.GetString(PrefName.WebServiceServerName) != "" &&       //using web service
                !ODEnvironment.IdIsThisComputer(PrefC.GetString(PrefName.WebServiceServerName).ToLower()))                   //and not on web server
            {
                if (isSilent)
                {
                    FormOpenDental.ExitCode = 141;   //Updates are only allowed from a designated web server
                    return(false);                   //if you are in debug mode and you really need to update the DB, you can manually clear the WebServiceServerName preference.
                }
                //This will be handled in CheckProgramVersion, giving the user option to downgrade or exit program.
                return(true);
            }
            //If MyISAM and InnoDb mix, then try to fix
            if (DataConnection.DBtype == DatabaseType.MySql)           //not for Oracle
            {
                string namesInnodb = InnoDb.GetInnodbTableNames();     //Or possibly some other format.
                int    numMyisam   = DatabaseMaintenances.GetMyisamTableCount();
                if (namesInnodb != "" && numMyisam > 0)
                {
                    if (!isSilent)
                    {
                        MessageBox.Show(Lan.g(this, "A mixture of database tables in InnoDB and MyISAM format were found.  A database backup will now be made, and then the following InnoDB tables will be converted to MyISAM format: ") + namesInnodb);
                    }
                    if (!Shared.MakeABackup(isSilent, BackupLocation.ConvertScript, false))
                    {
                        Cursor.Current          = Cursors.Default;
                        FormOpenDental.ExitCode = 101;                      //Database Backup failed
                        return(false);
                    }
                    if (!DatabaseMaintenances.ConvertTablesToMyisam())
                    {
                        FormOpenDental.ExitCode = 102;                      //Failed to convert InnoDB tables to MyISAM format
                        if (!isSilent)
                        {
                            MessageBox.Show(Lan.g(this, "Failed to convert InnoDB tables to MyISAM format. Please contact support."));
                        }
                        return(false);
                    }
                    if (!isSilent)
                    {
                        MessageBox.Show(Lan.g(this, "All tables converted to MyISAM format successfully."));
                    }
                    namesInnodb = "";
                }
                if (namesInnodb == "" && numMyisam > 0)             //if all tables are myisam
                //but default storage engine is innodb, then kick them out.
                {
                    if (DatabaseMaintenances.GetStorageEngineDefaultName().ToUpper() != "MYISAM") //Probably InnoDB but could be another format.
                    {
                        FormOpenDental.ExitCode = 103;                                            //Default database .ini setting is innoDB
                        if (!isSilent)
                        {
                            MessageBox.Show(Lan.g(this, "The database tables are in MyISAM format, but the default database engine format is InnoDB. You must change the default storage engine within the my.ini (or my.cnf) file on the database server and restart MySQL in order to fix this problem. Exiting."));
                        }
                        return(false);
                    }
                }
            }
#if DEBUG
            if (!isSilent && MessageBox.Show("You are in Debug mode.  Your database can now be converted" + "\r"
                                             + "from version" + " " + FromVersion.ToString() + "\r"
                                             + "to version" + " " + ToVersion.ToString() + "\r"
                                             + "You can click Cancel to skip conversion and attempt to run the newer code against the older database."
                                             , "", MessageBoxButtons.OKCancel) != DialogResult.OK)
            {
                return(true);               //If user clicks cancel, then do nothing
            }
#else
            if (!isSilent && MessageBox.Show(Lan.g(this, "Your database will now be converted") + "\r"
                                             + Lan.g(this, "from version") + " " + FromVersion.ToString() + "\r"
                                             + Lan.g(this, "to version") + " " + ToVersion.ToString() + "\r"
                                             + Lan.g(this, "The conversion works best if you are on the server.  Depending on the speed of your computer, it can be as fast as a few seconds, or it can take as long as 10 minutes.")
                                             , "", MessageBoxButtons.OKCancel) != DialogResult.OK)
            {
                return(false);               //If user clicks cancel, then close the program
            }
#endif
            Cursor.Current = Cursors.WaitCursor;
            Action actionCloseConvertProgress = null;
#if !DEBUG
            if (!isSilent)
            {
                if (DataConnection.DBtype != DatabaseType.MySql &&
                    !MsgBox.Show(this, true, "If you have not made a backup, please Cancel and backup before continuing.  Continue?"))
                {
                    return(false);
                }
            }
            if (DataConnection.DBtype == DatabaseType.MySql)
            {
                if (!Shared.MakeABackup(isSilent, BackupLocation.ConvertScript, false))
                {
                    Cursor.Current          = Cursors.Default;
                    FormOpenDental.ExitCode = 101;                  //Database Backup failed
                    return(false);
                }
            }
            //We've been getting an increasing number of phone calls with databases that have duplicate preferences which is impossible
            //unless a user has gotten this far and another computer in the office is in the middle of an update as well.
            //The issue is most likely due to the blocking messageboxes above which wait indefinitely for user input right before upgrading the database.
            //This means that the cache for this computer could be stale and we need to manually refresh our cache to double check
            //that the database isn't flagged as corrupt, an update isn't in progress, or that the database version hasn't changed (someone successfully updated already).
            Prefs.RefreshCache();
            //Now check the preferences that should stop this computer from executing an update.
            if (PrefC.GetBool(PrefName.CorruptedDatabase) ||
                (PrefC.GetString(PrefName.UpdateInProgressOnComputerName) != "" && PrefC.GetString(PrefName.UpdateInProgressOnComputerName) != Environment.MachineName))
            {
                //At this point, the pref "corrupted database" being true means that a computer is in the middle of running the upgrade script.
                //There will be another corrupted database check on start up which will take care of the scenario where this is truly a corrupted database.
                //Also, we need to make sure that the update in progress preference is set to this computer because we JUST set it to that value before entering this method.
                //If it has changed, we absolutely know without a doubt that another computer is trying to update at the same time.
                FormOpenDental.ExitCode = 142;              //Update is already in progress from another computer
                if (!isSilent)
                {
                    MsgBox.Show(this, "An update is already in progress from another computer.");
                }
                return(false);
            }
            //Double check that the database version has not changed.  This check is here just in case another computer has successfully updated the database already.
            Version versionDatabase = new Version(PrefC.GetString(PrefName.DataBaseVersion));
            if (FromVersion != versionDatabase)
            {
                FormOpenDental.ExitCode = 143;              //Database has already been updated from another computer
                if (!isSilent)
                {
                    MsgBox.Show(this, "The database has already been updated from another computer.");
                }
                return(false);
            }
            try {
#endif
            if (FromVersion < new Version("7.5.17"))                     //Insurance Plan schema conversion
            {
                if (isSilent)
                {
                    FormOpenDental.ExitCode = 139;                          //Update must be done manually to fix Insurance Plan Schema
                    Application.Exit();
                    return(false);
                }
                Cursor.Current = Cursors.Default;
                YN InsPlanConverstion_7_5_17_AutoMergeYN = YN.Unknown;
                if (FromVersion < new Version("7.5.1"))
                {
                    FormInsPlanConvert_7_5_17 form = new FormInsPlanConvert_7_5_17();
                    if (PrefC.GetBoolSilent(PrefName.InsurancePlansShared, true))
                    {
                        form.InsPlanConverstion_7_5_17_AutoMergeYN = YN.Yes;
                    }
                    else
                    {
                        form.InsPlanConverstion_7_5_17_AutoMergeYN = YN.No;
                    }
                    form.ShowDialog();
                    if (form.DialogResult == DialogResult.Cancel)
                    {
                        MessageBox.Show("Your database has not been altered.");
                        return(false);
                    }
                    InsPlanConverstion_7_5_17_AutoMergeYN = form.InsPlanConverstion_7_5_17_AutoMergeYN;
                }
                ConvertDatabases.Set_7_5_17_AutoMerge(InsPlanConverstion_7_5_17_AutoMergeYN);                        //does nothing if this pref is already present for some reason.
                Cursor.Current = Cursors.WaitCursor;
            }
            if (!isSilent && FromVersion > new Version("16.3.0") && FromVersion < new Version("16.3.29") && ApptReminderRules.IsReminders)
            {
                //16.3.29 is more strict about reminder rule setup. Prompt the user and allow them to exit the update if desired.
                //Get all currently enabled reminder rules.
                List <bool> listReminderFlags = ApptReminderRules.Get_16_3_29_ConversionFlags();
                if (listReminderFlags?[0] ?? false)                        //2 reminders scheduled for same day of appointment. 1 will be converted to future day reminder.
                {
                    MsgBox.Show(this, "You have multiple appointment reminders set to send on the same day of the appointment. One of these will be converted to send 1 day prior to the appointment.  Please review automated reminder rule setup after update has finished.");
                }
                if (listReminderFlags?[1] ?? false)                        //2 reminders scheduled for future day of appointment. 1 will be converted to same day reminder.
                {
                    MsgBox.Show(this, "You have multiple appointment reminders set to send 1 or more days prior to the day of the appointment. One of these will be converted to send 1 hour prior to the appointment.  Please review automated reminder rule setup after update has finished.");
                }
            }
            if (FromVersion >= new Version("17.3.1") && FromVersion < new Version("17.3.23") && DataConnection.DBtype == DatabaseType.MySql &&
                (Tasks.HasAnyLongDescripts() || TaskNotes.HasAnyLongNotes() || Commlogs.HasAnyLongNotes()))
            {
                if (isSilent)
                {
                    FormOpenDental.ExitCode = 138;                          //Update must be done manually in order to get data loss notification(s).
                    Application.Exit();
                    return(false);
                }
                if (!MsgBox.Show(this, true, "Data will be lost during this update."
                                 + "\r\nContact support in order to retrieve the data from a backup after the update."
                                 + "\r\n\r\nContinue?"))
                {
                    MessageBox.Show("Your database has not been altered.");
                    return(false);
                }
            }
            if (FromVersion >= new Version("3.4.0"))
            {
                Prefs.UpdateBool(PrefName.CorruptedDatabase, true);
            }
            ConvertDatabases.FromVersion = FromVersion;
#if !DEBUG
            //Typically the UpdateInProgressOnComputerName preference will have already been set within FormUpdate.
            //However, the user could have cancelled out of FormUpdate after successfully downloading the Setup.exe
            //OR the Setup.exe could have been manually sent to our customer (during troubleshooting with HQ).
            //For those scenarios, the preference will be empty at this point and we need to let other computers know that an update going to start.
            //Updating the string (again) here will guarantee that all computers know an update is in fact in progress from this machine.
            Prefs.UpdateString(PrefName.UpdateInProgressOnComputerName, Environment.MachineName);
#endif
            //Show a progress window that will indecate to the user that there is an active update in progress.  Currently okay to show during isSilent.
            actionCloseConvertProgress = ODProgressOld.ShowProgressStatus("ConvertDatabases", hasMinimize: false, currentForm: currentForm);
            ConvertDatabases.To2_8_2();                //begins going through the chain of conversion steps
            InvokeConvertMethods();                    //continues going through the chain of conversion steps starting at v17.1.1 via reflection.
            actionCloseConvertProgress();
            Cursor.Current = Cursors.Default;
            if (FromVersion >= new Version("3.4.0"))
            {
                //CacheL.Refresh(InvalidType.Prefs);//or it won't know it has to update in the next line.
                Prefs.UpdateBool(PrefName.CorruptedDatabase, false, true);                      //more forceful refresh in order to properly change flag
            }
            Cache.Refresh(InvalidType.Prefs);
            if (!isSilent)
            {
                MsgBox.Show(this, "Database update successful");
            }
            return(true);

#if !DEBUG
        }

        catch (System.IO.FileNotFoundException e) {
            actionCloseConvertProgress?.Invoke();
            FormOpenDental.ExitCode = 160;                  //File not found exception
            if (!isSilent)
            {
                MessageBox.Show(e.FileName + " " + Lan.g(this, "could not be found. Your database has not been altered and is still usable if you uninstall this version, then reinstall the previous version."));
            }
            if (FromVersion >= new Version("3.4.0"))
            {
                Prefs.UpdateBool(PrefName.CorruptedDatabase, false);
            }
            return(false);
        }
        catch (System.IO.DirectoryNotFoundException) {
            actionCloseConvertProgress?.Invoke();
            FormOpenDental.ExitCode = 160;                  //ConversionFiles folder could not be found
            if (!isSilent)
            {
                MessageBox.Show(Lan.g(this, "ConversionFiles folder could not be found. Your database has not been altered and is still usable if you uninstall this version, then reinstall the previous version."));
            }
            if (FromVersion >= new Version("3.4.0"))
            {
                Prefs.UpdateBool(PrefName.CorruptedDatabase, false);
            }
            return(false);
        }
        catch (Exception ex) {
            actionCloseConvertProgress?.Invoke();
            FormOpenDental.ExitCode = 201;                  //Database was corrupted due to an update failure
            if (!isSilent)
            {
                MessageBox.Show(ex.Message + "\r\n\r\n"
                                + Lan.g(this, "Conversion unsuccessful. Your database is now corrupted and you cannot use it.  Please contact us."));
            }
            //Then, application will exit, and database will remain tagged as corrupted.
            return(false);
        }
#endif
        }
Example #48
0
        public static void Check()
        {
            string sApplicationName = Assembly.GetExecutingAssembly().GetName().Name;

            System.Version oThisVersion = Assembly.GetEntryAssembly().GetName().Version;
            (Version oLatestVersion, string sLatestFilename) = GetLatestVersionData();

            if (oLatestVersion != null && oThisVersion.CompareTo(oLatestVersion) < 0)
            {
                Program.WriteToEventLog("A newer version of " + sApplicationName + " is available (" + oLatestVersion.ToString() + ").", Verbosity.Warning);

                string sSaveLocation = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
                if (GetCurrentVersion(oLatestVersion, sLatestFilename, ref sSaveLocation))
                {
                    try
                    {
                        var oUpdateDirectory = new FileInfo(sSaveLocation).Directory;

                        DirectoryInfo oPreviousVersionDirectory;
                        if (!Directory.Exists(oUpdateDirectory.Parent.FullName + "\\PreviousVersion\\"))
                        {
                            oPreviousVersionDirectory = Directory.CreateDirectory(oUpdateDirectory.Parent.FullName + "\\PreviousVersion\\");
                        }
                        else
                        {
                            oPreviousVersionDirectory = new FileInfo(oUpdateDirectory.Parent.FullName + "\\PreviousVersion\\").Directory;
                        }

                        foreach (FileInfo oFileInfo in oPreviousVersionDirectory.GetFiles())
                        {
                            oFileInfo.Delete();
                        }

                        try
                        {
                            foreach (FileInfo oFileInfo in oPreviousVersionDirectory.Parent.GetFiles())
                            {
                                // Move files to the PreviousVersion folder
                                if (oFileInfo.Name.Contains(".config") || oFileInfo.Name.Contains(".json"))
                                {
                                    File.Copy(oFileInfo.FullName, oPreviousVersionDirectory.FullName + "\\" + oFileInfo.Name);
                                }
                                else
                                {
                                    File.Move(oFileInfo.FullName, oPreviousVersionDirectory.FullName + "\\" + oFileInfo.Name);
                                }
                            }

                            Decompress(sSaveLocation, oPreviousVersionDirectory.Parent.FullName);
                        }
                        catch
                        {
                            // Rollback
                            foreach (FileInfo oFileInfo in oPreviousVersionDirectory.GetFiles())
                            {
                                // Move files back to the main plugin folder
                                File.Move(oFileInfo.FullName, oPreviousVersionDirectory.Parent.FullName + "\\" + oFileInfo.Name);
                            }

                            throw;
                        }

                        Program.WriteToEventLog(sApplicationName + " has been updated. Update will be applied on next restart of application", Verbosity.Warning);
                    }
                    catch (Exception exception)
                    {
                        Program.WriteToEventLog(sApplicationName + " could not be updated. Exception: " + exception.Message + " This may be due to a network issue, a configuration issue, lack of file permissions, or a too out of date install that can not be auto updated. If this error persists please update manually by downloading the latest version from https://github.com/fpdavis/MTOvJoyFeeder/releases", Verbosity.Error);
                    }
                }
            }
            else if (oLatestVersion == null)
            {
                Program.WriteToEventLog("A version number could not be found while checking for an update.", Verbosity.Critical);
            }
            else
            {
                Program.WriteToEventLog(String.Format("{0} ({1}) is up to date.", sApplicationName, oThisVersion.ToString()), Verbosity.Information);
            }
        }
 public static System.Version MaxVersion(System.Version a, System.Version b)
 {
     return((a.CompareTo(b) > 0) ? a : b);
 }
 public static int StringBasedCompareTo(TrackedBundleVersionInfo info1, TrackedBundleVersionInfo info2)
 {
     System.Version v1 = new System.Version(info1.version);
     System.Version v2 = new System.Version(info2.version);
     return(v1.CompareTo(v2));
 }
        //Get python path & compare versions
        private static string GetPythonPath(string requiredVersion = "", string maxVersion = "")
        {
            string[] possiblePythonLocations = new string[3] {
                @"HKLM\SOFTWARE\Python\PythonCore\",
                @"HKCU\SOFTWARE\Python\PythonCore\",
                @"HKLM\SOFTWARE\Wow6432Node\Python\PythonCore\"
            };
            //Version number, install path
            Dictionary <string, string> pythonLocations = new Dictionary <string, string>();

            foreach (string possibleLocation in possiblePythonLocations)
            {
                string      regKey = possibleLocation.Substring(0, 4), actualPath = possibleLocation.Substring(5);
                RegistryKey theKey   = (regKey == "HKLM" ? Registry.LocalMachine : Registry.CurrentUser);
                RegistryKey theValue = theKey.OpenSubKey(actualPath);

                foreach (var v in theValue.GetSubKeyNames())
                {
                    RegistryKey productKey = theValue.OpenSubKey(v);
                    if (productKey != null)
                    {
                        try {
                            string pythonExePath = productKey.OpenSubKey("InstallPath").GetValue("ExecutablePath").ToString();
                            if (pythonExePath != null && pythonExePath != "")
                            {
                                //Console.WriteLine("Got python version; " + v + " at path; " + pythonExePath);
                                pythonLocations.Add(v.ToString(), pythonExePath);
                            }
                        } catch {
                            //Install path doesn't exist
                        }
                    }
                }
            }

            if (pythonLocations.Count > 0)
            {
                System.Version desiredVersion = new System.Version(requiredVersion == "" ? "0.0.1" : requiredVersion),
                               maxPVersion    = new System.Version(maxVersion == "" ? "999.999.999" : maxVersion);

                string highestVersion = "", highestVersionPath = "";

                foreach (KeyValuePair <string, string> pVersion in pythonLocations)
                {
                    //TODO; if on 64-bit machine, prefer the 64 bit version over 32 and vice versa
                    int    index            = pVersion.Key.IndexOf("-"); //For x-32 and x-64 in version numbers
                    string formattedVersion = index > 0 ? pVersion.Key.Substring(0, index) : pVersion.Key;

                    System.Version thisVersion   = new System.Version(formattedVersion);
                    int            comparison    = desiredVersion.CompareTo(thisVersion),
                                   maxComparison = maxPVersion.CompareTo(thisVersion);

                    if (comparison <= 0)
                    {
                        //Version is greater or equal
                        if (maxComparison >= 0)
                        {
                            desiredVersion = thisVersion;

                            highestVersion     = pVersion.Key;
                            highestVersionPath = pVersion.Value;
                        }
                        else
                        {
                            //Console.WriteLine("Version is too high; " + maxComparison.ToString());
                        }
                    }
                    else
                    {
                        //Console.WriteLine("Version (" + pVersion.Key + ") is not within the spectrum.");
                    }
                }

                return(highestVersionPath);
            }

            return("");
        }
        void OnGUI()
        {
            if (!m_DidFocus)
            {
                Focus();
                m_DidFocus = true;
            }
            if (www == null)
            {
                return;
            }
            //            string str ="\n Welcome to TextureWang \n \n If you find it useful please consider becoming a patreon \nto help support future features \n ";
            string str       = "";
            string pathTitle = "Assets/TextureWang/TWtitle2.jpg";

            pathTitle = pathTitle.Replace("/", "" + Path.DirectorySeparatorChar);

            if (wwwImage != null && wwwImage.isDone)
            {
                File.WriteAllBytes(pathTitle, wwwImage.bytes);
                AssetDatabase.ImportAsset(pathTitle, ImportAssetOptions.ForceSynchronousImport);
                wwwImage = null;
            }

            if (m_Background == null)
            {
                m_Background = (Texture2D)AssetDatabase.LoadAssetAtPath(pathTitle, typeof(Texture2D));
                if (m_Background != null)
                {
                    DateTime createdTime = File.GetCreationTime(pathTitle);
                    DateTime now         = DateTime.Now;
                    TimeSpan age         = now - createdTime;
                    Debug.Log(" Title age days:" + age.Days + " " + age.Seconds);
                    if (age.Days > 1 || age.Seconds > 10)
                    {
                        StartLoadImage();
                    }
                }
                else
                {
                    StartLoadImage();
                }
            }

//            if (m_Down != null )
//                Debug.Log(" download hangler " + m_Down.isDone+ " wwwImage "+ wwwImage.downloadProgress+" err "+wwwImage.error);

            Rect buttonArea = new Rect(0, 500, 600, 100);


            if (www.isDone)
            {
                try
                {
                    Version v = new Version(www.text);

                    str += "\n\nLatest version available " + v + " your version: " + NodeEditorTWWindow.m_Version;
                    if (m_Background != null)
                    {
                        GUI.DrawTexture(new Rect((m_Width - 512) * 0.5f, 0, 512, 512), m_Background, ScaleMode.ScaleAndCrop); //ScaleMode.StretchToFill);
                    }
                    GUILayout.BeginArea(buttonArea);
                    if (v.CompareTo(NodeEditorTWWindow.m_Version) > 0)
                    {
                        //str += "New version available " + v + " yours: " + NodeEditorTWWindow.m_Version;
                        EditorGUILayout.LabelField(str, EditorStyles.wordWrappedLabel);
                        if (GUILayout.Button("Go get New version "))
                        {
                            this.Close();
                            Application.OpenURL("https://github.com/dizzy2003/TextureWang");
                        }

                        if (GUILayout.Button("Ignore new version"))
                        {
                            this.Close();
                        }
                        return;
                    }
                }
                catch (Exception ex)
                {
                    Debug.LogError("Exception in version number code " + ex);
                }
                GUILayout.EndArea();
            }
            else
            {
                if (m_Background != null)
                {
                    GUI.DrawTexture(new Rect((m_Width - 512) * 0.5f, 0, 512, 512), m_Background, ScaleMode.ScaleAndCrop); //ScaleMode.StretchToFill);
                }
                str += "\n\nConnecting to Server (to check for newer versions)";
                m_Count++;

                for (int i = 0; i < (m_Count >> 4) % 10; i++)
                {
                    str += ".";
                }
            }


            GUILayout.BeginArea(buttonArea);
            EditorGUILayout.LabelField(str, EditorStyles.wordWrappedLabel);
            if (GUILayout.Button("OK"))
            {
                this.Close();
            }
            GUILayout.EndArea();
        }