public void TestCleanup() { CleanupTestMethod(); RestClient = null; HttpClient = null; Server = null; }
public async Task ForexMarketFeed_WorksAsync() { //Arrange var restClient = new JsonRestClient(Server, AccessToken); var config = new Dictionary <string, string> { { "AccountId", AccountId.ToString() }, { "StreamingRatesUri", StreamingRatesUri }, { "AccessToken", AccessToken }, { "SelectedInstruments", "EUR_USD,USD_JPY" } }; var marketFeed = new ForexMarketFeed(restClient, config); var priceTick = new List <IPriceTick>(); marketFeed.TickReceived += new DelegateDefinitions.TickDataHandler(s => priceTick.Add(s)); marketFeed.Initialize(); //Act marketFeed.Startup(); await Task.Delay(20000); marketFeed.Shutdown(); await Task.Delay(5000); //Assert Assert.IsTrue(priceTick.Count > 0); }
public async Task JsonRestClient_WorksAsync() { var client = new JsonRestClient(Server, AccessToken); var request = new JsonGetRequest <Instruments>("instruments?accountId=" + 6184634 + "&instruments=" + Uri.EscapeDataString("EUR_USD,USD_CAD")); var result = await client.Get <Instruments>(request); }
public void WhenCreatingRestClientThenSetsServiceBase() { var uri = new Uri("http://localhost"); var client = new JsonRestClient(uri); Assert.AreEqual(uri, client.ServiceBase); }
public AudioClient(DiscordClient client, Server server, int id) { Id = id; Service = client.GetService <AudioService>(); Config = Service.Config; Serializer = client.Serializer; _gatewayState = (int)ConnectionState.Disconnected; //Logging Logger = client.Log.CreateLogger($"AudioClient #{id}"); //Async _taskManager = new TaskManager(Cleanup, false); _connectionLock = new AsyncLock(); CancelToken = new CancellationToken(true); //Networking if (Config.EnableMultiserver) { //TODO: We can remove this hack when official API launches var baseConfig = client.Config; var builder = new DiscordConfigBuilder { AppName = baseConfig.AppName, AppUrl = baseConfig.AppUrl, AppVersion = baseConfig.AppVersion, CacheToken = baseConfig.CacheDir != null, ConnectionTimeout = baseConfig.ConnectionTimeout, EnablePreUpdateEvents = false, FailedReconnectDelay = baseConfig.FailedReconnectDelay, LargeThreshold = 1, LogLevel = baseConfig.LogLevel, MessageCacheSize = 0, ReconnectDelay = baseConfig.ReconnectDelay, UsePermissionsCache = false }; _config = builder.Build(); ClientAPI = new JsonRestClient(_config, DiscordConfig.ClientAPIUrl, client.Log.CreateLogger($"ClientAPI #{id}")); GatewaySocket = new GatewaySocket(_config, client.Serializer, client.Log.CreateLogger($"Gateway #{id}")); GatewaySocket.Connected += (s, e) => { if (_gatewayState == ConnectionState.Connecting) { EndGatewayConnect(); } }; } else { _config = client.Config; GatewaySocket = client.GatewaySocket; } GatewaySocket.ReceivedDispatch += (s, e) => OnReceivedEvent(e); VoiceSocket = new VoiceSocket(_config, Config, client.Serializer, client.Log.CreateLogger($"Voice #{id}")); VoiceSocket.Server = server; OutputStream = new OutStream(this); }
/// <summary> Initializes a new instance of the DiscordClient class. </summary> public DiscordClient(DiscordConfig config) { Config = config; State = (int)ConnectionState.Disconnected; Status = UserStatus.Online; //Logging Log = new LogManager(this); Logger = Log.CreateLogger("Discord"); if (config.LogLevel >= LogSeverity.Verbose) { _connectionStopwatch = new Stopwatch(); } //Async _taskManager = new TaskManager(Cleanup); _connectionLock = new AsyncLock(); _disconnectedEvent = new ManualResetEvent(true); _connectedEvent = new ManualResetEventSlim(false); CancelToken = new CancellationToken(true); //Cache //ConcurrentLevel = 2 (only REST and WebSocket can add/remove) _servers = new ConcurrentDictionary <ulong, Server>(2, 0); _channels = new ConcurrentDictionary <ulong, IChannel>(2, 0); _privateChannels = new ConcurrentDictionary <ulong, PrivateChannel>(2, 0); //Serialization Serializer = new JsonSerializer(); Serializer.DateTimeZoneHandling = DateTimeZoneHandling.Utc; #if TEST_RESPONSES Serializer.CheckAdditionalContent = true; Serializer.MissingMemberHandling = MissingMemberHandling.Error; #else Serializer.CheckAdditionalContent = false; Serializer.MissingMemberHandling = MissingMemberHandling.Ignore; #endif Serializer.Error += (s, e) => { e.ErrorContext.Handled = true; Logger.Error("Serialization Failed", e.ErrorContext.Error); }; //Networking ClientAPI = new JsonRestClient(Config, DiscordConfig.ClientAPIUrl, Log.CreateLogger("ClientAPI")); StatusAPI = new JsonRestClient(Config, DiscordConfig.StatusAPIUrl, Log.CreateLogger("StatusAPI")); GatewaySocket = new GatewaySocket(Config, Serializer, Log.CreateLogger("Gateway")); //GatewaySocket.Disconnected += (s, e) => OnDisconnected(e.WasUnexpected, e.Exception); GatewaySocket.ReceivedDispatch += (s, e) => OnReceivedEvent(e); MessageQueue = new MessageQueue(ClientAPI, Log.CreateLogger("MessageQueue")); //Extensibility _services = new ServiceCollection(this); }
static BaseTests() { _configuration = new ConfigurationBuilder() .AddJsonFile("settings.json") .Build(); var jsonClient = new JsonRestClient(_configuration["api_url"], _configuration["api_key"], _configuration["api_secret"]); _restClient = new WooCommerceRestClient(jsonClient); }
public async Task <JiraCreateIssueResponse> CreateIssueAsync(JiraAction action, Error error, string accountName) { var url = GetUrl(action); var userName = GetUsername(action); var password = GetPassword(action); var projectKey = GetProjectKey(action); var client = new JsonRestClient(url) { Username = userName, Password = password }; var fields = new Dictionary <string, object> { ["project"] = new { key = projectKey }, ["issuetype"] = new { name = action.Name }, ["summary"] = error.Message.CleanCRLF().TruncateWithEllipsis(255), ["description"] = RenderDescription(error, accountName) }; var components = action.GetComponentsForApplication(error.ApplicationName); if (components?.Count > 0) { fields.Add("components", components); } var labels = action.Labels.IsNullOrEmpty() ? null : action.Labels.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); if (labels?.Length > 0) { fields.Add("labels", labels); } var payload = new { fields }; var result = await client.PostAsync <JiraCreateIssueResponse, object>("issue", payload); var commentBody = RenderVariableTable("Server Variables", error.ServerVariables) + RenderVariableTable("QueryString", error.QueryString) + RenderVariableTable("Form", error.Form) + RenderVariableTable("Cookies", error.Cookies) + RenderVariableTable("RequestHeaders", error.RequestHeaders); if (commentBody.HasValue()) { await CommentAsync(action, result, commentBody); } result.Host = GetHost(action); return(result); }
async void Start() { try { var jsonClient = new JsonRestClient(this); var url = isLocal ? "http://*****:*****@" + response.IpAddress + " on:" + response.Port); client.StartNetworked(response.Port, response.IpAddress, response.PlayerSessionId, this, settings); } catch (Exception e) { Debug.LogError("failed to start"); Debug.LogError(e); } }
public void TestInitialize() { Environment.SetEnvironmentVariable( "ASPNETCORE_ENVIRONMENT", "Development" ); var webHostBuilder = new WebHostBuilder() .UseStartup <Startup>() .UseContentRoot(TestContentRoot); Server = new TestServer(webHostBuilder); HttpClient = Server.CreateClient(); RestClient = new JsonRestClient(new HttpClientProvider(HttpClient)); InitializeTestMethod(); }
public void Setup() { var mockResponse = new Mock <WebResponse>(); mockResponse.Setup(x => x.GetResponseStream()).Returns(new MemoryStream()); _mockRequest = new Mock <HttpWebRequest>(); _mockRequest.Setup(x => x.GetRequestStream()).Returns(new MemoryStream()); _mockRequest.Setup(x => x.GetResponse()).Returns(() => mockResponse.Object); var mockWebRequestCreate = new Mock <IWebRequestCreate>(); mockWebRequestCreate.Setup(x => x.Create(It.IsAny <Uri>())).Returns(() => _mockRequest.Object); HttpWebRequest.RegisterPrefix("http://localhost", mockWebRequestCreate.Object); _mockRequest.Object.Headers = new WebHeaderCollection(); _jsonClient = new JsonRestClient(new Uri("http://localhost")); }
public async Task <string> CommentAsync(JiraCreateIssueResponse createResponse, string comment) { var client = new JsonRestClient(JiraApiUrl) { Username = Username, Password = Password }; var payload = new { body = comment }; var resource = $"issue/{createResponse.Key}/comment"; var response = await client.PostAsync <string, object>(resource, payload).ConfigureAwait(false); return(response); }
public AudioClient(DiscordClient client, Server server, int id) { Id = id; _config = client.Config; Service = client.Services.Get <AudioService>(); Config = Service.Config; Serializer = client.Serializer; _gatewayState = (int)ConnectionState.Disconnected; //Logging Logger = client.Log.CreateLogger($"AudioClient #{id}"); //Async _taskManager = new TaskManager(Cleanup, false); _connectionLock = new AsyncLock(); CancelToken = new CancellationToken(true); //Networking if (Config.EnableMultiserver) { ClientAPI = new JsonRestClient(_config, DiscordConfig.ClientAPIUrl, client.Log.CreateLogger($"ClientAPI #{id}")); GatewaySocket = new GatewaySocket(_config, client.Serializer, client.Log.CreateLogger($"Gateway #{id}")); GatewaySocket.Connected += (s, e) => { if (_gatewayState == ConnectionState.Connecting) { EndGatewayConnect(); } }; } else { GatewaySocket = client.GatewaySocket; } GatewaySocket.ReceivedDispatch += (s, e) => OnReceivedEvent(e); VoiceSocket = new VoiceSocket(_config, Config, client.Serializer, client.Log.CreateLogger($"Voice #{id}")); VoiceSocket.Server = server; OutputStream = new OutStream(this); }
public async Task <string> CommentAsync(JiraAction actions, JiraCreateIssueResponse createResponse, string comment) { var url = GetUrl(actions); var userName = GetUsername(actions); var password = GetPassword(actions); var client = new JsonRestClient(url) { Username = userName, Password = password }; var payload = new { body = comment }; var resource = $"issue/{createResponse.Key}/comment"; var response = await client.PostAsync <string, object>(resource, payload); return(response); }
public async Task <bool> CreateIssue(Event <LogEventData> evt) { if (evt == null) { return(false); } if ((LogEventLevelList?.Count ?? 0) > 0 && !LogEventLevelList.Contains(evt.Data.Level)) { return(false); } var description = evt.Data.Exception ?? evt.Data.RenderedMessage; var messageId = ComputeId(description); var summary = evt.Data.RenderedMessage.CleanCRLF().TruncateWithEllipsis(255); var client = new JsonRestClient(JiraApiUrl) { Username = Username, Password = Password }; // Try to match if (SeqEventField.HasValue) { var searchUrl = GiveMeTheSearchDuplicateIssueUrl(messageId); var searchResult = await client.GetAsync <JiraIssueSearchResult>(searchUrl).ConfigureAwait(false); if ((searchResult?.total ?? 0) > 0) { return(false); } } var fields = new Dictionary <string, object> { { "project", new { key = ProjectKey.Trim() } }, { "issuetype", new { name = JiraIssueType.Trim() } }, { "summary", summary }, { "description", RenderDescription(evt) }, }; // Process components var components = ComponentsAsArray; if ((components?.Count ?? 0) > 0) { fields.Add("components", components); } // Process labels var labels = Labels.IsNullOrEmpty() ? null : Labels.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); if ((labels?.Length ?? 0) > 0) { fields.Add("labels", labels.TrimAll()); } if (SeqEventField.HasValue) { fields.Add($"customfield_{SeqEventField}", messageId); } var payload = new { fields }; //var payloadJson = JsonConvert.SerializeObject(payload); // Create the issue _step = "Will create issue"; var result = await client.PostAsync <JiraCreateIssueResponse, object>("issue", payload) .ConfigureAwait(false); if ((result?.Errors?.Count ?? 0) > 0) { var e = new ApplicationException("Jira errors are " + JsonConvert.SerializeObject(result.Errors)); Log.Error(e, "Can not crate issue on Jira"); return(false); } _step = "Issue created"; // Add details as comment if (!FullDetailsInDescription) { _step = "Will add details as comment"; var commentBody = $"{{noformat}}{evt.Data.RenderedMessage}{{noformat}}"; if (commentBody.HasValue()) { await CommentAsync(result, commentBody).ConfigureAwait(false); } _step = "Added details as comment"; } // Properties as comment if (PropertiesAsComment) { _step = "Will add properties as comment"; var commentBody = RenderProperties(evt, "Structured Event Properties"); if (commentBody.HasValue()) { await CommentAsync(result, commentBody).ConfigureAwait(false); } _step = "Added properties as comment"; } return(true); }
private async Task <bool> CreateIssue(Event <LogEventData> evt) { if (evt == null) { return(false); } if ((LogEventLevelList?.Count ?? 0) > 0 && !LogEventLevelList.Contains(evt.Data.Level)) { return(false); } if (!(GitLabProjectName ?? "").HasValue() || !(GitLabPrivateToken ?? "").HasValue()) { return(false); } object projectNamePropValue = null; evt?.Data?.Properties?.TryGetValue(GitLabProjectName, out projectNamePropValue); var projectName = projectNamePropValue?.ToString() ?? GitLabProjectName; if (!(projectName ?? "").HasValue()) { return(false); } var apiBaseUrl = GitLabRestApiUrl.NormalizeHostOrFQDN(); var client = new JsonRestClient(apiBaseUrl); client.DoNotAuthorize = true; // Add private token data to request header Dictionary <string, string> headers = new Dictionary <string, string> { ["PRIVATE-TOKEN"] = GitLabPrivateToken }; _step = $"Will get project id for {projectName}"; var searchResult = await client.GetAsync <List <IdDto> >($"projects/search/{projectName}", headers) .ConfigureAwait(false); var projectId = searchResult.FirstOrDefault(); if (projectId == null) { Log.Error($"Project not found {projectName}"); return(false); } var renderedMessage = (evt?.Data?.RenderedMessage ?? ""); var summary = renderedMessage.CleanCRLF().TruncateWithEllipsis(255); _step = $"DONE get project id for {projectName}"; var seqUrl = SeqUrl.NormalizeHostOrFQDN(); var eventUrl = $"{seqUrl}#/events?filter=@Id%20%3D%20'{evt.Id}'"; var propValuesInTitle = BuildPropertyValuesString(evt, TitlePropertiesList); var labels = BuildPropertyValuesString(evt, LabelPropertiesList, ",", (AddLogLevelAsLabel ? new string[1] { evt.Data.Level.ToString() } : null)); StringBuilder sb = new StringBuilder(); // Attach the rendered message if (renderedMessage.HasValue()) { sb.AppendLine($"**Message** [View Event]({eventUrl})"); sb.AppendLine("```"); sb.AppendLine(renderedMessage); sb.AppendLine("```"); sb.AppendLine(""); } // If event has exception attach that Exception if (AttachException && (evt?.Data?.Exception ?? "").HasValue()) { sb.AppendLine("**Exception**"); sb.AppendLine("```"); sb.AppendLine(evt?.Data?.Exception); sb.AppendLine("```"); sb.AppendLine(""); } // Attach structured properties if (AttachProperties && (evt?.Data?.Properties?.Count ?? 0) > 0) { sb.AppendLine("**Properties**"); var allProps = evt.Data.Properties; var additionPropList = AdditionalPropertiesList; sb.AppendLine("```"); foreach (var kvp in allProps) { if (additionPropList?.Count > 0 && !additionPropList.Contains(kvp.Key)) { continue; } sb.AppendLine($"* {kvp.Key} : {(kvp.Value != null ? JsonConvert.SerializeObject(kvp.Value) : "")}");; } sb.AppendLine("```"); sb.AppendLine(""); } // Create the issue var gitLabIssue = new NewIssuePayload { id = projectId.id, title = $"{(propValuesInTitle.HasValue() ? propValuesInTitle + " : " : "")}{summary}", description = sb.ToString(), labels = labels }; _step = $"Will create issue for {projectId.id} -> {projectName}"; // Post the message var createIssueResult = await client.PostAsync <NewIssueResponsePayload, NewIssuePayload>($"projects/{projectId.id}/issues", gitLabIssue, headers) .ConfigureAwait(false); if (createIssueResult == null || !createIssueResult.id.HasValue) { var e = new ApplicationException($"Can not create issue for project {projectId.id} -> {projectName}"); var error = (createIssueResult?.error ?? ""); Log.Error(e, "GitLab create issue failure : {error}", error); return(false); } _step = $"DONE create issue {projectId.id} -> {projectName}"; return(true); }
public AudioClient(DiscordClient client, Server server, int id) { Id = id; _config = client.Config; Service = client.Services.Get<AudioService>(); Config = Service.Config; Serializer = client.Serializer; _gatewayState = (int)ConnectionState.Disconnected; //Logging Logger = client.Log.CreateLogger($"AudioClient #{id}"); //Async _taskManager = new TaskManager(Cleanup, false); _connectionLock = new AsyncLock(); CancelToken = new CancellationToken(true); //Networking if (Config.EnableMultiserver) { ClientAPI = new JsonRestClient(_config, DiscordConfig.ClientAPIUrl, client.Log.CreateLogger($"ClientAPI #{id}")); GatewaySocket = new GatewaySocket(_config, client.Serializer, client.Log.CreateLogger($"Gateway #{id}")); GatewaySocket.Connected += (s, e) => { if (_gatewayState == ConnectionState.Connecting) EndGatewayConnect(); }; } else GatewaySocket = client.GatewaySocket; GatewaySocket.ReceivedDispatch += (s, e) => OnReceivedEvent(e); VoiceSocket = new VoiceSocket(_config, Config, client.Serializer, client.Log.CreateLogger($"Voice #{id}")); VoiceSocket.Server = server; OutputStream = new OutStream(this); }
private async Task <bool> PostMessage(Event <LogEventData> evt) { if (evt == null) { return(false); } if ((LogEventLevelList?.Count ?? 0) > 0 && !LogEventLevelList.Contains(evt.Data.Level)) { return(false); } if (!(Channel ?? "").HasValue()) { return(false); } var apiBaseUrl = RocketApiUrl.NormalizeHostOrFQDN(); var client = new JsonRestClient(apiBaseUrl); client.DoNotAuthorize = true; // Get the auth ticket _step = "Will authenticate: " + client.GetUriForResource("login"); var authTicket = await client.PostAsync <RocketAuthTicket, RocketAuthPayload>("login", new RocketAuthPayload { username = Username, password = Password }) .ConfigureAwait(false); if (authTicket?.data == null || authTicket.status != "success") { var e = new ApplicationException("Can not authenticate Rocket.Chat with the specified username/passwod"); Log.Error(e, "Rocket.Chat authentication failure"); return(false); } _step = "Done authenticate"; var renderedMessage = (evt?.Data?.RenderedMessage ?? ""); var summary = renderedMessage.CleanCRLF().TruncateWithEllipsis(255); var channel = Channel.StartsWith("#") ? Channel.Trim() : $"#{Channel.Trim()}"; var seqUrl = SeqUrl.NormalizeHostOrFQDN(); var eventUrl = $"{seqUrl}#/events?filter=@Id%20%3D%20'{evt.Id}'"; var propValuesInTitle = BuildPropertyValuesString(evt); // Create the rocket message var rocketMessage = new RocketChatMessage { channel = channel, text = $"[ View Event ]({eventUrl}) {(propValuesInTitle.HasValue() ? propValuesInTitle + " : " : "")}{summary}" }; // Attach the rendered message if (renderedMessage.HasValue()) { var attachment = new RocketChatMessageAttachment { color = RocketChatMessageAttachment.ColorByLevel(evt.Data.Level), title = "Message", //title_link = eventUrl, collapsed = true, }; var field = new RocketChatMessageAttachmentField { @short = false, value = renderedMessage, }; attachment.fields = attachment.fields ?? new List <RocketChatMessageAttachmentField>(); attachment.fields.Add(field); rocketMessage.attachments = rocketMessage.attachments ?? new List <RocketChatMessageAttachment>(); rocketMessage.attachments.Add(attachment); } // If event has exception attach that Exception if (AttachException && (evt?.Data?.Exception ?? "").HasValue()) { var attachment = new RocketChatMessageAttachment { color = RocketChatMessageAttachment.ColorByLevel(LogEventLevel.Fatal), title = "Exception", //title_link = eventUrl, collapsed = true, }; var field = new RocketChatMessageAttachmentField { @short = false, value = evt.Data.Exception, }; attachment.fields = attachment.fields ?? new List <RocketChatMessageAttachmentField>(); attachment.fields.Add(field); rocketMessage.attachments = rocketMessage.attachments ?? new List <RocketChatMessageAttachment>(); rocketMessage.attachments.Add(attachment); } // Attach structured properties if (AttachProperties && (evt?.Data?.Properties?.Count ?? 0) > 0) { var attachment = new RocketChatMessageAttachment { title = "Additional Data", //title_link = eventUrl, collapsed = true }; var allProps = evt.Data.Properties; var additionPropList = AdditionalPropertiesList; foreach (var kvp in allProps) { if (additionPropList?.Count > 0 && !additionPropList.Contains(kvp.Key)) { continue; } var field = new RocketChatMessageAttachmentField { @short = false, title = kvp.Key, value = kvp.Value != null?JsonConvert.SerializeObject(kvp.Value) : "" }; attachment.fields = attachment.fields ?? new List <RocketChatMessageAttachmentField>(); attachment.fields.Add(field); } rocketMessage.attachments = rocketMessage.attachments ?? new List <RocketChatMessageAttachment>(); rocketMessage.attachments.Add(attachment); } // Add auth token data to request header Dictionary <string, string> authHeaders = new Dictionary <string, string> { ["X-User-Id"] = authTicket.data.userId, ["X-Auth-Token"] = authTicket.data.authToken, }; _step = "Will post message"; // Post the message var postMessageResult = await client.PostAsync <RocketChatPostMessageResult, RocketChatMessage>("chat.postMessage", rocketMessage, authHeaders).ConfigureAwait(false); if (postMessageResult == null || !postMessageResult.success) { var e = new ApplicationException("Can not post message to Rocket.Chat"); var error = (postMessageResult?.error ?? ""); Log.Error(e, "Rocket.Chat post message failure : {error}", error); return(false); } _step = "Done post message"; return(true); }