Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 15 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
# Seq HTTP API Client [![Build status](https://ci.appveyor.com/api/projects/status/bhtx25hyqmmdqhvt?svg=true)](https://ci.appveyor.com/project/datalust/seq-api) [![NuGet Pre Release](https://img.shields.io/nuget/vpre/Seq.Api.svg)](https://nuget.org/packages/seq.api) [![Join the chat at https://gitter.im/datalust/seq](https://img.shields.io/gitter/room/datalust/seq.svg)](https://gitter.im/datalust/seq)


This library includes:

* C# representations of the entities exposed by the Seq HTTP API
Expand Down Expand Up @@ -32,7 +31,19 @@ var installedApps = await connection.Apps.ListAsync();

**To authenticate**, the `SeqConnection` constructor accepts an `apiKey` parameter (make sure the API key permits _user-level access_) or, if you want to log in with personal credentials you can `await connection.Users.Login(username, password)`.

For a more complete example, see the [seq-tail app included in the source](https://github.com/continuousit/seq-api/blob/master/example/SeqTail/Program.cs);
For a more complete example, see the [seq-tail app included in the source](https://github.com/datalust/seq-api/blob/master/example/SeqTail/Program.cs).

#### Creating entities

The Seq API provides a `/template` resource for each resource group that provides a new instance of the resource with defaults populated. The API client uses this pattern when creating new entities:

```csharp
var signal = await connection.Signals.TemplateAsync();
signal.Title = "Signal 123";
await connection.Signals.AddAsync(signal);
```

See the [signal-copy app](https://github.com/datalust/seq-api/blob/master/example/SignalCopy/Program.cs) for an example of this pattern in action.

### Reading events

Expand All @@ -46,7 +57,7 @@ string lastReadEventId = null;
while(true)
{
var resultSet = await connection.Events.InSignalAsync(
filter: "Environment == \"Test\"",
filter: "Environment = 'Test'",
render: true,
afterId: lastReadEventId);

Expand All @@ -64,7 +75,7 @@ If the result set is expected to be small, `ListAsync()` will buffer results and

```csharp
var resultSet = await connection.Events.ListAsync(
filter: "Environment == \"Test\"",
filter: "Environment = 'Test'",
render: true,
count: 1000);

Expand Down
36 changes: 0 additions & 36 deletions example/SeqQuery/Properties/AssemblyInfo.cs

This file was deleted.

36 changes: 0 additions & 36 deletions example/SeqTail/Properties/AssemblyInfo.cs

This file was deleted.

14 changes: 14 additions & 0 deletions example/SignalCopy/App.config
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Net.Http.Primitives" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.2.28.0" newVersion="4.2.28.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>
109 changes: 109 additions & 0 deletions example/SignalCopy/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
using System;
using System.Threading.Tasks;
using DocoptNet;
using Seq.Api;
using System.Linq;
using Seq.Api.Model.Signals;
using System.Collections.Generic;

namespace SeqQuery
{
class Program
{
const string Usage = @"signal-copy: copy Seq signals from one server to another.

Usage:
signal-copy.exe <src> <dst> [--srckey=<sk>] [--dstkey=<dk>]
signal-copy.exe (-h | --help)

Options:
-h --help Show this screen.
--srckey=<sk> Source server API key.
--dstkey=<dk> Destination server API key.

";

static void Main(string[] args)
{
Task.Run(async () =>
{
try
{
var arguments = new Docopt().Apply(Usage, args, version: "Seq Signal Copy 0.1", exit: true);

var src = arguments["<src>"].ToString();
var dst = arguments["<dst>"].ToString();
var srcKey = Normalize(arguments["--srckey"]);
var dstKey = Normalize(arguments["--dstkey"]);

await Run(src, srcKey, dst, dstKey);
}
catch (Exception ex)
{
Console.ForegroundColor = ConsoleColor.White;
Console.BackgroundColor = ConsoleColor.Red;
Console.WriteLine("signal-copy: {0}", ex);
Console.ResetColor();
Environment.Exit(-1);
}
}).Wait();
}

static string Normalize(ValueObject v)
{
if (v == null) return null;
var s = v.ToString();
return string.IsNullOrWhiteSpace(s) ? null : s;
}

static async Task Run(string src, string srcKey, string dst, string dstKey)
{
var srcConnection = new SeqConnection(src, srcKey);
var dstConnection = new SeqConnection(dst, dstKey);

var dstSignals = new Dictionary<string, SignalEntity>();
foreach (var dstSignal in await dstConnection.Signals.ListAsync())
{
if (dstSignals.ContainsKey(dstSignal.Title))
{
Console.WriteLine($"The destination server has more than one signal named '{dstSignal.Title}'; only one copy of the signal will be updated.");
continue;
}

dstSignals.Add(dstSignal.Title, dstSignal);
}

var count = 0;

foreach (var signal in await srcConnection.Signals.ListAsync())
{
SignalEntity target;
if (dstSignals.TryGetValue(signal.Title, out target))
{
if (target.IsRestricted)
{
Console.WriteLine($"Skipping restricted signal '{signal.Title}' ({target.Id})");
continue;
}

Console.WriteLine($"Updating existing signal '{signal.Title}' ({target.Id})");
}
else
{
Console.WriteLine($"Creating new signal '{signal.Title}'");
target = await dstConnection.Signals.TemplateAsync();
}

target.Title = signal.Title;
target.Filters = signal.Filters;
target.TaggedProperties = signal.TaggedProperties;
target.Description = signal.Description + " (copy)";

await (target.Id != null ? dstConnection.Signals.UpdateAsync(target) : dstConnection.Signals.AddAsync(target));
++count;
}

Console.WriteLine($"Done, {count} signals updated.");
}
}
}
8 changes: 8 additions & 0 deletions example/SignalCopy/Properties/launchSettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"profiles": {
"SignalCopy": {
"commandName": "Project",
"commandLineArgs": "http://localhost:5341 http://localhost:5342 --srckey=fSCcBOyOfttZ0kiZFgq"
}
}
}
Binary file added example/SignalCopy/getseq_net.ico
Binary file not shown.
28 changes: 28 additions & 0 deletions example/SignalCopy/project.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
{
"version": "1.0.0-*",
"buildOptions": {
"emitEntryPoint": true,
"outputName": "signal-copy"
},

"dependencies": {
"Seq.Api": { "target": "project" },
"docopt.net": "0.6.1.9"
},

"frameworks": {
"net4.6": {},
"netcoreapp1.0": {
"dependencies": {
"Microsoft.NETCore.App": {
"type": "platform",
"version": "1.0.0"
}
},
"imports": [
"dnxcore50",
"portable-net45+win8"
]
}
}
}
19 changes: 19 additions & 0 deletions example/SignalCopy/signal-copy.xproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">14.0</VisualStudioVersion>
<VSToolsPath Condition="'$(VSToolsPath)' == ''">$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)</VSToolsPath>
</PropertyGroup>
<Import Project="$(VSToolsPath)\DotNet\Microsoft.DotNet.Props" Condition="'$(VSToolsPath)' != ''" />
<PropertyGroup Label="Globals">
<ProjectGuid>e8cdde17-8e29-4eb4-a4bb-38bce346a752</ProjectGuid>
<RootNamespace>SignalCopy</RootNamespace>
<BaseIntermediateOutputPath Condition="'$(BaseIntermediateOutputPath)'=='' ">.\obj</BaseIntermediateOutputPath>
<OutputPath Condition="'$(OutputPath)'=='' ">.\bin\</OutputPath>
<TargetFrameworkVersion>v4.5.2</TargetFrameworkVersion>
</PropertyGroup>
<PropertyGroup>
<SchemaVersion>2.0</SchemaVersion>
</PropertyGroup>
<Import Project="$(VSToolsPath)\DotNet\Microsoft.DotNet.targets" Condition="'$(VSToolsPath)' != ''" />
</Project>
7 changes: 7 additions & 0 deletions seq-api.sln
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "seq-query", "example\SeqQue
EndProject
Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "seq-tail", "example\SeqTail\seq-tail.xproj", "{42CEBFBA-208F-40F1-AC95-13F05F6D5412}"
EndProject
Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "signal-copy", "example\SignalCopy\signal-copy.xproj", "{E8CDDE17-8E29-4EB4-A4BB-38BCE346A752}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand All @@ -53,6 +55,10 @@ Global
{42CEBFBA-208F-40F1-AC95-13F05F6D5412}.Debug|Any CPU.Build.0 = Debug|Any CPU
{42CEBFBA-208F-40F1-AC95-13F05F6D5412}.Release|Any CPU.ActiveCfg = Release|Any CPU
{42CEBFBA-208F-40F1-AC95-13F05F6D5412}.Release|Any CPU.Build.0 = Release|Any CPU
{E8CDDE17-8E29-4EB4-A4BB-38BCE346A752}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{E8CDDE17-8E29-4EB4-A4BB-38BCE346A752}.Debug|Any CPU.Build.0 = Debug|Any CPU
{E8CDDE17-8E29-4EB4-A4BB-38BCE346A752}.Release|Any CPU.ActiveCfg = Release|Any CPU
{E8CDDE17-8E29-4EB4-A4BB-38BCE346A752}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand All @@ -62,5 +68,6 @@ Global
{CD473266-4AED-4207-89FD-0B185239F1C7} = {5E7A565B-A8EE-43E7-A225-5B640A5D29A0}
{34BBD428-8297-484E-B771-0B72C172C264} = {1C66E116-DC21-4C8F-833E-A4C2DDF58487}
{42CEBFBA-208F-40F1-AC95-13F05F6D5412} = {1C66E116-DC21-4C8F-833E-A4C2DDF58487}
{E8CDDE17-8E29-4EB4-A4BB-38BCE346A752} = {1C66E116-DC21-4C8F-833E-A4C2DDF58487}
EndGlobalSection
EndGlobal
12 changes: 7 additions & 5 deletions src/Seq.Api/Api/Client/SeqApiClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -170,17 +170,19 @@ async Task<Stream> HttpSendAsync(HttpRequestMessage request)
if (response.IsSuccessStatusCode)
return stream;

Dictionary<string, object> payload = null;
try
{
var payload = _serializer.Deserialize<Dictionary<string, object>>(new JsonTextReader(new StreamReader(stream)));
object error;
if (payload.TryGetValue("Error", out error) && error != null)
throw new SeqApiException(error.ToString());
payload = _serializer.Deserialize<Dictionary<string, object>>(new JsonTextReader(new StreamReader(stream)));
}
// ReSharper disable once EmptyGeneralCatchClause
catch { }

throw new SeqApiException("The Seq request failed (" + response.StatusCode + ").");
object error;
if (payload != null && payload.TryGetValue("Error", out error) && error != null)
throw new SeqApiException($"{(int)response.StatusCode} - {error}");

throw new SeqApiException($"The Seq request failed ({(int)response.StatusCode}).");
}

HttpContent MakeJsonContent(object content)
Expand Down