public void Setup() { EnvironmentHelper.SetTestEnvironmentVariable(); DynamicSerializersInitializer.Init(); }
public void GetConnectionTimeoutShouldReturnDefaultValue() { Assert.AreEqual(EnvironmentHelperTests.DefaultTimeout, EnvironmentHelper.GetConnectionTimeout()); }
public void GetConnectionTimeoutShouldReturnDefaultOnEnvVariableValueDecimal() { Environment.SetEnvironmentVariable(EnvironmentHelper.VstestConnectionTimeout, "10.4"); Assert.AreEqual(EnvironmentHelperTests.DefaultTimeout, EnvironmentHelper.GetConnectionTimeout()); }
private void LoginButton_Click(object sender, RoutedEventArgs e) { if (LoginBox.Text != "" && PassBox.Password != "") { bool isAdmin = false; var hash = ""; var hashfromsql = ""; using (var md5Hash = MD5.Create()) { var data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(PassBox.Password)); var sBuilder = new StringBuilder(); foreach (var item in data) { sBuilder.Append(item.ToString("x2")); } hash = sBuilder.ToString(); } try { using (var con = new SqlConnection(SystemSingleton.Configuration.ConnectionString)) { SystemSingleton.Configuration.SqlConnections.Add(con); using (var command = new SqlCommand(SqlCommands.LoginCommand, con)) { command.Parameters.Add("@LoginText", SqlDbType.NVarChar); command.Parameters["@LoginText"].Value = LoginBox.Text; EnvironmentHelper.SendLogSQL(command.CommandText); con.Open(); using (var reader = command.ExecuteReader()) { if (reader.Read()) { SystemSingleton.CurrentSession.ID = reader.GetGuid(0); hashfromsql = reader.GetString(1); SystemSingleton.CurrentSession.TelegramID = reader.GetInt64(2); SystemSingleton.CurrentSession.FirstName = reader.GetString(3); SystemSingleton.CurrentSession.LastName = reader.GetString(4); SystemSingleton.CurrentSession.FullName = reader.GetString(5); isAdmin = reader.GetBoolean(6); } } con.Close(); } } } catch (Exception ex) { EnvironmentHelper.SendErrorDialogBox(ex.Message, "SQL Error", ex.StackTrace); } if (SystemSingleton.CurrentSession.ID == Guid.Empty || hash != hashfromsql) { SendAttentionToBottomBar("m_tab_LogIn_PasWrong"); SystemSingleton.CurrentSession.CloseSession(); } else if (!isAdmin) { SendAttentionToBottomBar("m_tab_LogIn_NotAdmin_PasWrong"); SystemSingleton.CurrentSession.CloseSession(); } else { SystemSingleton.CurrentSession.Login = LoginBox.Text; PassBox.Clear(); ClearBottomBar(); LogOffItem.Visibility = Visibility.Visible; WorkingTab.Visibility = Visibility.Visible; TabControl.SelectedIndex = 1; LoginTab.Visibility = Visibility.Collapsed; menuLanguage.Visibility = Visibility.Collapsed; EnvironmentHelper.SendLog("Log In - " + SystemSingleton.CurrentSession.Login); OnLogin(); } } else { SendAttentionToBottomBar("m_tab_LogIn_LogOrPassNotTyped"); } }
private void UpdateButton_Click(object sender, RoutedEventArgs e) { EnvironmentHelper.UpdateView(); }
private bool CheckSqlServer() { // disabled since not fixed yet // return true; return(EnvironmentHelper.CheckSqlServer()); }
public void InitPluginCore( TabPage pluginScreenSpace, Label pluginStatusText) { // タイトルをセットする pluginScreenSpace.Text = "SPESPE"; EnvironmentMigrater.Migrate(); MasterFilePublisher.Publish(); WPFHelper.Start(); WPFHelper.BeginInvoke(async() => { AppLog.LoadConfiguration(AppLog.HojoringConfig); this.AppLogger?.Trace(Assembly.GetExecutingAssembly().GetName().ToString() + " start."); try { this.PluginStatusLabel = pluginStatusText; if (!EnvironmentHelper.IsValidPluginLoadOrder()) { if (pluginStatusText != null) { pluginStatusText.Text = "Plugin Initialize Error"; } return; } EnvironmentHelper.GarbageLogs(); EnvironmentHelper.StartActivator(() => { BaseView.Instance.SetActivationStatus(false); this.DeInitPluginCore(); }); Logger.Init(); Logger.Write("[SPESPE] Start InitPlugin"); // .NET FrameworkとOSのバージョンを確認する if (!UpdateChecker.IsAvailableDotNet() || !UpdateChecker.IsAvailableWindows()) { NotSupportedView.AddAndShow(pluginScreenSpace); return; } // FFXIV.Framework.config を読み込ませる lock (FFXIV.Framework.Config.ConfigBlocker) { _ = FFXIV.Framework.Config.Instance; } // HojoringのSplashを表示する UpdateChecker.ShowSplash(); // 外部リソースをダウンロードする await ResourcesDownloader.Instance.DownloadAsync(); // メイン設定ファイルを読み込む Settings.Default.Load(); Settings.Default.ApplyRenderMode(); Settings.Default.StartAutoSave(); // 最小化する? if (Settings.Default.IsMinimizeOnStart) { ActGlobals.oFormActMain.WindowState = FormWindowState.Minimized; } // 自身の場所を格納しておく var plugin = ActGlobals.oFormActMain.PluginGetSelfData(this.PluginRoot); if (plugin != null) { this.Location = plugin.pluginFile.DirectoryName; } // 設定ファイルを読み込む SpellPanelTable.Instance.Load(); SpellTable.Instance.Load(); TickerTable.Instance.Load(); TagTable.Instance.Load(); _ = TimelineSettings.Instance; // 設定ファイルをバックアップする await EnvironmentHelper.BackupFilesAsync( Settings.Default.FileName, SpellPanelTable.Instance.DefaultFile, SpellTable.Instance.DefaultFile, TickerTable.Instance.DefaultFile, TagTable.Instance.DefaultFile, TimelineSettings.FileName, FFXIV.Framework.Config.FileName); TTSDictionary.Instance.Load(); // 設定Panelを追加する var baseView = new BaseView(pluginScreenSpace.Font); pluginScreenSpace.Controls.Add(new ElementHost() { Child = baseView, Dock = DockStyle.Fill, Font = pluginScreenSpace.Font, }); EnvironmentHelper.WaitInitActDone(); // 本体を開始する PluginMainWorker.Instance.Begin(); TimelineController.Init(); // 付加情報オーバーレイを表示する LPSView.ShowLPS(); POSView.ShowPOS(); this.SetSwitchVisibleButton(); if (this.PluginStatusLabel != null) { this.PluginStatusLabel.Text = "Plugin Started"; } Logger.Write("[SPESPE] End InitPlugin"); // 共通ビューを追加する CommonViewHelper.Instance.AddCommonView( pluginScreenSpace.Parent as TabControl); this.isLoaded = true; // アップデートを確認する await Task.Run(() => this.Update()); } catch (Exception ex) { Logger.Write("InitPlugin error.", ex); if (this.PluginStatusLabel != null) { this.PluginStatusLabel.Text = "Plugin Initialize Error"; } ModernMessageBox.ShowDialog( "Plugin init error !", "ACT.SpecialSpellTimer", System.Windows.MessageBoxButton.OK, ex); } }); }
/// <summary> /// Runs application. /// </summary> /// <param name="args">CLI arguments.</param> /// <param name="cancellationToken">Cancellation token</param> public async Task <int> RunAsync(string[] args, CancellationToken cancellationToken = default) { await Task.Yield(); // process CLI args var arguments = Cli.Parse <TArgs>(args); if (arguments.HelpInvoked) { return(0); } if (arguments.ShowVersion) { Console.WriteLine($"App version: {ApplicationHelper.GetAssemblyVersion()}"); return(CuriosityExitCodes.Success); } // basic app setup: culture, content root directory var customContentRootDirectory = String.Empty; if (EnvironmentHelper.IsDevelopmentEnvironment()) { customContentRootDirectory = Directory.GetCurrentDirectory(); } ApplicationHelper.ChangeCurrentDirectoryForDevelopment(); // get configuration var configurationProvider = new YamlConfigurationProvider <TConfiguration>(arguments.ConfigurationDirectory, IsConfigFileOptional, args); var configuration = configurationProvider.GetConfiguration(); ApplicationHelper.SetDefaultCulture(configuration.Culture); // configure logs var loggingConfiguration = new CuriosityNLogConfigurator(configuration.Log.LogConfigurationPath, LoadLoggingConfiguration); loggingConfiguration.WithLogOutputDirectory(configuration.Log.LogOutputDirectory); loggingConfiguration.WithAppName(configuration.AppName); // ReSharper disable once SuspiciousTypeConversion.Global if (configuration is IConfigurationWithMailLogger configurationWithMailLogger) { loggingConfiguration.WithMail(configurationWithMailLogger.LoggerMail); } loggingConfiguration.Configure(); var logger = LogManager.GetCurrentClassLogger(); logger.Info($"Using configurations from directory \"{configurationProvider.PathToConfigurationFiles}\"'"); // print configuration var configPrinter = new ConfigurationPrinter(); var configLog = configPrinter.GetLog(configuration); logger.Info($"Starting app with configuration: \n{configLog ?? "<no config>"}"); // validate configuration var errors = configuration.Validate(); if (errors.Count == 0) { logger.Info("Configuration is valid."); } else { var errorsBuilder = new StringBuilder(); foreach (var validationError in errors) { errorsBuilder.AppendLine($"- {validationError.FieldName}: {validationError.Error}"); } logger.Error($"Configuration is invalid. Errors: {Environment.NewLine}{errorsBuilder}"); return(CuriosityExitCodes.IncorrectConfiguration); } try { var startEmailLogger = LogManager.GetLogger("appStartEmailLog"); startEmailLogger.Info($"{configuration.AppName} is started"); return(await RunInternalAsync(args, arguments, configuration, configurationProvider, customContentRootDirectory, cancellationToken)); } catch (Exception e) when(e is OperationCanceledException || e is TaskCanceledException) { logger.Warn(e, $"{configuration.AppName} was cancelled."); return(CuriosityExitCodes.Cancellation); } catch (Exception e) { logger.Fatal(e, $"Critical error on {configuration.AppName} work"); return(CuriosityExitCodes.UnhandledException); } finally { var startEmailLogger = LogManager.GetLogger("appStopEmailLog"); startEmailLogger.Info($"{configuration.AppName} is stopped"); // Ensure to flush and stop internal timers/threads before application-exit (Avoid segmentation fault on Linux) LogManager.Shutdown(); } }
static PathComparer() { Default = new PathComparer(EnvironmentHelper.IsUnix()); }
/// <inheritdoc /> public void CheckVersionWithTestHost() { // Negotiation follows these steps: // Runner sends highest supported version to Test host // Test host sends the version it can support (must be less than highest) to runner // Error case: test host can send a protocol error if it cannot find a supported version var protocolNegotiated = new ManualResetEvent(false); this.onMessageReceived = (sender, args) => { var message = this.dataSerializer.DeserializeMessage(args.Data); if (EqtTrace.IsVerboseEnabled) { EqtTrace.Verbose("TestRequestSender.CheckVersionWithTestHost: onMessageReceived received message: {0}", message); } if (message.MessageType == MessageType.VersionCheck) { this.protocolVersion = this.dataSerializer.DeserializePayload <int>(message); } // TRH can also send TestMessage if tracing is enabled, so log it at runner end else if (message.MessageType == MessageType.TestMessage) { // Ignore test messages. Currently we don't have handler(which sends messages to client/console.) here. // Above we are logging it to EqtTrace. } else if (message.MessageType == MessageType.ProtocolError) { throw new TestPlatformException(string.Format(CultureInfo.CurrentUICulture, CommonResources.VersionCheckFailed)); } else { throw new TestPlatformException(string.Format( CultureInfo.CurrentUICulture, CommonResources.UnexpectedMessage, MessageType.VersionCheck, message.MessageType)); } protocolNegotiated.Set(); }; this.channel.MessageReceived += this.onMessageReceived; try { // Send the protocol negotiation request. Note that we always serialize this data // without any versioning in the message itself. var data = this.dataSerializer.SerializePayload(MessageType.VersionCheck, this.highestSupportedVersion); this.channel.Send(data); // Wait for negotiation response var timeout = EnvironmentHelper.GetConnectionTimeout(); if (!protocolNegotiated.WaitOne(timeout * 1000)) { throw new TestPlatformException(string.Format(CultureInfo.CurrentUICulture, CommonResources.VersionCheckTimedout, timeout, EnvironmentHelper.VstestConnectionTimeout)); } } finally { this.channel.MessageReceived -= this.onMessageReceived; this.onMessageReceived = null; } }
/// <summary> /// Method to execute a smoke test. /// </summary> /// <param name="shouldDeserializeTraces">Optimization parameter, pass false when the resulting traces aren't being verified</param> protected void CheckForSmoke(bool shouldDeserializeTraces = true) { var applicationPath = EnvironmentHelper.GetSampleApplicationPath().Replace(@"\\", @"\"); Output.WriteLine($"Application path: {applicationPath}"); var executable = EnvironmentHelper.GetSampleExecutionSource(); Output.WriteLine($"Executable path: {executable}"); if (!System.IO.File.Exists(applicationPath)) { throw new Exception($"Smoke test file does not exist: {applicationPath}"); } // clear all relevant environment variables to start with a clean slate EnvironmentHelper.ClearProfilerEnvironmentVariables(); int agentPort = TcpPortProvider.GetOpenPort(); int aspNetCorePort = TcpPortProvider.GetOpenPort(); // unused for now Output.WriteLine($"Assigning port {agentPort} for the agentPort."); Output.WriteLine($"Assigning port {aspNetCorePort} for the aspNetCorePort."); ProcessResult result; using (var agent = new MockTracerAgent(agentPort)) { agent.ShouldDeserializeTraces = shouldDeserializeTraces; // Using the following code to avoid possible hangs on WaitForExit due to synchronous reads: https://stackoverflow.com/questions/139593/processstartinfo-hanging-on-waitforexit-why using (var process = new Process()) { // Initialize StartInfo process.StartInfo.FileName = executable; EnvironmentHelper.SetEnvironmentVariables(agentPort, aspNetCorePort, statsdPort: null, executable, process.StartInfo.EnvironmentVariables); if (EnvironmentHelper.IsCoreClr()) { // Command becomes: dotnet.exe <applicationPath> process.StartInfo.Arguments = applicationPath; } process.StartInfo.UseShellExecute = false; process.StartInfo.CreateNoWindow = true; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.RedirectStandardError = true; process.StartInfo.RedirectStandardInput = false; process.Start(); using var helper = new ProcessHelper(process); var ranToCompletion = process.WaitForExit(MaxTestRunMilliseconds) && helper.Drain(MaxTestRunMilliseconds / 2); var standardOutput = helper.StandardOutput; var standardError = helper.ErrorOutput; if (!ranToCompletion) { if (!process.HasExited) { try { process.Kill(); } catch { // Do nothing } } if (AssumeSuccessOnTimeout) { Assert.True(true, "No smoke is a good sign for this case, even on timeout."); return; } else { Output.WriteLine("The smoke test is running for too long or was lost."); Output.WriteLine($"StandardOutput:{Environment.NewLine}{standardOutput}"); Output.WriteLine($"StandardError:{Environment.NewLine}{standardError}"); throw new TimeoutException("The smoke test is running for too long or was lost."); } } if (!string.IsNullOrWhiteSpace(standardOutput)) { Output.WriteLine($"StandardOutput:{Environment.NewLine}{standardOutput}"); } if (!string.IsNullOrWhiteSpace(standardError)) { Output.WriteLine($"StandardError:{Environment.NewLine}{standardError}"); } int exitCode = process.ExitCode; result = new ProcessResult(process, standardOutput, standardError, exitCode); } } var successCode = 0; Assert.True(successCode == result.ExitCode, $"Non-success exit code {result.ExitCode}"); Assert.True(string.IsNullOrEmpty(result.StandardError), $"Expected no errors in smoke test: {result.StandardError}"); }
public void Initialize() { var tracer = _tracerFactory.GetTracer(); using (tracer.Step("LibGit2SharpRepository Initialize")) { var dotGitPath = LibGit2Sharp.Repository.Init(RepositoryPath); using (var repo = new LibGit2Sharp.Repository(dotGitPath)) { repo.Config.Set("core.autocrlf", OSDetector.IsOnWindows()); // This speeds up git operations like 'git checkout', especially on slow drives like in Azure repo.Config.Set("core.preloadindex", true); repo.Config.Set("user.name", _settings.GetGitUsername()); repo.Config.Set("user.email", _settings.GetGitEmail()); // This is needed to make lfs work repo.Config.Set("filter.lfs.clean", "git-lfs clean %f"); repo.Config.Set("filter.lfs.smudge", "git-lfs smudge %f"); repo.Config.Set("filter.lfs.required", true); using (tracer.Step("Configure git server")) { // Allow getting pushes even though we're not bare repo.Config.Set("receive.denyCurrentBranch", "ignore"); } // to disallow browsing to this folder in case of in-place repo using (tracer.Step("Create deny users for .git folder")) { string content = "<?xml version=\"1.0\"" + @"?> <configuration> <system.web> <authorization> <deny users=" + "\"*\"" + @"/> </authorization> </system.web> <configuration>"; File.WriteAllText(Path.Combine(dotGitPath, "web.config"), content); } // Server env does not support interactive cred prompt; hence, we intercept any credential provision // for git fetch/clone with http/https scheme and return random invalid u/p forcing 'fatal: Authentication failed.' using (tracer.Step("Configure git-credential")) { FileSystemHelpers.EnsureDirectory(Path.GetDirectoryName(GitCredentialHookPath)); string content = @"#!/bin/sh if [ " + "\"$1\" = \"get\"" + @" ]; then echo username=dummyUser echo password=dummyPassword fi" + "\n"; File.WriteAllText(GitCredentialHookPath, content); repo.Config.Set("credential.helper", string.Format("!'{0}'", GitCredentialHookPath)); } } using (tracer.Step("Setup post receive hook")) { FileSystemHelpers.EnsureDirectory(Path.GetDirectoryName(PostReceiveHookPath)); var command = ""; if (EnvironmentHelper.IsDynamicInstallEnvironment()) { command = KnownEnvironment.KUDUCOMMAND_DYNAMICINSTALL; } else { command = KnownEnvironment.KUDUCOMMAND; } var content = @"#!/bin/sh read i echo $i > pushinfo " + command + "\r\n"; File.WriteAllText(PostReceiveHookPath, content); } // NOTE: don't add any new init steps after creating the post receive hook, // as it's also used to mark that Init was fully executed } }
static int Main(string[] args) { var program = new Program("Calamari", typeof(Program).GetTypeInfo().Assembly.GetInformationalVersion(), EnvironmentHelper.SafelyGetEnvironmentInformation()); return(program.Execute(args)); }
public void Setup() { EnvironmentHelper.SetTestEnvironmentVariable(); var settings = new AlphaSettings { HorizonUrl = "https://horizon-testnet.stellar.org", NetworkPassphrase = "Test SDF Network ; September 2015", CWD = "AppData" }; var stellarProvider = new MockStellarDataProvider(settings.NetworkPassphrase, settings.HorizonUrl); context = new AlphaContext(settings, new MockStorage(), stellarProvider, useLegacyOrderbook); context.Init().Wait(); var requestRateLimits = new RequestRateLimits { HourLimit = 1000, MinuteLimit = 100 }; var account1 = new AccountWrapper(new Models.Account { Id = 1, Pubkey = new RawPubKey() { Data = KeyPair.Random().PublicKey }, Balances = new List <Balance>() }, requestRateLimits); account1.Account.CreateBalance(0); account1.Account.GetBalance(0).UpdateBalance(10000000000); account1.Account.CreateBalance(1); account1.Account.GetBalance(1).UpdateBalance(10000000000); var account2 = new AccountWrapper(new Models.Account { Id = 2, Pubkey = new RawPubKey() { Data = KeyPair.Random().PublicKey }, Balances = new List <Balance>() }, requestRateLimits); account2.Account.CreateBalance(0); account2.Account.GetBalance(0).UpdateBalance(10000000000); account2.Account.CreateBalance(1); account2.Account.GetBalance(1).UpdateBalance(10000000000); context.Setup(new Snapshot { Accounts = new List <AccountWrapper> { account1, account2 }, Apex = 0, TxCursor = 1, Orders = new List <Order>(), Settings = new ConstellationSettings { Vault = KeyPair.Random().PublicKey, Assets = new List <AssetSettings> { new AssetSettings { Id = 1, Code = "X", Issuer = new RawPubKey() } }, RequestRateLimits = requestRateLimits }, }).Wait(); this.account1 = context.AccountStorage.GetAccount(account1.Id); this.account2 = context.AccountStorage.GetAccount(account2.Id); }
public ProcessHelper(Tracer tracer, EnvironmentHelper environment) { _environment = environment; _tracer = tracer; TraceProcesses = true; }
public override TestResult[] Execute(ITestMethod testMethod) { var platform = EnvironmentHelper.GetEnvironmentVariable(ENVIRONMENT_TEST_VARIABLE.YUNIQL_TEST_TARGET_PLATFORM); var testDataServiceFactory = new TestDataServiceFactory(); var testDataService = testDataServiceFactory.Create(platform); //Ignores test methods with [TestMethodExAttribute (Requires = "IsAtomicDDLSupported")] attribute if (this.Requires.Contains(nameof(testDataService.IsAtomicDDLSupported)) && !testDataService.IsAtomicDDLSupported) { var message = $"Target database platform or version does not support atomic DDL operations. " + $"DDL operations like CREATE TABLE, CREATE VIEW are not gauranteed to be executed transactional."; return(new[] { new TestResult { Outcome = UnitTestOutcome.NotRunnable, LogOutput = message } }); } //Ignores test methods with [TestMethodExAttribute (Requires = "IsAtomicDDLSupported")] attribute if (this.Requires.Contains("IsAtomicDDLNotSupported") && testDataService.IsAtomicDDLSupported) { var message = $"Target database platform or version supports atomic DDL operations. " + $"This test is exclusive for platforms not supporting transaction DDL operations."; return(new[] { new TestResult { Outcome = UnitTestOutcome.NotRunnable, LogOutput = message } }); } //Ignores test methods with [TestMethodExAttribute (Requires = "IsSchemaSupported")] attribute if (this.Requires.Contains(nameof(testDataService.IsSchemaSupported)) && !testDataService.IsSchemaSupported) { var message = $"Target database platform or version does not support schema within the same database."; return(new[] { new TestResult { Outcome = UnitTestOutcome.NotRunnable, LogOutput = message } }); } //Ignores test methods with [TestMethodExAttribute (Requires = "IsBatchSqlSupported")] attribute if (this.Requires.Contains(nameof(testDataService.IsBatchSqlSupported)) && !testDataService.IsBatchSqlSupported) { var message = $"Target database platform or version does not support schema within the same database."; return(new[] { new TestResult { Outcome = UnitTestOutcome.NotRunnable, LogOutput = message } }); } return(base.Execute(testMethod)); }
public ICommunicationRequest BuildUrl(CheckoutBillingRequest request) { try { if (request.CheckoutResponse != null) { _checkout = request.CheckoutResponse; var billingInfo = _checkout.BillingInfo; var cardInfo = _checkout.PaymentInfo.CardInfo; var isPrepopulatedCard = !string.IsNullOrEmpty(cardInfo.Id); var selectedSavedAddress = _checkout.SavedAddresses.Where(x => x.IsSelected).FirstOrDefault() ?? new SavedAddressOption(); var selectedSavedCard = _checkout.SavedCards.Where(x => x.IsSelected).FirstOrDefault() ?? new Option(); var url = string.Format("{0}{1}{2}&csrf_token={3}", Config.Urls.SecureBaseUrl, Config.Urls.CheckoutBillingPost, _checkout.Cart.DWQuery, _checkout.CsrfToken); //cpere: rollback due to gift-card issues. //var url = string.Format("{0}{1}/{2}", Config.Urls.SecureBaseUrl, Config.Urls.CheckoutBillingPost, _checkout.Cart.DWQuery.Replace("?dwcont=", "")); var postSb = new StringBuilder(); postSb.AppendFormat("dwfrm_billing_save={0}", "true"); if (_checkout.IsLoggedIn) { postSb.AppendFormat("&dwfrm_billing_addressList={0}", HttpUtility.UrlEncode(selectedSavedAddress.Value)); } postSb.AppendFormat("&dwfrm_billing_billingAddress_addressFields_firstName={0}", HttpUtility.UrlEncode(billingInfo.FirstName)); postSb.AppendFormat("&dwfrm_billing_billingAddress_addressFields_lastName={0}", HttpUtility.UrlEncode(billingInfo.LastName)); postSb.AppendFormat("&dwfrm_billing_billingAddress_addressFields_address1={0}", HttpUtility.UrlEncode(billingInfo.Address1)); postSb.AppendFormat("&dwfrm_billing_billingAddress_addressFields_address2={0}", HttpUtility.UrlEncode(billingInfo.Address2)); postSb.AppendFormat("&dwfrm_billing_billingAddress_addressFields_country={0}", "US"); postSb.AppendFormat("&dwfrm_billing_billingAddress_addressFields_city={0}", HttpUtility.UrlEncode(billingInfo.City)); postSb.AppendFormat("&dwfrm_billing_billingAddress_addressFields_states_state={0}", HttpUtility.UrlEncode(billingInfo.State)); postSb.AppendFormat("&dwfrm_billing_billingAddress_addressFields_zip={0}", HttpUtility.UrlEncode(billingInfo.Zip)); postSb.AppendFormat("&dwfrm_billing_billingAddress_addressFields_phone={0}", HttpUtility.UrlEncode(billingInfo.Phone)); postSb.AppendFormat("&dwfrm_billing_billingAddress_email_emailAddress={0}", HttpUtility.UrlEncode(_checkout.Email)); if (_checkout.IsAddToAddressBook) { postSb.Append("&dwfrm_billing_billingAddress_addToAddressBook=true"); } if (_checkout.IsAddToEmailList) { postSb.Append("&dwfrm_billing_billingAddress_addToEmailList=true"); } if (_checkout.IsNoPaymentNeeded) { postSb.AppendFormat("&dwfrm_billing_paymentMethods_selectedPaymentMethodID={0}", "GIFT_CERTIFICATE"); postSb.Append("&noPaymentNeeded=true"); } else { var selectedPaymentMethod = _checkout.PaymentMethods.Find(x => x.IsSelected) ?? new Option(); _isPayPal = selectedPaymentMethod.Value == "PayPal"; if (_isPayPal) { postSb.AppendFormat("&EnvironmentID={0}", EnvironmentHelper.GetEnvironmentId(_core.Context.Request)); } postSb.AppendFormat("&dwfrm_billing_paymentMethods_selectedPaymentMethodID={0}", selectedPaymentMethod.Value); if (_checkout.IsLoggedIn) { postSb.AppendFormat("&dwfrm_billing_paymentMethods_creditCardList={0}", HttpUtility.UrlEncode(selectedSavedCard.Value)); } postSb.AppendFormat("&dwfrm_billing_paymentMethods_creditCard_owner={0}", HttpUtility.UrlEncode(cardInfo.NameOnCard)); postSb.AppendFormat("&dwfrm_billing_paymentMethods_creditCard_type={0}", !string.IsNullOrEmpty(cardInfo.Type) ? cardInfo.Type : _checkout.PaymentInfo.AvailableCardTypes.FirstOrDefault().Value); postSb.AppendFormat("&dwfrm_billing_paymentMethods_creditCard_maskedFourDigit={0}", isPrepopulatedCard ? cardInfo.Number : string.Empty); postSb.AppendFormat("&dwfrm_billing_paymentMethods_creditCard_number={0}", isPrepopulatedCard ? cardInfo.Id : cardInfo.Number); postSb.AppendFormat("&dwfrm_billing_paymentMethods_creditCard_month={0}", cardInfo.ExpirationMonth); postSb.AppendFormat("&dwfrm_billing_paymentMethods_creditCard_year={0}", cardInfo.ExpirationYear); postSb.AppendFormat("&dwfrm_billing_paymentMethods_creditCard_isSubscription={0}", isPrepopulatedCard.ToString()); postSb.AppendFormat("&dwfrm_billing_paymentMethods_creditCard_cvn={0}", cardInfo.Cvv); } if (_checkout.IsLoggedIn && _checkout.IsSaveThisCard) { postSb.Append("&dwfrm_billing_paymentMethods_creditCard_saveCard=true"); } postSb.Append("&dwfrm_billing_paymentMethods_selectedPaymentMethodID="); postSb.AppendFormat("&dwfrm_billing_securekey={0}", _checkout.DWSecureKey); postSb.Append("&dwfrm_billing_couponCode="); postSb.AppendFormat("&dwfrm_billing_giftCardNum={0}", _checkout.GiftCard.GiftCardNumber); postSb.AppendFormat("&recaptcha_challenge_field={0}", _checkout.CaptchaChalange); postSb.AppendFormat("&recaptcha_response_field={0}", _checkout.CaptchaResponse); postSb.AppendFormat("&dwfrm_ReCaptchaTest_securekey={0}", _checkout.DWCaptchaSecureKey); if (request.IsApplyGiftCard) { postSb.AppendFormat("&dwfrm_billing_redeemGiftCert={0}", "Apply"); } else { postSb.AppendFormat("&dwfrm_billing_save={0}", "Next%3A+Review+Your+Order"); } postSb.AppendFormat("&dwfrm_billing_giftCardPin={0}", _checkout.GiftCard.GiftCardPinNumber); _core.CommunicationRequest = new ExtendedComRequest(HttpRequestMethod.POST, url, _core, _errors) { OverridePostData = postSb.ToString(), OverrideStopAutoRedirects = _isPayPal, OptionalReturnResponseHeaders = _isPayPal, OverrideBlockXDocumentConversion = _isPayPal, }; } else { var url = string.Format("{0}{1}?EnvironmentID={2}", Config.Urls.SecureBaseUrl, Config.Urls.CheckoutBillingGet, EnvironmentHelper.GetEnvironmentId(_core.Context.Request)); _core.CommunicationRequest = new ExtendedComRequest(HttpRequestMethod.GET, url, _core, _errors); } } catch (Exception ex) { _errors.Add(ex.Handle("CheckoutBilling.BuildUrl", ErrorSeverity.FollowUp, ErrorType.BuildUrl)); } return(_core.CommunicationRequest); }
protected override void Arrange() { EnvironmentHelper.AssertOracleClientIsInstalled(); database = new OracleDatabase("server=entlib;user id=testuser;password=testuser"); }
public void Initialize() { var tracer = _tracerFactory.GetTracer(); using (tracer.Step("GitExeRepository.Initialize")) { Execute(tracer, "init"); Execute(tracer, "config core.autocrlf {0}", OSDetector.IsOnWindows() ? "true" : "false"); // This speeds up git operations like 'git checkout', especially on slow drives like in Azure Execute(tracer, "config core.preloadindex true"); Execute(tracer, @"config user.name ""{0}""", _settings.GetGitUsername()); Execute(tracer, @"config user.email ""{0}""", _settings.GetGitEmail()); // This is needed to make lfs work Execute(tracer, @"config filter.lfs.clean ""git-lfs clean %f"""); Execute(tracer, @"config filter.lfs.smudge ""git-lfs smudge %f"""); Execute(tracer, @"config filter.lfs.required true"); using (tracer.Step("Configure git server")) { // Allow getting pushes even though we're not bare Execute(tracer, "config receive.denyCurrentBranch ignore"); } // to disallow browsing to this folder in case of in-place repo using (tracer.Step("Create deny users for .git folder")) { string content = "<?xml version=\"1.0\"" + @"?> <configuration> <system.web> <authorization> <deny users=" + "\"*\"" + @"/> </authorization> </system.web> <configuration>"; File.WriteAllText(Path.Combine(_gitExe.WorkingDirectory, ".git", "web.config"), content); } // Server env does not support interactive cred prompt; hence, we intercept any credential provision // for git fetch/clone with http/https scheme and return random invalid u/p forcing 'fatal: Authentication failed.' using (tracer.Step("Configure git-credential")) { FileSystemHelpers.EnsureDirectory(Path.GetDirectoryName(GitCredentialHookPath)); string content = @"#!/bin/sh if [ " + "\"$1\" = \"get\"" + @" ]; then echo username=dummyUser echo password=dummyPassword fi" + "\n"; File.WriteAllText(GitCredentialHookPath, content); Execute(tracer, "config credential.helper \"!'{0}'\"", GitCredentialHookPath); } using (tracer.Step("Setup post receive hook")) { FileSystemHelpers.EnsureDirectory(Path.GetDirectoryName(PostReceiveHookPath)); //#!/bin/sh //read i //echo $i > pushinfo //KnownEnvironment.KUDUCOMMAND StringBuilder sb = new StringBuilder(); sb.AppendLine("#!/bin/sh"); sb.AppendLine("read i"); sb.AppendLine("echo $i > pushinfo"); if (EnvironmentHelper.IsDynamicInstallEnvironment()) { sb.AppendLine(KnownEnvironment.KUDUCOMMAND_DYNAMICINSTALL); } else { sb.AppendLine(KnownEnvironment.KUDUCOMMAND); } if (OSDetector.IsOnWindows()) { FileSystemHelpers.WriteAllText(PostReceiveHookPath, sb.ToString()); } else { FileSystemHelpers.WriteAllText(PostReceiveHookPath, sb.ToString().Replace("\r\n", "\n")); using (tracer.Step("Non-Windows enviroment, granting 755 permission to post-receive hook file")) { PermissionHelper.Chmod("755", PostReceiveHookPath, _environment, _settings, NullLogger.Instance); } } } // NOTE: don't add any new init steps after creating the post receive hook, // as it's also used to mark that Init was fully executed } }
/// <summary> /// Method to execute a smoke test. /// </summary> /// <param name="shouldDeserializeTraces">Optimization parameter, pass false when the resulting traces aren't being verified</param> protected void CheckForSmoke(bool shouldDeserializeTraces = true) { var applicationPath = EnvironmentHelper.GetSampleApplicationPath().Replace(@"\\", @"\"); Output.WriteLine($"Application path: {applicationPath}"); var executable = EnvironmentHelper.GetSampleExecutionSource(); Output.WriteLine($"Executable path: {executable}"); if (!System.IO.File.Exists(applicationPath)) { throw new Exception($"Smoke test file does not exist: {applicationPath}"); } // clear all relevant environment variables to start with a clean slate EnvironmentHelper.ClearProfilerEnvironmentVariables(); ProcessStartInfo startInfo; int agentPort = TcpPortProvider.GetOpenPort(); int aspNetCorePort = TcpPortProvider.GetOpenPort(); // unused for now Output.WriteLine($"Assigning port {agentPort} for the agentPort."); Output.WriteLine($"Assigning port {aspNetCorePort} for the aspNetCorePort."); if (EnvironmentHelper.IsCoreClr()) { // .NET Core startInfo = new ProcessStartInfo(executable, $"{applicationPath}"); EnvironmentHelper.SetEnvironmentVariableDefaults(agentPort, aspNetCorePort, executable, startInfo.EnvironmentVariables); } else { // .NET Framework startInfo = new ProcessStartInfo(executable); EnvironmentHelper.SetEnvironmentVariableDefaults(agentPort, aspNetCorePort, executable, startInfo.EnvironmentVariables); } startInfo.UseShellExecute = false; startInfo.CreateNoWindow = true; startInfo.RedirectStandardOutput = true; startInfo.RedirectStandardError = true; startInfo.RedirectStandardInput = false; ProcessResult result; using (var agent = new MockTracerAgent(agentPort)) { agent.ShouldDeserializeTraces = shouldDeserializeTraces; using (var process = Process.Start(startInfo)) { if (process == null) { throw new NullException("We need a reference to the process for this test."); } var ranToCompletion = process.WaitForExit(MaxTestRunMilliseconds); if (AssumeSuccessOnTimeout && !ranToCompletion) { process.Kill(); Assert.True(true, "No smoke is a good sign for this case, even on timeout."); return; } if (!ranToCompletion) { throw new TimeoutException("The smoke test is running for too long or was lost."); } string standardOutput = process.StandardOutput.ReadToEnd(); string standardError = process.StandardError.ReadToEnd(); int exitCode = process.ExitCode; if (!string.IsNullOrWhiteSpace(standardOutput)) { Output.WriteLine($"StandardOutput:{Environment.NewLine}{standardOutput}"); } if (!string.IsNullOrWhiteSpace(standardError)) { Output.WriteLine($"StandardError:{Environment.NewLine}{standardError}"); } result = new ProcessResult(process, standardOutput, standardError, exitCode); } } var successCode = 0; Assert.True(successCode == result.ExitCode, $"Non-success exit code {result.ExitCode}"); Assert.True(string.IsNullOrEmpty(result.StandardError), $"Expected no errors in smoke test: {result.StandardError}"); }
public void InitPlugin( IActPluginV1 plugin, TabPage pluginScreenSpace, Label pluginStatusText) { // タイトルをセットする pluginScreenSpace.Text = "YUKKURI"; EnvironmentMigrater.Migrate(); MasterFilePublisher.Publish(); WPFHelper.Start(); WPFHelper.BeginInvoke(async() => { AppLog.LoadConfiguration(AppLog.HojoringConfig); this.Logger?.Trace(Assembly.GetExecutingAssembly().GetName().ToString() + " start."); try { this.PluginStatusLabel = pluginStatusText; if (!EnvironmentHelper.IsValidPluginLoadOrder()) { if (pluginStatusText != null) { pluginStatusText.Text = "Plugin Initialize Error"; } return; } EnvironmentHelper.GarbageLogs(); EnvironmentHelper.StartActivator(() => { ConfigBaseView.Instance.SetActivationStatus(false); this.DeInitPlugin(); }); this.Logger.Trace("[YUKKURI] Start InitPlugin"); var pluginInfo = ActGlobals.oFormActMain.PluginGetSelfData(plugin); if (pluginInfo != null) { this.PluginDirectory = pluginInfo.pluginFile.DirectoryName; } // .NET FrameworkとOSのバージョンを確認する if (!UpdateChecker.IsAvailableDotNet() || !UpdateChecker.IsAvailableWindows()) { NotSupportedView.AddAndShow(pluginScreenSpace); return; } // FFXIV.Framework.config を読み込ませる lock (FFXIV.Framework.Config.ConfigBlocker) { _ = FFXIV.Framework.Config.Instance; } // HojoringのSplashを表示する UpdateChecker.ShowSplash(); // 外部リソースをダウンロードする await ResourcesDownloader.Instance.DownloadAsync(); // 設定ファイルを読み込む Settings.Default.Load(); Settings.Default.StatusAlertSettings.EnabledTPAlert = false; // 設定ファイルをバックアップする await EnvironmentHelper.BackupFilesAsync( Settings.FilePath); // 漢字変換を初期化する KanjiTranslator.Default.Initialize(); // TTSキャッシュの移行とGarbageを行う await Task.Run(() => { this.MigrateTTSCache(); this.GarbageTTSCache(); }); EnvironmentHelper.WaitInitActDone(); await Task.Run(() => { // TTSを初期化する SpeechController.Default.Initialize(); // FF14監視スレッドを初期化する FFXIVWatcher.Initialize(); }); // 設定Panelを追加する pluginScreenSpace.Controls.Add(new ElementHost() { Child = new ConfigBaseView(), Dock = DockStyle.Fill, }); // TTSメソッドを置き換える this.StartReplaceTTSMethodTimer(); await Task.Run(() => { // DISCORD BOT クライアントを初期化する DiscordClientModel.Model.Initialize(); // AutoJoinがONならば接続する if (Settings.Default.DiscordSettings.AutoJoin) { DiscordClientModel.Model.Connect(true); } }); await Task.Run(() => { // VOICEROIDを起動する if (SpeechController.Default is VoiceroidSpeechController ctrl) { ctrl.Start(); } }); // Bridgeにメソッドを登録する PlayBridge.Instance.SetBothDelegate((message, voicePalette, isSync, volume) => this.Speak(message, PlayDevices.Both, voicePalette, isSync, volume)); PlayBridge.Instance.SetMainDeviceDelegate((message, voicePalette, isSync, volume) => this.Speak(message, PlayDevices.Main, voicePalette, isSync, volume)); PlayBridge.Instance.SetSubDeviceDelegate((message, voicePalette, isSync, volume) => this.Speak(message, PlayDevices.Sub, voicePalette, isSync, volume)); PlayBridge.Instance.SetSyncStatusDelegate(() => Settings.Default.Player == WavePlayerTypes.WASAPIBuffered); // テキストコマンドの購読を登録する this.SubscribeTextCommands(); // サウンドデバイスを初期化する SoundPlayerWrapper.Init(); SoundPlayerWrapper.LoadTTSCache(); // CeVIOをアイコン化する if (Settings.Default.TTS == TTSType.Sasara) { CevioTrayManager.Start(); CevioTrayManager.ToIcon(); } if (this.PluginStatusLabel != null) { this.PluginStatusLabel.Text = "Plugin Started"; } this.Logger.Trace("[YUKKURI] End InitPlugin"); // 共通ビューを追加する CommonViewHelper.Instance.AddCommonView( pluginScreenSpace.Parent as TabControl); this.isLoaded = true; // アップデートを確認する await Task.Run(() => this.Update()); } catch (Exception ex) { this.Logger.Error(ex, "InitPlugin error."); ModernMessageBox.ShowDialog( "Plugin init error !", "ACT.TTSYukkuri", System.Windows.MessageBoxButton.OK, ex); // TTSをゆっくりに戻す Settings.Default.TTS = TTSType.Yukkuri; Settings.Default.Save(); } }); }
public void SubmitsTraces(string packageVersion) { using var telemetry = this.ConfigureTelemetry(); using (var agent = EnvironmentHelper.GetMockAgent()) using (RunSampleAndWaitForExit(agent, arguments: $"{TestPrefix}", packageVersion: packageVersion)) { var expected = new TupleList <string, string> { { "SET", $"SET {TestPrefix}StackExchange.Redis.INCR" }, { "PING", "PING" }, { "INCR", $"INCR {TestPrefix}StackExchange.Redis.INCR" }, { "INCRBYFLOAT", $"INCRBYFLOAT {TestPrefix}StackExchange.Redis.INCR" }, { "GET", $"GET {TestPrefix}StackExchange.Redis.INCR" }, { "DDCUSTOM", "DDCUSTOM" }, { "ECHO", "ECHO" }, { "SLOWLOG", "SLOWLOG" }, { "TIME", "TIME" }, }; if (string.IsNullOrEmpty(packageVersion) || packageVersion.CompareTo("1.2.2") < 0) { expected.Remove(new Tuple <string, string>("DDCUSTOM", "DDCUSTOM")); expected.Remove(new Tuple <string, string>("ECHO", "ECHO")); expected.Remove(new Tuple <string, string>("SLOWLOG", "SLOWLOG")); expected.Remove(new Tuple <string, string>("TIME", "TIME")); } var batchPrefix = $"{TestPrefix}StackExchange.Redis.Batch."; expected.AddRange(new TupleList <string, string> { { "DEBUG", $"DEBUG {batchPrefix}DebugObjectAsync" }, { "DDCUSTOM", $"DDCUSTOM" }, // Only present on 1.2.2+ { "GEOADD", $"GEOADD {batchPrefix}GeoAddAsync" }, // Only present on 1.2.0+ { "GEODIST", $"GEODIST {batchPrefix}GeoDistanceAsync" }, // Only present on 1.2.0+ { "GEOHASH", $"GEOHASH {batchPrefix}GeoHashAsync" }, // Only present on 1.2.0+ { "GEOPOS", $"GEOPOS {batchPrefix}GeoPositionAsync" }, // Only present on 1.2.0+ { "GEORADIUSBYMEMBER", $"GEORADIUSBYMEMBER {batchPrefix}GeoRadiusAsync" }, // Only present on 1.2.0+ { "ZREM", $"ZREM {batchPrefix}GeoRemoveAsync" }, // Only present on 1.2.0+ { "HINCRBYFLOAT", $"HINCRBYFLOAT {batchPrefix}HashDecrementAsync" }, { "HDEL", $"HDEL {batchPrefix}HashDeleteAsync" }, { "HEXISTS", $"HEXISTS {batchPrefix}HashExistsAsync" }, { "HGETALL", $"HGETALL {batchPrefix}HashGetAllAsync" }, { "HINCRBYFLOAT", $"HINCRBYFLOAT {batchPrefix}HashIncrementAsync" }, { "HKEYS", $"HKEYS {batchPrefix}HashKeysAsync" }, { "HLEN", $"HLEN {batchPrefix}HashLengthAsync" }, { "HMSET", $"HMSET {batchPrefix}HashSetAsync" }, { "HVALS", $"HVALS {batchPrefix}HashValuesAsync" }, { "PFADD", $"PFADD {batchPrefix}HyperLogLogAddAsync" }, // Only present on 1.0.242+ { "PFCOUNT", $"PFCOUNT {batchPrefix}HyperLogLogLengthAsync" }, // Only present on 1.0.242+ { "PFMERGE", $"PFMERGE {batchPrefix}HyperLogLogMergeAsync" }, // Only present on 1.0.242+ { "PING", $"PING" }, // { "DEL", $"DEL key" }, { "DUMP", $"DUMP key" }, { "EXISTS", $"EXISTS key" }, { "PEXPIRE", $"PEXPIRE key" }, { "MOVE", $"MOVE key" }, { "PERSIST", $"PERSIST key" }, { "RANDOMKEY", $"RANDOMKEY" }, { "RENAME", "RENAME key1" }, { "RESTORE", "RESTORE key" }, { "TYPE", "TYPE key" }, { "LINDEX", "LINDEX listkey" }, { "LINSERT", "LINSERT listkey" }, { "LINSERT", "LINSERT listkey" }, { "LPOP", "LPOP listkey" }, { "LPUSH", "LPUSH listkey" }, { "LLEN", "LLEN listkey" }, { "LRANGE", "LRANGE listkey" }, { "LREM", "LREM listkey" }, { "RPOP", "RPOP listkey" }, { "RPOPLPUSH", "RPOPLPUSH listkey" }, { "RPUSH", "RPUSH listkey" }, { "LSET", "LSET listkey" }, { "LTRIM", "LTRIM listkey" }, { "GET", "GET listkey" }, { "SET", "SET listkey" }, { "PUBLISH", "PUBLISH channel" }, { "SADD", "SADD setkey" }, { "SUNIONSTORE", "SUNIONSTORE setkey" }, { "SUNION", "SUNION setkey1" }, { "SISMEMBER", "SISMEMBER setkey" }, { "SCARD", "SCARD setkey" }, { "SMEMBERS", "SMEMBERS setkey" }, { "SMOVE", "SMOVE setkey1" }, { "SPOP", "SPOP setkey1" }, { "SRANDMEMBER", "SRANDMEMBER setkey" }, { "SRANDMEMBER", "SRANDMEMBER setkey" }, { "SREM", "SREM setkey" }, { "SORT", "SORT setkey" }, // Only present on 1.0.206+ { "SORT", "SORT setkey" }, // Only present on 1.0.206+ { "ZUNIONSTORE", "ZUNIONSTORE ssetkey1" }, // Only present on 1.0.206+ { "ZADD", "ZADD ssetkey" }, { "ZINCRBY", "ZINCRBY ssetkey" }, { "ZINCRBY", "ZINCRBY ssetkey" }, { "ZCARD", "ZCARD ssetkey" }, { "ZRANGE", "ZRANGE ssetkey" }, { "ZRANGE", "ZRANGE ssetkey" }, { "ZRANGEBYSCORE", "ZRANGEBYSCORE ssetkey" }, { "ZRANGEBYSCORE", "ZRANGEBYSCORE ssetkey" }, { "ZRANK", "ZRANK ssetkey" }, { "ZREM", "ZREM ssetkey" }, { "ZREMRANGEBYRANK", "ZREMRANGEBYRANK ssetkey" }, { "ZREMRANGEBYSCORE", "ZREMRANGEBYSCORE ssetkey" }, { "ZSCORE", "ZSCORE ssestkey" }, { "ZLEXCOUNT", "ZLEXCOUNT ssetkey" }, // Only present on 1.0.273+ { "ZRANGEBYLEX", "ZRANGEBYLEX ssetkey" }, // Only present on 1.0.273+ { "ZREMRANGEBYLEX", "ZREMRANGEBYLEX ssetkey" }, // Only present on 1.0.273+ { "APPEND", "APPEND ssetkey" }, { "BITCOUNT", "BITCOUNT ssetkey" }, { "BITOP", "BITOP" }, { "BITPOS", "BITPOS ssetkey1" }, { "INCRBYFLOAT", "INCRBYFLOAT key" }, { "GET", "GET key" }, { "GETBIT", "GETBIT key" }, { "GETRANGE", "GETRANGE key" }, { "GETSET", "GETSET key" }, { "INCR", "INCR key" }, { "STRLEN", "STRLEN key" }, { "SET", "SET key" }, { "SETBIT", "SETBIT key" }, { "SETRANGE", "SETRANGE key" }, }); FilterExpectedResultsByApiVersion(expected, packageVersion); var dbPrefix = $"{TestPrefix}StackExchange.Redis.Database."; expected.AddRange(new TupleList <string, string> { { "DEBUG", $"DEBUG {dbPrefix}DebugObject" }, { "DDCUSTOM", $"DDCUSTOM" }, // Only present on 1.2.2+ { "GEOADD", $"GEOADD {dbPrefix}Geo" }, // Only present on 1.2.0+ { "GEODIST", $"GEODIST {dbPrefix}Geo" }, // Only present on 1.2.0+ { "GEOHASH", $"GEOHASH {dbPrefix}Geo" }, // Only present on 1.2.0+ { "GEOPOS", $"GEOPOS {dbPrefix}Geo" }, // Only present on 1.2.0+ { "GEORADIUSBYMEMBER", $"GEORADIUSBYMEMBER {dbPrefix}Geo" }, // Only present on 1.2.0+ { "ZREM", $"ZREM {dbPrefix}Geo" }, // Only present on 1.2.0+ { "HINCRBYFLOAT", $"HINCRBYFLOAT {dbPrefix}Hash" }, { "HDEL", $"HDEL {dbPrefix}Hash" }, { "HEXISTS", $"HEXISTS {dbPrefix}Hash" }, { "HGET", $"HGET {dbPrefix}Hash" }, { "HGETALL", $"HGETALL {dbPrefix}Hash" }, { "HINCRBY", $"HINCRBY {dbPrefix}Hash" }, { "HKEYS", $"HKEYS {dbPrefix}Hash" }, { "HLEN", $"HLEN {dbPrefix}Hash" }, // { "HSCAN", $"HSCAN {dbPrefix}Hash" }, { "HMSET", $"HMSET {dbPrefix}Hash" }, { "HVALS", $"HVALS {dbPrefix}Hash" }, { "PFADD", $"PFADD {dbPrefix}HyperLogLog" }, // Only present on 1.0.242+ { "PFCOUNT", $"PFCOUNT {dbPrefix}HyperLogLog" }, // Only present on 1.0.242+ { "PFMERGE", $"PFMERGE {dbPrefix}HyperLogLog2" }, // Only present on 1.0.242+ // { "DEL", $"DEL {dbPrefix}Key" }, { "DUMP", $"DUMP {dbPrefix}Key" }, { "EXISTS", $"EXISTS {dbPrefix}Key" }, { "PEXPIRE", $"PEXPIRE {dbPrefix}Key" }, { "MIGRATE", $"MIGRATE {dbPrefix}Key" }, // Only present on 1.0.297+ { "MOVE", $"MOVE {dbPrefix}Key" }, { "PERSIST", $"PERSIST {dbPrefix}Key" }, { "RANDOMKEY", $"RANDOMKEY" }, { "RENAME", $"RENAME {dbPrefix}Key" }, { "RESTORE", $"RESTORE {dbPrefix}Key" }, { "PTTL", $"PTTL {dbPrefix}Key" }, { "TYPE", $"TYPE {dbPrefix}Key" }, { "LINDEX", $"LINDEX {dbPrefix}List" }, { "LINSERT", $"LINSERT {dbPrefix}List" }, { "LINSERT", $"LINSERT {dbPrefix}List" }, { "LPOP", $"LPOP {dbPrefix}List" }, { "LPUSH", $"LPUSH {dbPrefix}List" }, { "LLEN", $"LLEN {dbPrefix}List" }, { "LRANGE", $"LRANGE {dbPrefix}List" }, { "LREM", $"LREM {dbPrefix}List" }, { "RPOP", $"RPOP {dbPrefix}List" }, { "RPOPLPUSH", $"RPOPLPUSH {dbPrefix}List" }, { "RPUSH", $"RPUSH {dbPrefix}List" }, { "LSET", $"LSET {dbPrefix}List" }, { "LTRIM", $"LTRIM {dbPrefix}List" }, { "GET", $"GET {dbPrefix}Lock" }, { "SET", $"SET {dbPrefix}Lock" }, { "PING", $"PING" }, { "PUBLISH", $"PUBLISH value" }, { "SADD", $"SADD {dbPrefix}Set" }, { "SUNION", $"SUNION {dbPrefix}Set" }, { "SUNIONSTORE", $"SUNIONSTORE {dbPrefix}Set" }, { "SISMEMBER", $"SISMEMBER {dbPrefix}Set" }, { "SCARD", $"SCARD {dbPrefix}Set" }, { "SMEMBERS", $"SMEMBERS {dbPrefix}Set" }, { "SMOVE", $"SMOVE {dbPrefix}Set" }, { "SPOP", $"SPOP {dbPrefix}Set" }, { "SRANDMEMBER", $"SRANDMEMBER {dbPrefix}Set" }, { "SRANDMEMBER", $"SRANDMEMBER {dbPrefix}Set" }, { "SREM", $"SREM {dbPrefix}Set" }, { "EXEC", $"EXEC" }, { "SORT", $"SORT {dbPrefix}Key" }, // Only present on 1.0.206+ { "SORT", $"SORT {dbPrefix}Key" }, // Only present on 1.0.206+ { "ZUNIONSTORE", $"ZUNIONSTORE {dbPrefix}SortedSet2" }, // Only present on 1.0.206+ { "ZADD", $"ZADD {dbPrefix}SortedSet" }, { "ZINCRBY", $"ZINCRBY {dbPrefix}SortedSet" }, { "ZINCRBY", $"ZINCRBY {dbPrefix}SortedSet" }, { "ZCARD", $"ZCARD {dbPrefix}SortedSet" }, { "ZRANGE", $"ZRANGE {dbPrefix}SortedSet" }, { "ZRANGE", $"ZRANGE {dbPrefix}SortedSet" }, { "ZRANGEBYSCORE", $"ZRANGEBYSCORE {dbPrefix}SortedSet" }, { "ZRANGEBYSCORE", $"ZRANGEBYSCORE {dbPrefix}SortedSet" }, { "ZRANK", $"ZRANK {dbPrefix}SortedSet" }, { "ZREM", $"ZREM {dbPrefix}SortedSet" }, { "ZREMRANGEBYRANK", $"ZREMRANGEBYRANK {dbPrefix}SortedSet" }, { "ZREMRANGEBYSCORE", $"ZREMRANGEBYSCORE {dbPrefix}SortedSet" }, { "ZSCORE", $"ZSCORE {dbPrefix}SortedSet" }, { "ZLEXCOUNT", $"ZLEXCOUNT {dbPrefix}SortedSet" }, // Only present on 1.0.273+ { "ZRANGEBYLEX", $"ZRANGEBYLEX {dbPrefix}SortedSet" }, // Only present on 1.0.273+ { "ZREMRANGEBYLEX", $"ZREMRANGEBYLEX {dbPrefix}SortedSet" }, // Only present on 1.0.273+ { "APPEND", $"APPEND {dbPrefix}Key" }, { "BITCOUNT", $"BITCOUNT {dbPrefix}Key" }, { "BITOP", $"BITOP" }, { "BITPOS", $"BITPOS {dbPrefix}Key" }, { "INCRBYFLOAT", $"INCRBYFLOAT {dbPrefix}Key" }, { "GET", $"GET {dbPrefix}Key" }, { "GETBIT", $"GETBIT {dbPrefix}Key" }, { "GETRANGE", $"GETRANGE {dbPrefix}Key" }, { "GETSET", $"GETSET {dbPrefix}Key" }, { "PTTL+GET", $"PTTL+GET {dbPrefix}Key" }, { "STRLEN", $"STRLEN {dbPrefix}Key" }, { "SET", $"SET {dbPrefix}Key" }, { "SETBIT", $"SETBIT {dbPrefix}Key" }, { "SETRANGE", $"SETRANGE {dbPrefix}Key" }, }); FilterExpectedResultsByApiVersion(expected, packageVersion); var spans = agent.WaitForSpans(expected.Count).Where(s => s.Type == "redis").OrderBy(s => s.Start).ToList(); var host = Environment.GetEnvironmentVariable("STACKEXCHANGE_REDIS_HOST") ?? "localhost:6389"; var port = host.Substring(host.IndexOf(':') + 1); host = host.Substring(0, host.IndexOf(':')); foreach (var span in spans) { Assert.Equal("redis.command", span.Name); Assert.Equal("Samples.StackExchange.Redis-redis", span.Service); Assert.Equal(SpanTypes.Redis, span.Type); Assert.Equal(host, DictionaryExtensions.GetValueOrDefault(span.Tags, "out.host")); Assert.Equal(port, DictionaryExtensions.GetValueOrDefault(span.Tags, "out.port")); Assert.False(span.Tags?.ContainsKey(Tags.Version), "External service span should not have service version tag."); } var spanLookup = new Dictionary <Tuple <string, string>, int>(); foreach (var span in spans) { var key = new Tuple <string, string>(span.Resource, DictionaryExtensions.GetValueOrDefault(span.Tags, "redis.raw_command")); if (spanLookup.ContainsKey(key)) { spanLookup[key]++; } else { spanLookup[key] = 1; } } var missing = new List <Tuple <string, string> >(); foreach (var e in expected) { var found = spanLookup.ContainsKey(e); if (found) { if (--spanLookup[e] <= 0) { spanLookup.Remove(e); } } else { missing.Add(e); } } foreach (var e in missing) { Assert.True(false, $"no span found for `{e.Item1}`, `{e.Item2}`, remaining spans: `{string.Join(", ", spanLookup.Select(kvp => $"{kvp.Key.Item1}, {kvp.Key.Item2}").ToArray())}`"); } telemetry.AssertIntegrationEnabled(IntegrationId.StackExchangeRedis); } }
private void OnLogin() { EnvironmentHelper.SetWorkingPlace(TabWorkControl, this); }
/// <summary> /// Ensure that the engine is ready for test operations. /// Usually includes starting up the test host process. /// </summary> /// <param name="sources"> /// List of test sources. /// </param> /// <param name="cancellationToken"> /// </param> /// <returns> /// Returns true if Communation is established b/w runner and host /// </returns> public virtual bool SetupChannel(IEnumerable <string> sources) { this.CancellationTokenSource.Token.ThrowTestPlatformExceptionIfCancellationRequested(); var connTimeout = EnvironmentHelper.GetConnectionTimeout(); if (!this.initialized) { this.testHostProcessStdError = string.Empty; TestHostConnectionInfo testHostConnectionInfo = this.testHostManager.GetTestHostConnectionInfo(); var portNumber = 0; if (testHostConnectionInfo.Role == ConnectionRole.Client) { portNumber = this.RequestSender.InitializeCommunication(); testHostConnectionInfo.Endpoint += portNumber; } var processId = this.processHelper.GetCurrentProcessId(); var connectionInfo = new TestRunnerConnectionInfo { Port = portNumber, ConnectionInfo = testHostConnectionInfo, RunnerProcessId = processId, LogFile = this.GetTimestampedLogFile(EqtTrace.LogFile) }; // Subscribe to TestHost Event this.testHostManager.HostLaunched += this.TestHostManagerHostLaunched; this.testHostManager.HostExited += this.TestHostManagerHostExited; // Get the test process start info var testHostStartInfo = this.UpdateTestProcessStartInfo(this.testHostManager.GetTestHostProcessStartInfo(sources, null, connectionInfo)); try { // Launch the test host. var hostLaunchedTask = this.testHostManager.LaunchTestHostAsync(testHostStartInfo, this.CancellationTokenSource.Token); this.testHostLaunched = hostLaunchedTask.Result; if (this.testHostLaunched && testHostConnectionInfo.Role == ConnectionRole.Host) { // If test runtime is service host, try to poll for connection as client this.RequestSender.InitializeCommunication(); } } catch (Exception ex) { EqtTrace.Error("ProxyOperationManager: Failed to launch testhost :{0}", ex); this.CancellationTokenSource.Token.ThrowTestPlatformExceptionIfCancellationRequested(); throw new TestPlatformException(string.Format(CultureInfo.CurrentUICulture, CrossPlatEngineResources.FailedToLaunchTestHost, ex.ToString())); } // Warn the user that execution will wait for debugger attach. var hostDebugEnabled = Environment.GetEnvironmentVariable("VSTEST_HOST_DEBUG"); if (!string.IsNullOrEmpty(hostDebugEnabled) && hostDebugEnabled.Equals("1", StringComparison.Ordinal)) { ConsoleOutput.Instance.WriteLine(CrossPlatEngineResources.HostDebuggerWarning, OutputLevel.Warning); ConsoleOutput.Instance.WriteLine( string.Format("Process Id: {0}, Name: {1}", this.testHostProcessId, this.processHelper.GetProcessName(this.testHostProcessId)), OutputLevel.Information); // Increase connection timeout when debugging is enabled. connTimeout *= 5; } // Wait for a timeout for the client to connect. if (!this.testHostLaunched || !this.RequestSender.WaitForRequestHandlerConnection(connTimeout * 1000, this.CancellationTokenSource.Token)) { this.CancellationTokenSource.Token.ThrowTestPlatformExceptionIfCancellationRequested(); this.ThrowExceptionOnConnectionFailure(connTimeout); } // Handling special case for dotnet core projects with older test hosts // Older test hosts are not aware of protocol version check // Hence we should not be sending VersionCheck message to these test hosts this.CompatIssueWithVersionCheckAndRunsettings(); if (this.versionCheckRequired) { this.RequestSender.CheckVersionWithTestHost(); } this.initialized = true; } return(true); }
private void CreateNew_OnClick_Click(object sender, RoutedEventArgs e) { EnvironmentHelper.CreateNew(); }
private static void RemoveCloseButton() { EnvironmentHelper.GetInstance().RemoveCurrentConsoleWindowMenu(); }
public void GetConnectionTimeoutShouldReturnZeroOnEnvVariableValueZero() { Environment.SetEnvironmentVariable(EnvironmentHelper.VstestConnectionTimeout, "0"); Assert.AreEqual(0, EnvironmentHelper.GetConnectionTimeout()); }
static NativeMethods() { IntPtr chromaSdkPointer; if (EnvironmentHelper.Is64BitProcess() && EnvironmentHelper.Is64BitOperatingSystem()) { // We are running 64-bit! chromaSdkPointer = Native.Kernel32.NativeMethods.LoadLibrary("RzChromaSDK64.dll"); } else { // We are running 32-bit! chromaSdkPointer = Native.Kernel32.NativeMethods.LoadLibrary("RzChromaSDK.dll"); } if (chromaSdkPointer == IntPtr.Zero) { throw new ColoreException( "Failed to dynamically load Chroma SDK library (Error " + Marshal.GetLastWin32Error() + ")."); } Init = GetDelegateFromLibrary <InitDelegate>(chromaSdkPointer, "Init"); UnInit = GetDelegateFromLibrary <UnInitDelegate>(chromaSdkPointer, "UnInit"); CreateEffect = GetDelegateFromLibrary <CreateEffectDelegate>(chromaSdkPointer, "CreateEffect"); CreateKeyboardEffect = GetDelegateFromLibrary <CreateKeyboardEffectDelegate>( chromaSdkPointer, "CreateKeyboardEffect"); CreateMouseEffect = GetDelegateFromLibrary <CreateMouseEffectDelegate>(chromaSdkPointer, "CreateMouseEffect"); CreateHeadsetEffect = GetDelegateFromLibrary <CreateHeadsetEffectDelegate>( chromaSdkPointer, "CreateHeadsetEffect"); CreateMousepadEffect = GetDelegateFromLibrary <CreateMousepadEffectDelegate>( chromaSdkPointer, "CreateMousepadEffect"); CreateKeypadEffect = GetDelegateFromLibrary <CreateKeypadEffectDelegate>( chromaSdkPointer, "CreateKeypadEffect"); CreateChromaLinkEffect = GetDelegateFromLibrary <CreateChromaLinkEffectDelegate>( chromaSdkPointer, "CreateChromaLinkEffect"); DeleteEffect = GetDelegateFromLibrary <DeleteEffectDelegate>(chromaSdkPointer, "DeleteEffect"); SetEffect = GetDelegateFromLibrary <SetEffectDelegate>(chromaSdkPointer, "SetEffect"); RegisterEventNotification = GetDelegateFromLibrary <RegisterEventNotificationDelegate>( chromaSdkPointer, "RegisterEventNotification"); UnregisterEventNotification = GetDelegateFromLibrary <UnregisterEventNotificationDelegate>( chromaSdkPointer, "UnregisterEventNotification"); QueryDevice = GetDelegateFromLibrary <QueryDeviceDelegate>(chromaSdkPointer, "QueryDevice"); }
public void GetConnectionTimeoutShouldReturnDefaultOnInvalidValue() { Environment.SetEnvironmentVariable(EnvironmentHelper.VstestConnectionTimeout, "InvalidValue"); Assert.AreEqual(EnvironmentHelperTests.DefaultTimeout, EnvironmentHelper.GetConnectionTimeout()); }
public void SubmitsTraces(string packageVersion) { #if NET6_0_OR_GREATER if (packageVersion?.StartsWith("3.") == true) { // Versions 3.* of RabbitMQ.Client aren't compatible with .NET 6 // https://github.com/dotnet/runtime/issues/61167 return; } #endif var expectedSpanCount = 26; int basicPublishCount = 0; int basicGetCount = 0; int basicDeliverCount = 0; int exchangeDeclareCount = 0; int queueDeclareCount = 0; int queueBindCount = 0; var distributedParentSpans = new Dictionary <ulong, int>(); int emptyBasicGetCount = 0; using var telemetry = this.ConfigureTelemetry(); using (var agent = EnvironmentHelper.GetMockAgent()) using (RunSampleAndWaitForExit(agent, arguments: $"{TestPrefix}", packageVersion: packageVersion)) { var spans = agent.WaitForSpans(expectedSpanCount); // Do not filter on operation name because they will vary depending on instrumented method Assert.True(spans.Count >= expectedSpanCount, $"Expecting at least {expectedSpanCount} spans, only received {spans.Count}"); var rabbitmqSpans = spans.Where(span => string.Equals(span.Service, ExpectedServiceName, StringComparison.OrdinalIgnoreCase)); var manualSpans = spans.Where(span => !string.Equals(span.Service, ExpectedServiceName, StringComparison.OrdinalIgnoreCase)); foreach (var span in rabbitmqSpans) { Assert.Equal(SpanTypes.Queue, span.Type); Assert.Equal("RabbitMQ", span.Tags[Tags.InstrumentationName]); Assert.False(span.Tags?.ContainsKey(Tags.Version), "External service span should not have service version tag."); Assert.NotNull(span.Tags[Tags.AmqpCommand]); Assert.Equal("amqp.command", span.Name); var command = span.Tags[Tags.AmqpCommand]; if (command.StartsWith("basic.", StringComparison.OrdinalIgnoreCase)) { if (string.Equals(command, "basic.publish", StringComparison.OrdinalIgnoreCase)) { basicPublishCount++; Assert.Equal(SpanKinds.Producer, span.Tags[Tags.SpanKind]); Assert.NotNull(span.Tags[Tags.AmqpExchange]); Assert.NotNull(span.Tags[Tags.AmqpRoutingKey]); Assert.NotNull(span.Tags["message.size"]); Assert.True(int.TryParse(span.Tags["message.size"], out _)); // Enforce that the resource name has the following structure: "basic.publish [<default>|{actual exchangeName}] -> [<all>|<generated>|{actual routingKey}]" string regexPattern = @"basic\.publish (?<exchangeName>\S*) -> (?<routingKey>\S*)"; var match = Regex.Match(span.Resource, regexPattern); Assert.True(match.Success); var exchangeName = match.Groups["exchangeName"].Value; Assert.True(string.Equals(exchangeName, "<default>") || string.Equals(exchangeName, span.Tags[Tags.AmqpExchange])); var routingKey = match.Groups["routingKey"].Value; Assert.True(string.Equals(routingKey, "<all>") || string.Equals(routingKey, "<generated>") || string.Equals(routingKey, span.Tags[Tags.AmqpRoutingKey])); } else if (string.Equals(command, "basic.get", StringComparison.OrdinalIgnoreCase)) { basicGetCount++; // Successful responses will have the "message.size" tag // Empty responses will not if (span.Tags.TryGetValue("message.size", out string messageSize)) { Assert.NotNull(span.ParentId); Assert.True(int.TryParse(messageSize, out _)); // Add the parent span ID to a dictionary so we can later assert 1:1 mappings if (distributedParentSpans.TryGetValue(span.ParentId.Value, out int count)) { distributedParentSpans[span.ParentId.Value] = count + 1; } else { distributedParentSpans[span.ParentId.Value] = 1; } } else { emptyBasicGetCount++; } Assert.Equal(SpanKinds.Consumer, span.Tags[Tags.SpanKind]); Assert.NotNull(span.Tags[Tags.AmqpQueue]); // Enforce that the resource name has the following structure: "basic.get [<generated>|{actual queueName}]" string regexPattern = @"basic\.get (?<queueName>\S*)"; var match = Regex.Match(span.Resource, regexPattern); Assert.True(match.Success); var queueName = match.Groups["queueName"].Value; Assert.True(string.Equals(queueName, "<generated>") || string.Equals(queueName, span.Tags[Tags.AmqpQueue])); } else if (string.Equals(command, "basic.deliver", StringComparison.OrdinalIgnoreCase)) { basicDeliverCount++; Assert.NotNull(span.ParentId); // Add the parent span ID to a dictionary so we can later assert 1:1 mappings if (distributedParentSpans.TryGetValue(span.ParentId.Value, out int count)) { distributedParentSpans[span.ParentId.Value] = count + 1; } else { distributedParentSpans[span.ParentId.Value] = 1; } Assert.Equal(SpanKinds.Consumer, span.Tags[Tags.SpanKind]); // Assert.NotNull(span.Tags[Tags.AmqpQueue]); // Java does this but we're having difficulty doing this. Push to v2? Assert.NotNull(span.Tags[Tags.AmqpExchange]); Assert.NotNull(span.Tags[Tags.AmqpRoutingKey]); Assert.NotNull(span.Tags["message.size"]); Assert.True(int.TryParse(span.Tags["message.size"], out _)); // Enforce that the resource name has the following structure: "basic.deliver [<generated>|{actual queueName}]" string regexPattern = @"basic\.deliver (?<queueName>\S*)"; var match = Regex.Match(span.Resource, regexPattern); // Assert.True(match.Success); // Enable once we can get the queue name included var queueName = match.Groups["queueName"].Value; // Assert.True(string.Equals(queueName, "<generated>") || string.Equals(queueName, span.Tags[Tags.AmqpQueue])); // Enable once we can get the queue name included } else { throw new Xunit.Sdk.XunitException($"amqp.command {command} not recognized."); } } else { Assert.Equal(SpanKinds.Client, span.Tags[Tags.SpanKind]); Assert.Equal(command, span.Resource); if (string.Equals(command, "exchange.declare", StringComparison.OrdinalIgnoreCase)) { exchangeDeclareCount++; Assert.NotNull(span.Tags[Tags.AmqpExchange]); } else if (string.Equals(command, "queue.declare", StringComparison.OrdinalIgnoreCase)) { queueDeclareCount++; Assert.NotNull(span.Tags[Tags.AmqpQueue]); } else if (string.Equals(command, "queue.bind", StringComparison.OrdinalIgnoreCase)) { queueBindCount++; Assert.NotNull(span.Tags[Tags.AmqpExchange]); Assert.NotNull(span.Tags[Tags.AmqpQueue]); Assert.NotNull(span.Tags[Tags.AmqpRoutingKey]); } else { throw new Xunit.Sdk.XunitException($"amqp.command {command} not recognized."); } } } foreach (var span in manualSpans) { Assert.Equal("Samples.RabbitMQ", span.Service); Assert.Equal("1.0.0", span.Tags[Tags.Version]); } } // Assert that all empty get results are expected Assert.Equal(2, emptyBasicGetCount); // Assert that each span that started a distributed trace (basic.publish) // has only one child span (basic.deliver or basic.get) Assert.All(distributedParentSpans, kvp => Assert.Equal(1, kvp.Value)); Assert.Equal(5, basicPublishCount); Assert.Equal(4, basicGetCount); Assert.Equal(3, basicDeliverCount); Assert.Equal(1, exchangeDeclareCount); Assert.Equal(1, queueBindCount); Assert.Equal(4, queueDeclareCount); telemetry.AssertIntegrationEnabled(IntegrationId.RabbitMQ); }