private static void RecoverFromBackupFailure() { string appDataPath = DirectoryUtilities.GetUserStoragePath(VersionHelper.IsNightly()); DirectoryInfo info = new DirectoryInfo(appDataPath); IEnumerable <FileInfo> foundFiles = info.GetFiles("*.last"); foreach (FileInfo file in foundFiles) { string corruptedFile = file.FullName.Replace(".last", string.Empty); if (File.Exists(corruptedFile)) { File.Delete(corruptedFile); } File.Move(file.FullName, corruptedFile); } }
public void FromGitDescription_BadFormat() { VersionHelper.ParseGitDescription("a.b.c.d"); }
/// <summary> /// Generate the header for the log file. /// </summary> /// <returns> /// The generatedlog header. /// </returns> public static StringBuilder CreateLogHeader() { var logHeader = new StringBuilder(); StringBuilder gpuBuilder = new StringBuilder(); foreach (var item in SystemInfo.GetGPUInfo) { gpuBuilder.AppendLine(string.Format(" {0}", item)); } if (string.IsNullOrEmpty(gpuBuilder.ToString().Trim())) { gpuBuilder.Append("GPU Information is unavailable"); } logHeader.AppendLine(string.Format("HandBrake {0}", VersionHelper.GetVersion())); logHeader.AppendLine(string.Format("OS: {0}", Environment.OSVersion)); logHeader.AppendLine(string.Format("CPU: {0}", SystemInfo.GetCpu)); logHeader.AppendLine(string.Format("Ram: {0} MB, ", SystemInfo.TotalPhysicalMemory)); logHeader.AppendLine(string.Format("GPU Information:{0}{1}", Environment.NewLine, gpuBuilder.ToString().TrimEnd())); logHeader.AppendLine(string.Format("Screen: {0}x{1}", SystemInfo.ScreenBounds.Bounds.Width, SystemInfo.ScreenBounds.Bounds.Height)); logHeader.AppendLine(string.Format("Temp Dir: {0}", Path.GetTempPath())); logHeader.AppendLine(string.Format("Install Dir: {0}", Application.StartupPath)); logHeader.AppendLine(string.Format("Data Dir: {0}\n", DirectoryUtilities.GetUserStoragePath(VersionHelper.IsNightly()))); logHeader.AppendLine("-------------------------------------------"); return(logHeader); }
public VersionDTO GetVersion(string version) => VersionHelper.FindVersion(version);
public void FromGitDescription_ArgumentNull() { VersionHelper.ParseGitDescription(null); }
public NonClientAreaViewModel() { VersionInfo = VersionHelper.GetVersion(); }
/// <summary> /// Load the User Settings /// </summary> private void Load() { try { // Load up the users current settings file. if (File.Exists(this.settingsFile)) { using (StreamReader reader = new StreamReader(this.settingsFile)) { string appSettings = reader.ReadToEnd(); Dictionary <string, object> deserialisedSettings = JsonConvert.DeserializeObject <Dictionary <string, object> >(appSettings); this.userSettings = deserialisedSettings; } } else if (VersionHelper.IsNightly() && File.Exists(this.releaseSettingsFile)) { // Port the release versions config to the nightly. if (!Directory.Exists(DirectoryUtilities.GetUserStoragePath(true))) { Directory.CreateDirectory(DirectoryUtilities.GetUserStoragePath(true)); } File.Copy(this.releaseSettingsFile, this.nightlySettingsFile); using (StreamReader reader = new StreamReader(this.settingsFile)) { string appSettings = reader.ReadToEnd(); Dictionary <string, object> deserialisedSettings = JsonConvert.DeserializeObject <Dictionary <string, object> >(appSettings); this.userSettings = deserialisedSettings; } } else { this.userSettings = new Dictionary <string, object>(); } // Add any missing / new settings Dictionary <string, object> defaults = this.GetDefaults(); foreach (var item in defaults.Where(item => !this.userSettings.Keys.Contains(item.Key))) { this.userSettings.Add(item.Key, item.Value); this.Save(); } this.ResetUnsupportedSettings(); } catch (Exception exc) { try { this.userSettings = this.GetDefaults(); if (File.Exists(this.settingsFile)) { File.Delete(this.settingsFile); } this.Save(); throw new GeneralApplicationException(Resources.UserSettings_YourSettingsHaveBeenReset, Resources.UserSettings_YourSettingsAreCorrupt, exc); } catch (Exception) { throw new GeneralApplicationException(string.Format(Resources.UserSettings_UnableToLoad, this.settingsFile), Resources.UserSettings_UnableToLoadSolution, exc); } } }
protected bool IsSupportedApiVersion(string requiredApiVersion) { VersionHelper.ValidateVersionFormat(requiredApiVersion); return(VersionHelper.CompareVersionTo(requiredApiVersion, ApiVersion) != 1); }
private void cmdOK_Click(object sender, System.EventArgs e) { txtFirstName.Text = txtFirstName.Text.Trim(); txtLastName.Text = txtLastName.Text.Trim(); txtEmail.Text = txtEmail.Text.Trim(); txtPassword.Text = txtPassword.Text.Trim(); if (txtFirstName.Text == string.Empty) { MessageBox.Show("The first name is required.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } else if (txtLastName.Text == string.Empty) { MessageBox.Show("The last name is required.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } else if (cboCountry.SelectedIndex == 0) { MessageBox.Show("The country is required.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } else if (txtEmail.Text == string.Empty) { MessageBox.Show("The email is required.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } else if (txtPassword.Text == string.Empty) { MessageBox.Show("The password is required.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } else if (txtPassword.Text != txtVerify.Text) { MessageBox.Show("The password must be verified.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } ResultModel result = null; try { var model = new UserAccount(); model.FirstName = txtFirstName.Text; model.LastName = txtLastName.Text; model.City = txtCity.Text; model.Region = txtRegion.Text; model.Postcode = txtPostalCode.Text; model.Country = cboCountry.SelectedItem.ToString(); model.Email = txtEmail.Text; model.PremiumKey = txtPremium.Text; model.Password = txtPassword.Text; model.MachineKey = SecurityHelper.GetMachineID(); model.Version = VersionHelper.GetCurrentVersion(); model.AllowStats = chkStat.Checked; result = VersionHelper.RegisterUser(model); } catch (Exception ex) { MessageBox.Show("There was an error trying to register. Please visit the main nHydrate site: https://github.com/nHydrate/nHydrate.", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } if (!result.Success) { MessageBox.Show(result.Text, "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } var key = result.Text; //Validate premium key AddinAppData.Instance.PremiumValidated = false; //if (!string.IsNullOrEmpty(txtPremium.Text)) //{ // var result = service.VerifyPremiumKey(txtEmail.Text, txtPassword.Text, SecurityHelper.GetMachineID(), txtPremium.Text); // if (string.IsNullOrEmpty(result)) // { // AddinAppData.Instance.PremiumValidated = true; // MessageBox.Show("The premium key has been verified and applied. All application features have been enabled.", "Success!", MessageBoxButtons.OK, MessageBoxIcon.Information); // } // else // { // //Display the reason for the error // MessageBox.Show("An error has occurred while verifying your premium key. The failure reason is listed below.\n\n'" + result + "'", "Success!", MessageBoxButtons.OK, MessageBoxIcon.Error); // } //} AddinAppData.Instance.Key = key; AddinAppData.Instance.PremiumKey = txtPremium.Text; AddinAppData.Instance.AllowStats = chkStat.Checked; AddinAppData.Instance.Save(); this.DialogResult = DialogResult.OK; this.Close(); }
public void VersionForType() { var version = VersionHelper.ForType <VersionHelperTests>(); Assert.Equal("1.0.0-tests", version); }
public RawAcceleration() { InitializeComponent(); Version assemVersion = typeof(RawAcceleration).Assembly.GetName().Version; Version driverVersion = null; try { driverVersion = VersionHelper.ValidateAndGetDriverVersion(assemVersion); } catch (VersionException ex) { MessageBox.Show(ex.Message); throw; } ToolStripMenuItem HelpMenuItem = new ToolStripMenuItem("&Help"); HelpMenuItem.DropDownItems.AddRange(new ToolStripItem[] { new ToolStripMenuItem("&About", null, (s, e) => new AboutBox(driverVersion).ShowDialog()) }); menuStrip1.Items.AddRange(new ToolStripItem[] { HelpMenuItem }); AccelGUI = AccelGUIFactory.Construct( this, ManagedAccel.GetActiveAccel(), AccelerationChart, AccelerationChartY, VelocityChart, VelocityChartY, GainChart, GainChartY, accelTypeDropX, accelTypeDropY, writeButton, toggleButton, showVelocityGainToolStripMenuItem, showLastMouseMoveToolStripMenuItem, wholeVectorToolStripMenuItem, byVectorComponentToolStripMenuItem, gainCapToolStripMenuItem, legacyCapToolStripMenuItem, gainOffsetToolStripMenuItem, legacyOffsetToolStripMenuItem, AutoWriteMenuItem, ScaleMenuItem, DPITextBox, PollRateTextBox, sensitivityBoxX, sensitivityBoxY, rotationBox, weightBoxX, weightBoxY, capBoxX, capBoxY, offsetBoxX, offsetBoxY, accelerationBoxX, accelerationBoxY, scaleBoxX, scaleBoxY, limitBoxX, limitBoxY, expBoxX, expBoxY, midpointBoxX, midpointBoxY, sensXYLock, ByComponentXYLock, LockXYLabel, sensitivityLabel, rotationLabel, weightLabelX, weightLabelY, capLabelX, capLabelY, offsetLabelX, offsetLabelY, constantOneLabelX, constantOneLabelY, scaleLabelX, scaleLabelY, limitLabelX, limitLabelY, expLabelX, expLabelY, constantThreeLabelX, constantThreeLabelY, ActiveValueTitle, ActiveValueTitleY, SensitivityActiveXLabel, SensitivityActiveYLabel, RotationActiveLabel, WeightActiveXLabel, WeightActiveYLabel, CapActiveXLabel, CapActiveYLabel, OffsetActiveXLabel, OffsetActiveYLabel, AccelerationActiveLabelX, AccelerationActiveLabelY, ScaleActiveXLabel, ScaleActiveYLabel, LimitActiveXLabel, LimitActiveYLabel, ExpActiveXLabel, ExpActiveYLabel, MidpointActiveXLabel, MidpointActiveYLabel, AccelTypeActiveLabelX, AccelTypeActiveLabelY, OptionSetXTitle, OptionSetYTitle, MouseLabel); }
/// <summary> /// Check if the queue recovery file contains records. /// If it does, it means the last queue did not complete before HandBrake closed. /// So, return a boolean if true. /// </summary> /// <param name="filterQueueFiles"> /// The filter Queue Files. /// </param> /// <returns> /// True if there is a queue to recover. /// </returns> public static List <string> CheckQueueRecovery(List <string> filterQueueFiles) { try { // Check for any Corrupted Backup Files and try recover them RecoverFromBackupFailure(); // Now check for all available recovery files. (There may be more than 1 for multi-instance support) string tempPath = DirectoryUtilities.GetUserStoragePath(VersionHelper.IsNightly()); DirectoryInfo info = new DirectoryInfo(tempPath); IEnumerable <FileInfo> foundFiles = info.GetFiles("*.json").Where(f => f.Name.StartsWith(QueueFileName)); var queueFiles = GetFilesExcludingActiveProcesses(foundFiles, filterQueueFiles); if (!queueFiles.Any()) { return(queueFiles); } List <string> removeFiles = new List <string>(); List <string> acceptedFiles = new List <string>(); foreach (string file in queueFiles) { try { using (StreamReader stream = new StreamReader(file)) { List <QueueTask> list = list = JsonSerializer.Deserialize <List <QueueTask> >(stream.ReadToEnd(), JsonSettings.Options); if (list != null && list.Count == 0) { removeFiles.Add(file); } if (list != null && list.Count != 0) { List <QueueTask> tasks = list.Where(l => l.Status != QueueItemStatus.Completed).ToList(); if (tasks.Count != 0) { acceptedFiles.Add(Path.GetFileName(file)); } else { removeFiles.Add(file); } } } } catch (Exception exc) { Debug.WriteLine(exc); } } CleanupFiles(removeFiles, false); return(acceptedFiles); } catch (Exception exc) { Debug.WriteLine(exc); return(new List <string>()); // Keep quiet about the error. } }
public static void ResetArchives() { string appDataPath = DirectoryUtilities.GetUserStoragePath(VersionHelper.IsNightly()); DirectoryInfo info = new DirectoryInfo(appDataPath); IEnumerable <FileInfo> foundFiles = info.GetFiles("*.archive").Where(f => f.Name.StartsWith(QueueFileName)); foreach (FileInfo file in foundFiles) { string fullPath = Path.Combine(appDataPath, file.Name); File.Move(fullPath, fullPath.Replace(".archive", string.Empty)); } }
/// <summary> /// Tidy up archive files older than 7 days. /// Gives the user an opportunity to recover a queue file they accidentally chose not to import. /// </summary> private static void TidyArchiveFiles() { string appDataPath = DirectoryUtilities.GetUserStoragePath(VersionHelper.IsNightly()); DirectoryInfo info = new DirectoryInfo(appDataPath); IEnumerable <FileInfo> foundFiles = info.GetFiles("*.archive").Where(f => f.Name.StartsWith(QueueFileName)); DateTime lastWeek = DateTime.Now.AddDays(-7); foreach (FileInfo file in foundFiles) { if (file.CreationTime < lastWeek) { string fullPath = Path.Combine(appDataPath, file.Name); File.Delete(fullPath); } } }
static void Main(string[] args) { //Initialize: var mode = "RELEASE"; #if DEBUG mode = "DEBUG"; #endif var environment = Config.Get("environment"); var liveMode = Config.GetBool("live-mode"); Log.DebuggingEnabled = Config.GetBool("debug-mode"); Log.LogHandler = Composer.Instance.GetExportedValueByTypeName <ILogHandler>(Config.Get("log-handler", "CompositeLogHandler")); //Name thread for the profiler: Thread.CurrentThread.Name = "Algorithm Analysis Thread"; Log.Trace("Engine.Main(): LEAN ALGORITHMIC TRADING ENGINE v" + Globals.Version + " Mode: " + mode); Log.Trace("Engine.Main(): Started " + DateTime.Now.ToShortTimeString()); Log.Trace("Engine.Main(): Memory " + OS.ApplicationMemoryUsed + "Mb-App " + +OS.TotalPhysicalMemoryUsed + "Mb-Used " + OS.TotalPhysicalMemory + "Mb-Total"); //Import external libraries specific to physical server location (cloud/local) LeanEngineSystemHandlers leanEngineSystemHandlers; try { leanEngineSystemHandlers = LeanEngineSystemHandlers.FromConfiguration(Composer.Instance); } catch (CompositionException compositionException) { Log.Error("Engine.Main(): Failed to load library: " + compositionException); throw; } //Setup packeting, queue and controls system: These don't do much locally. leanEngineSystemHandlers.Initialize(); //-> Pull job from QuantConnect job queue, or, pull local build: string assemblyPath; var job = leanEngineSystemHandlers.JobQueue.NextJob(out assemblyPath); if (job == null) { throw new Exception("Engine.Main(): Job was null."); } LeanEngineAlgorithmHandlers leanEngineAlgorithmHandlers; try { leanEngineAlgorithmHandlers = LeanEngineAlgorithmHandlers.FromConfiguration(Composer.Instance); } catch (CompositionException compositionException) { Log.Error("Engine.Main(): Failed to load library: " + compositionException); throw; } if (environment.EndsWith("-desktop")) { var info = new ProcessStartInfo { UseShellExecute = false, FileName = Config.Get("desktop-exe"), Arguments = Config.Get("desktop-http-port") }; Process.Start(info); } // log the job endpoints Log.Trace("JOB HANDLERS: "); Log.Trace(" DataFeed: " + leanEngineAlgorithmHandlers.DataFeed.GetType().FullName); Log.Trace(" Setup: " + leanEngineAlgorithmHandlers.Setup.GetType().FullName); Log.Trace(" RealTime: " + leanEngineAlgorithmHandlers.RealTime.GetType().FullName); Log.Trace(" Results: " + leanEngineAlgorithmHandlers.Results.GetType().FullName); Log.Trace(" Transactions: " + leanEngineAlgorithmHandlers.Transactions.GetType().FullName); Log.Trace(" History: " + leanEngineAlgorithmHandlers.HistoryProvider.GetType().FullName); Log.Trace(" Commands: " + leanEngineAlgorithmHandlers.CommandQueue.GetType().FullName); if (job is LiveNodePacket) { Log.Trace(" Brokerage: " + ((LiveNodePacket)job).Brokerage); } // if the job version doesn't match this instance version then we can't process it // we also don't want to reprocess redelivered jobs if (VersionHelper.IsNotEqualVersion(job.Version) || job.Redelivered) { Log.Error("Engine.Run(): Job Version: " + job.Version + " Deployed Version: " + Globals.Version + " Redelivered: " + job.Redelivered); //Tiny chance there was an uncontrolled collapse of a server, resulting in an old user task circulating. //In this event kill the old algorithm and leave a message so the user can later review. leanEngineSystemHandlers.Api.SetAlgorithmStatus(job.AlgorithmId, AlgorithmStatus.RuntimeError, _collapseMessage); leanEngineSystemHandlers.Notify.SetAuthentication(job); leanEngineSystemHandlers.Notify.Send(new RuntimeErrorPacket(job.AlgorithmId, _collapseMessage)); leanEngineSystemHandlers.JobQueue.AcknowledgeJob(job); return; } try { var engine = new Engine.Engine(leanEngineSystemHandlers, leanEngineAlgorithmHandlers, liveMode); engine.Run(job, assemblyPath); } finally { //Delete the message from the job queue: leanEngineSystemHandlers.JobQueue.AcknowledgeJob(job); Log.Trace("Engine.Main(): Packet removed from queue: " + job.AlgorithmId); // clean up resources leanEngineSystemHandlers.Dispose(); leanEngineAlgorithmHandlers.Dispose(); Log.LogHandler.Dispose(); } }
/// <summary> /// Check for Updates /// </summary> /// <param name="callback"> /// The callback. /// </param> public void CheckForUpdates(Action <UpdateCheckInformation> callback) { ThreadPool.QueueUserWorkItem( delegate { try { string url = VersionHelper.Is64Bit() || Environment.Is64BitOperatingSystem ? Constants.Appcast64 : Constants.Appcast32; if (VersionHelper.IsNightly()) { url = VersionHelper.Is64Bit() || Environment.Is64BitOperatingSystem ? Constants.AppcastUnstable64 : Constants.AppcastUnstable32; } var currentBuild = HandBrakeUtils.Build; var skipBuild = this.userSettingService.GetUserSetting <int>(UserSettingConstants.Skipversion); // Initialize variables WebRequest request = WebRequest.Create(url); WebResponse response = request.GetResponse(); var reader = new AppcastReader(); // Get the data, convert it to a string, and parse it into the AppcastReader reader.GetUpdateInfo(new StreamReader(response.GetResponseStream()).ReadToEnd()); // Further parse the information string build = reader.Build; int latest = int.Parse(build); int current = currentBuild; int skip = skipBuild; // If the user wanted to skip this version, don't report the update if (latest == skip) { var info = new UpdateCheckInformation { NewVersionAvailable = false }; callback(info); return; } var info2 = new UpdateCheckInformation { NewVersionAvailable = latest > current, DescriptionUrl = reader.DescriptionUrl, DownloadFile = reader.DownloadFile, Build = reader.Build, Version = reader.Version, }; callback(info2); } catch (Exception exc) { callback(new UpdateCheckInformation { NewVersionAvailable = false, Error = exc }); } }); }
private DataServiceProtocolVersion CalculateDataServiceProtocolVersion(ODataRequest request, ODataResponse response) { DataServiceProtocolVersion dataServiceVersion = VersionHelper.ConvertToDataServiceProtocolVersion(request.GetHeaderValueIfExists(HttpHeaders.DataServiceVersion)); DataServiceProtocolVersion maxDataServiceVersion = VersionHelper.ConvertToDataServiceProtocolVersion(request.GetHeaderValueIfExists(HttpHeaders.MaxDataServiceVersion)); var responseContentType = response.GetHeaderValueIfExists(HttpHeaders.ContentType); if (responseContentType != null) { if (responseContentType.StartsWith(MimeTypes.ApplicationJsonODataLightNonStreaming, StringComparison.OrdinalIgnoreCase) || responseContentType.StartsWith(MimeTypes.ApplicationJsonODataLightStreaming, StringComparison.OrdinalIgnoreCase)) { return(DataServiceProtocolVersion.V4); } } if (response.StatusCode.IsError()) { return(DataServiceProtocolVersion.V4); } DataServiceProtocolVersion expectedVersion = DataServiceProtocolVersion.V4; // Apply minDsv if MPV > V2 if (maxDataServiceVersion != DataServiceProtocolVersion.Unspecified && this.maxProtocolVersion >= maxDataServiceVersion) { expectedVersion = maxDataServiceVersion; } else { expectedVersion = this.maxProtocolVersion; } // If body of a response is empty, the version is V1 unless it has prefer header. if (!this.IsResponseBodyEmpty(response)) { if (request.Uri.IsMetadata()) { // metadata payloads are not handled by the normal payload element visitor, but the response header will match the model version exactly expectedVersion = VersionHelper.IncreaseVersionIfRequired(expectedVersion, this.ModelVersionCalculator.CalculateProtocolVersion(this.model)); } else { // GET requests are versioned based on the URI because type information is not known until serialization if (request.GetEffectiveVerb() == HttpVerb.Get || request.Uri.IsServiceOperation() || request.Uri.IsAction()) { expectedVersion = VersionHelper.IncreaseVersionIfRequired(expectedVersion, this.UriVersionCalculator.CalculateProtocolVersion(request.Uri, response.Headers[HttpHeaders.ContentType], this.maxProtocolVersion, dataServiceVersion, maxDataServiceVersion)); } // Post and update requests are versioned based on the specific instance if (response.RootElement != null) { expectedVersion = VersionHelper.IncreaseVersionIfRequired(expectedVersion, this.PayloadElementVersionCalculator.CalculateProtocolVersion(response.RootElement, response.Headers[HttpHeaders.ContentType], this.maxProtocolVersion, maxDataServiceVersion)); } } } else { if (request.Uri.IsAction()) { expectedVersion = VersionHelper.IncreaseVersionIfRequired(expectedVersion, this.UriVersionCalculator.CalculateProtocolVersion(request.Uri, response.GetHeaderValueIfExists(HttpHeaders.ContentType), this.maxProtocolVersion, dataServiceVersion, maxDataServiceVersion)); } } // NOTE: the prefer verifier will ensure that this header is present if it should be, so our only concern here // is that the version is >= V3 if it is present if (response.Headers.ContainsKey(HttpHeaders.PreferenceApplied)) { expectedVersion = VersionHelper.IncreaseVersionIfRequired(expectedVersion, DataServiceProtocolVersion.V4); } return(expectedVersion); }
protected virtual SemVersion GetPluginVersion() { return(VersionHelper.ParseAssemblyVersion(GetType().Assembly)); }
/// <summary> /// Check for Updates /// </summary> /// <param name="callback"> /// The callback. /// </param> public void CheckForUpdates(Action <UpdateCheckInformation> callback) { ThreadPool.QueueUserWorkItem( delegate { try { // Figure out which appcast we want to read. string url = VersionHelper.Is64Bit() || Environment.Is64BitOperatingSystem ? Constants.Appcast64 : Constants.Appcast32; if (VersionHelper.IsNightly()) { url = VersionHelper.Is64Bit() || Environment.Is64BitOperatingSystem ? Constants.AppcastUnstable64 : Constants.AppcastUnstable32; } var currentBuild = HandBrakeUtils.Build; // Fetch the Appcast from our server. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.AllowAutoRedirect = false; // We will never do this. WebResponse response = request.GetResponse(); // Parse the data with the AppcastReader var reader = new AppcastReader(); reader.GetUpdateInfo(new StreamReader(response.GetResponseStream()).ReadToEnd()); // Further parse the information string build = reader.Build; int latest = int.Parse(build); int current = currentBuild; // Security Check // Verify the download URL is for handbrake.fr and served over https. // This prevents a compromised appcast download tricking the GUI into downloading a file, or accessing another website or local network resource. Uri uriResult; bool result = Uri.TryCreate(reader.DownloadFile, UriKind.Absolute, out uriResult) && uriResult.Scheme == Uri.UriSchemeHttps; if (!result || (uriResult.Host != "handbrake.fr" && uriResult.Host != "download.handbrake.fr")) { callback(new UpdateCheckInformation { NewVersionAvailable = false, Error = new Exception("The HandBrake update service is currently unavailable.") }); return; } // Validate the URL from the appcast is ours. var info2 = new UpdateCheckInformation { NewVersionAvailable = latest > current, DescriptionUrl = reader.DescriptionUrl, DownloadFile = reader.DownloadFile, Build = reader.Build, Version = reader.Version, Signature = reader.Hash }; callback(info2); } catch (Exception exc) { callback(new UpdateCheckInformation { NewVersionAvailable = false, Error = exc }); } }); }
public FatalErrorWindow() { Log.Debug("ctor"); Build(); Title += VersionHelper.GetVersionString(); }
public IEnumerable <VersionDTO> GetAllVersions() => VersionHelper.GetAllVersions();
/// <summary> /// Download the update file. /// </summary> /// <param name="url"> /// The url. /// </param> /// <param name="expectedSignature"> /// The expected DSA SHA265 Signature /// </param> /// <param name="completed"> /// The complete. /// </param> /// <param name="progress"> /// The progress. /// </param> public void DownloadFile(string url, string expectedSignature, Action <DownloadStatus> completed, Action <DownloadStatus> progress) { ThreadPool.QueueUserWorkItem( delegate { string tempPath = Path.Combine(Path.GetTempPath(), "handbrake-setup.exe"); WebClient wcDownload = new WebClient(); try { if (File.Exists(tempPath)) { File.Delete(tempPath); } HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url); webRequest.Credentials = CredentialCache.DefaultCredentials; webRequest.UserAgent = string.Format("HandBrake Win Upd {0}", VersionHelper.GetVersionShort()); HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse(); long fileSize = webResponse.ContentLength; Stream responceStream = wcDownload.OpenRead(url); Stream localStream = new FileStream(tempPath, FileMode.Create, FileAccess.Write, FileShare.None); int bytesSize; byte[] downBuffer = new byte[2048]; while ((bytesSize = responceStream.Read(downBuffer, 0, downBuffer.Length)) > 0) { localStream.Write(downBuffer, 0, bytesSize); progress(new DownloadStatus { BytesRead = localStream.Length, TotalBytes = fileSize }); } responceStream.Close(); localStream.Close(); completed( this.VerifyDownload(expectedSignature, tempPath) ? new DownloadStatus { WasSuccessful = true, Message = "Download Complete." } : new DownloadStatus { WasSuccessful = false, Message = "Download Failed. Checksum Failed. Please visit the website to download this update." }); } catch (Exception exc) { progress(new DownloadStatus { WasSuccessful = false, Exception = exc, Message = "Download Failed. Please visit the website to download this update." }); } }); }
/// <summary> /// Check if the queue recovery file contains records. /// If it does, it means the last queue did not complete before HandBrake closed. /// So, return a boolean if true. /// </summary> /// <returns> /// True if there is a queue to recover. /// </returns> public static List <string> CheckQueueRecovery(List <string> filterQueueFiles) { try { string tempPath = DirectoryUtilities.GetUserStoragePath(VersionHelper.IsNightly()); DirectoryInfo info = new DirectoryInfo(tempPath); IEnumerable <FileInfo> foundFiles = info.GetFiles("*.xml").Where(f => f.Name.StartsWith("hb_queue_recovery")); var queueFiles = GetFilesExcludingActiveProcesses(foundFiles, filterQueueFiles); if (!queueFiles.Any()) { return(queueFiles); } List <string> removeFiles = new List <string>(); List <string> acceptedFiles = new List <string>(); XmlSerializer ser = new XmlSerializer(typeof(List <QueueTask>)); foreach (string file in queueFiles) { try { using (FileStream strm = new FileStream(file, FileMode.Open, FileAccess.Read)) { List <QueueTask> list = ser.Deserialize(strm) as List <QueueTask>; if (list != null && list.Count == 0) { removeFiles.Add(file); } if (list != null && list.Count != 0) { List <QueueTask> tasks = list.Where(l => l.Status != QueueItemStatus.Completed).ToList(); if (tasks.Count != 0) { acceptedFiles.Add(Path.GetFileName(file)); } else { removeFiles.Add(file); } } } } catch (Exception exc) { Debug.WriteLine(exc); } } CleanupFiles(removeFiles); return(acceptedFiles); } catch (Exception exc) { Debug.WriteLine(exc); return(new List <string>()); // Keep quiet about the error. } }
public static bool HasVersion(this PackageSpecification package) { var hasVersion = !VersionHelper.IsNone(package.Version); return(hasVersion); }
public void FromGitDescription_ArgumentEmpty() { VersionHelper.ParseGitDescription(string.Empty); }
public IVersionSupport CreateNewVersion() { VersionHelper vHelper = new VersionHelper(this.Session); return(vHelper.CreateNewVersion((IVersionSupport)(((crmDealWithoutStage)(this.MainObject)).Current), vHelper)); }
public void GetVersion_Test() { string myVersion = "1.0.1"; Assert.AreEqual($"{VersionHelper.VERSION_PREFIX}{myVersion}", VersionHelper.GetVersion(myVersion)); }
/// <summary> /// Load in the Built-in and User presets into the collection /// </summary> private void LoadPresets() { // First clear the Presets arraylists this.presets.Clear(); // Load the presets file. try { // If we don't have a presets file. Create one for first load. if (!File.Exists(this.presetFile)) { // If this is a nightly, and we don't have a presets file, try port the main version if it exists. string releasePresetFile = Path.Combine(DirectoryUtilities.GetUserStoragePath(false), "presets.json"); if (VersionHelper.IsNightly() && File.Exists(releasePresetFile)) { File.Copy(releasePresetFile, DirectoryUtilities.GetUserStoragePath(true)); } else { this.UpdateBuiltInPresets(); return; // Update built-in presets stores the presets locally, so just return. } } // Otherwise, we already have a file, so lets try load it. PresetTransportContainer container = null; using (StreamReader reader = new StreamReader(this.presetFile)) { try { container = JsonConvert.DeserializeObject <PresetTransportContainer>(reader.ReadToEnd()); } catch (Exception exc) { Debug.WriteLine("Failed to parse presets file: " + exc); } } // Sanity Check. Did the container deserialise. if (container == null || container.PresetList == null) { string filename = this.RecoverFromCorruptedPresetFile(this.presetFile); this.errorService.ShowMessageBox( Resources.PresetService_UnableToLoadPresets + filename, Resources.PresetService_UnableToLoad, MessageBoxButton.OK, MessageBoxImage.Exclamation); this.UpdateBuiltInPresets(); return; // Update built-in presets stores the presets locally, so just return. } // Version Check // If we have old presets, or the container wasn't parseable, or we have a version mismatch, backup the user preset file // incase something goes wrong and reset built-in presets, then re-save. if (container.VersionMajor != Constants.PresetVersionMajor || container.VersionMinor != Constants.PresetVersionMinor || container.VersionMicro != Constants.PresetVersionMicro) { string fileName = this.ArchivePresetFile(this.presetFile); this.errorService.ShowMessageBox( Resources.PresetService_PresetsOutOfDate + Environment.NewLine + Environment.NewLine + Resources.PresetService_ArchiveFile + fileName, Resources.PresetService_UnableToLoad, MessageBoxButton.OK, MessageBoxImage.Exclamation); this.UpdateBuiltInPresets(); // Update built-in presets stores the presets locally, so just return. return; } // Force Upgrade of presets if (this.userSettingService.GetUserSetting <int>(UserSettingConstants.ForcePresetReset) < ForcePresetReset) { this.userSettingService.SetUserSetting(UserSettingConstants.ForcePresetReset, ForcePresetReset); string fileName = this.ArchivePresetFile(this.presetFile); this.errorService.ShowMessageBox( Resources.Presets_PresetForceReset + Environment.NewLine + Environment.NewLine + Resources.PresetService_ArchiveFile + fileName, Resources.PresetService_UnableToLoad, MessageBoxButton.OK, MessageBoxImage.Exclamation); this.UpdateBuiltInPresets(); // Update built-in presets stores the presets locally, so just return. return; } // The presets file loaded was OK, so process it. foreach (var item in container.PresetList) { object deserialisedItem = JsonConvert.DeserializeObject <PresetCategory>(item.ToString()); // Handle Categorised Presets. PresetCategory category = deserialisedItem as PresetCategory; if (category != null && category.Folder) { foreach (HBPreset hbpreset in category.ChildrenArray) { Preset preset = JsonPresetFactory.ImportPreset(hbpreset); preset.Category = category.PresetName; preset.IsBuildIn = hbpreset.Type == 0; // IF we are using Source Max, Set the Max Width / Height values. if (preset.PictureSettingsMode == PresetPictureSettingsMode.SourceMaximum) { preset.Task.MaxWidth = preset.Task.Height; preset.Task.MaxHeight = preset.Task.Width; } this.Add(preset, true); } } // Uncategorised Presets deserialisedItem = JsonConvert.DeserializeObject <HBPreset>(item.ToString()); HBPreset hbPreset = deserialisedItem as HBPreset; if (hbPreset != null && !hbPreset.Folder) { Preset preset = JsonPresetFactory.ImportPreset(hbPreset); preset.Category = UserPresetCatgoryName; preset.IsBuildIn = hbPreset.Type == 1; // IF we are using Source Max, Set the Max Width / Height values. if (preset.PictureSettingsMode == PresetPictureSettingsMode.SourceMaximum) { preset.Task.MaxWidth = preset.Task.Height; preset.Task.MaxHeight = preset.Task.Width; } this.Add(preset, true); } } } catch (Exception ex) { Debug.WriteLine(ex); this.RecoverFromCorruptedPresetFile(this.presetFile); this.UpdateBuiltInPresets(); } }
static void Main(string[] args) { //Initialize: var mode = "RELEASE"; #if DEBUG mode = "DEBUG"; #endif if (OS.IsWindows) { Console.OutputEncoding = System.Text.Encoding.UTF8; } // expect first argument to be config file name if (args.Length > 0) { Config.MergeCommandLineArgumentsWithConfiguration(LeanArgumentParser.ParseArguments(args)); } var environment = Config.Get("environment"); var liveMode = Config.GetBool("live-mode"); Log.DebuggingEnabled = Config.GetBool("debug-mode"); Log.LogHandler = Composer.Instance.GetExportedValueByTypeName <ILogHandler>(Config.Get("log-handler", "CompositeLogHandler")); //Name thread for the profiler: Thread.CurrentThread.Name = "Algorithm Analysis Thread"; Log.Trace("Engine.Main(): LEAN ALGORITHMIC TRADING ENGINE v" + Globals.Version + " Mode: " + mode + " (" + (Environment.Is64BitProcess ? "64" : "32") + "bit)"); Log.Trace("Engine.Main(): Started " + DateTime.Now.ToShortTimeString()); //Import external libraries specific to physical server location (cloud/local) LeanEngineSystemHandlers leanEngineSystemHandlers; try { leanEngineSystemHandlers = LeanEngineSystemHandlers.FromConfiguration(Composer.Instance); } catch (CompositionException compositionException) { Log.Error("Engine.Main(): Failed to load library: " + compositionException); throw; } //Setup packeting, queue and controls system: These don't do much locally. leanEngineSystemHandlers.Initialize(); //-> Pull job from QuantConnect job queue, or, pull local build: string assemblyPath; var job = leanEngineSystemHandlers.JobQueue.NextJob(out assemblyPath); if (job == null) { throw new Exception("Engine.Main(): Job was null."); } LeanEngineAlgorithmHandlers leanEngineAlgorithmHandlers; try { leanEngineAlgorithmHandlers = LeanEngineAlgorithmHandlers.FromConfiguration(Composer.Instance); } catch (CompositionException compositionException) { Log.Error("Engine.Main(): Failed to load library: " + compositionException); throw; } // if the job version doesn't match this instance version then we can't process it // we also don't want to reprocess redelivered jobs if (VersionHelper.IsNotEqualVersion(job.Version) || job.Redelivered) { Log.Error("Engine.Run(): Job Version: " + job.Version + " Deployed Version: " + Globals.Version + " Redelivered: " + job.Redelivered); //Tiny chance there was an uncontrolled collapse of a server, resulting in an old user task circulating. //In this event kill the old algorithm and leave a message so the user can later review. leanEngineSystemHandlers.Api.SetAlgorithmStatus(job.AlgorithmId, AlgorithmStatus.RuntimeError, _collapseMessage); leanEngineSystemHandlers.Notify.SetAuthentication(job); leanEngineSystemHandlers.Notify.Send(new RuntimeErrorPacket(job.UserId, job.AlgorithmId, _collapseMessage)); leanEngineSystemHandlers.JobQueue.AcknowledgeJob(job); return; } try { var algorithmManager = new AlgorithmManager(liveMode); leanEngineSystemHandlers.LeanManager.Initialize(leanEngineSystemHandlers, leanEngineAlgorithmHandlers, job, algorithmManager); var engine = new Engine.Engine(leanEngineSystemHandlers, leanEngineAlgorithmHandlers, liveMode); engine.Run(job, algorithmManager, assemblyPath); } finally { //Delete the message from the job queue: leanEngineSystemHandlers.JobQueue.AcknowledgeJob(job); Log.Trace("Engine.Main(): Packet removed from queue: " + job.AlgorithmId); // clean up resources leanEngineSystemHandlers.Dispose(); leanEngineAlgorithmHandlers.Dispose(); Log.LogHandler.Dispose(); Log.Trace("Program.Main(): Exiting Lean..."); Environment.Exit(0); } }
public static bool ArchivesExist() { string appDataPath = DirectoryUtilities.GetUserStoragePath(VersionHelper.IsNightly()); DirectoryInfo info = new DirectoryInfo(appDataPath); IEnumerable <FileInfo> foundFiles = info.GetFiles("*.archive").Where(f => f.Name.StartsWith(QueueFileName)); return(foundFiles.Any()); }