Git Product home page Git Product logo

splunk-sdk-csharp-pcl's Introduction

Splunk Enterprise SDK for C#

Version 2.2.9

Deprecation Notice

Please note that the Splunk Enterprise SDK for C# v2.x is deprecated.

What deprecation means

  • Splunk will no longer provide any feature enhancements, bug fixes and support to the Splunk Enterprise SDK for C# v2.x.
  • The resources relating to the Splunk Enterprise SDK for C# v2.x will soon be removed from dev.splunk.com and will only be available in the GitHub repository.
  • Apps that use the Splunk Enterprise SDK for C# v2.x will continue to work as they do now.
  • The Splunk Enterprise SDK for C# v2.x project will continue to be available as an archived repo on GitHub, should developers want to clone or fork the project.

Recommendation for new app development and app updates

Splunk is no longer investing in the Splunk Enterprise SDK for C# v2.x. We recommend that any app development be done using these other approaches:

  • Directly using the Splunk REST API in the language of their choice.

For existing apps that use the Splunk Enterprise SDK for C# v2.x, we request that developers update their apps to use one of the above approaches. We encourage you to post your feedback and questions regarding this to Splunk Answers in the "Splunk Development" community with the tag splunk-csharp-sdk.

The Splunk Enterprise Software Development Kit (SDK) for C# contains library code and examples designed to enable developers to build applications using the Splunk platform.

The Splunk platform is a search engine and analytic environment that uses a distributed map-reduce architecture to efficiently index, search, and process large time-varying data sets.

The Splunk platform is popular with system administrators for aggregation and monitoring of IT machine data, security, compliance, and a wide variety of other scenarios that share a requirement to efficiently index, search, analyze, and generate real-time notifications from large volumes of time-series data.

The Splunk developer platform enables developers to take advantage of the same technology used by the Splunk platform to build exciting new applications.

For more information, see Splunk Enterprise SDK for C# on the Splunk Developer Portal.

What's new in Version 2.x

Version 2.0 introduces new modern APIs that leverage the latest .NET platform advancements.

  • Async. All APIs are 100% asynchronous supporting the new async/await features.
  • All APIs follow .NET guidelines and abide by FxCop and StyleCop rules.
  • Reactive Extensions. Splunk Enterprise query results implement IObservable, allowing usage with the .NET Reactive Extensions.
  • Support for cross-platform development. The Splunk API client (Splunk.Client.dll) in the new version is a Portable Class Library supporting .NET development on multiple platforms.

Below is an example of a simple one shot search:

using Splunk.Client;

var service = new Service(new Uri("https://localhost:8089"));

//login
await service.LogOnAsync("admin", "changeme");

//create a One Shot Search and retrieve the results
var searchResults = await service.SearchOneShotSearchAsync("search index=_internal | head 10");

//loop through the results
foreach (var result in searchResults)
{
    //write out the raw event
    Console.WriteLine(string.Format("{0:D8}: {1}", ++recordNumber, result.GetValue("_raw")));
}

Supported platforms

This SDK supports .NET 4.5/Mono 3.4, PCL (Windows 8.1), iOS (via Xamarin.iOS), and Android (via Xamarin.Android) platforms.

Compatibility

The Splunk Enterprise SDK for C# version 2.x is a rewrite of the 1.x SDK, and introduces completely new APIs.

Important: Applications built with Splunk Enterprise SDK for C# version 1.x will not recompile using Splunk Enterprise SDK for C# version 2.xf.

Splunk Enterprise SDK for C# version 2.x includes a subset of the capability in version 1.0 of the SDK, and focuses on the most common customer scenarios. The major focus areas are search, search jobs, configuration, and modular inputs.

The areas that are covered are:

  • Login
  • Access control (users and passwords)
  • Searches (normal, blocking, oneshot, and export)
  • Jobs
  • Reports (saved searches)
  • Configuration and properties
  • Indexes
  • Inputs (sending simple and streamed events to Splunk Enterprise)
  • Applications
  • Modular inputs

See the Splunk REST API Coverage for details.

Getting started with the Splunk Enterprise SDK for C#

The Splunk Enterprise SDK for C# contains library code and examples that show how to programmatically interact with the Splunk platform for a variety of scenarios including searching, saved searches, data inputs, and many more, along with building complete applications.

Requirements

Here's what you need to get going with the Splunk Enterprise SDK for C# version 2.x.

  • Splunk Enterprise

    If you haven't already installed Splunk Enterprise, download it here. For more information, see the Splunk Enterprise Installation Manual.

    The Splunk Enterprise SDK for C# has been tested with Splunk Enterprise 7.0 and 7.2.

  • Splunk Enterprise SDK for C#

    • Use the MyGet feed

      Download the Splunk SDK C# NuGet packages from MyGet. Add the following feed to your package sources in Visual Studio: https://splunk.myget.org/F/splunk-sdk-csharp-pcl/

      The following packages are in that feed:

      • Splunk.Client: Client for the Splunk Enterprise REST API. This library is portable.

      • Splunk.ModularInputs: Functionality for building modular inputs.

        Note: Both packages are published to NuGet when the SDK is released.

    • Get the source

      Download the Splunk Enterprise SDK for C# ZIP file and extract the contents. If you are want to contribute to the Splunk Enterprise SDK for C#, clone the repository from GitHub.

Developer environments

The Splunk Enterprise SDK for C# supports development in the following environments:

  • Microsoft Visual Studio 2012 and later

    You must also install Code Contracts for .NET.

    Note: Close Visual Studio before installing Code Contracts. Otherwise, the installation will not work, despite appearing to.

    To run the unit tests, install an xUnit runner. If you use resharper, install its xUnit.net Test Support. Otherwise, install the xUnit.net runner for Visual Studio 2012 and 2013.

  • Xamarin Studio and Mono Develop

    You must set the MonoCS compilation constant in the project settings for Splunk.Client.csproj and Splunk.ModularInputs.csproj.

    To run the unit tests, download xUnit and run it using the command-line tools or GUI runner.

Build the SDK

To build the SDK, the examples, and the unit tests after extracting or cloning the SDK:

  1. At the root level of the splunk-sdk-csharp-pcl directory, open the splunk-sdk-csharp-pcl.sln file in Visual Studio.
  2. On the BUILD menu, click Build Solution.

Examples and unit tests

The Splunk Enterprise SDK for C# includes full unit tests that run using xunit as well as several examples.

Solution layout

Directory Description
/src
   Splunk.Client Client for the Splunk Enterprise REST API.
   Splunk.ModularInputs Functionality for building modular inputs.
   Splunk.Client.Helpers Helper utilities used by tests and samples.
/examples
   Windows8/Search Contains a Windows Store Search App.
   authenticate Connects to a Splunk Enterprise instance and retrieves a session token.
   list_apps Lists installed applications on a Splunk Enterprise instance.
   mock-context Demonstrates how to use the included HTTP record/play framework for unit tests.
   mock-interface Demonstrates how to mock the functional interface for Splunk Enterprise entities.
   mock-object Demontrates how to mock concrete SDK objects and create fake HTTP responses for unit tests.
   normal-search Performs a normal search against a Splunk Enterprise instance and retrieves results using enumeration and Rx.
   random-numbers Sample modular input that returns randomly-generated numbers.
   saved-searches Creates a saved search and retrieves results.
   search-export Creates a search and uses the Export endpoint to return results.
   search-realtime Creates a real-time search.
   search-response-message-stream Demonstrates how to run long-running search jobs and use Job.GetSearchReponseMessageAsync.
   search Performs a oneshot search.
   submit Creates an index, then sends events to it over HTTP.
/tests
   unit-tests Contains unit tests for all of the classes in the SDK. Does not require a Splunk Enterprise instance.
   acceptance-tests Contains end-to-end tests using the SDK. By default, these tests run against a Splunk Enterprise instance. You can also run tests in playback mode by setting MockContext.Mode to "Playback" in App.Config.

Changelog

The CHANGELOG contains a description of changes for each version of the SDK. For the latest version, see the CHANGELOG.md on GitHub.

Branches

The master branch represents a stable and released version of the SDK. To learn about our branching model, see Branching Model on GitHub.

Documentation and resources

Resource Description
Splunk Developer Portal General developer documentation, tools, and examples
Integrate the Splunk platform using development tools for .NET Documentation for .NET development
Splunk Enterprise SDK for C# Reference SDK API reference documentation
REST API Reference Manual Splunk REST API reference documentation
Splunk>Docs General documentation for the Splunk platform
GitHub Wiki Documentation for this SDK's repository on GitHub

Community

Stay connected with other developers building on the Splunk platform.

Contributions

If you would like to contribute to the SDK, see Contributing to Splunk. For additional guidelines, see CONTRIBUTING.

Support

  • You will be granted support if you or your company are already covered under an existing maintenance/support agreement. Submit a new case in the Support Portal and include "Splunk Enterprise SDK for C# PCL" in the subject line.

    If you are not covered under an existing maintenance/support agreement, you can find help through the broader community at Splunk Answers.

  • Splunk will NOT provide support for SDKs if the core library (the code in the 1. src directory) has been modified. If you modify an SDK and want support, you can find help through the broader community and Splunk Answers.

    We would also like to know why you modified the core library, so please send feedback to [email protected].

  • File any issues on GitHub.

Contact Us

You can reach the Splunk Developer Platform team at [email protected].

License

The Splunk Enterprise Software Development Kit for C# is licensed under the Apache License 2.0. See LICENSE for details.

splunk-sdk-csharp-pcl's People

Contributors

adamralph avatar adamryman avatar apruneda avatar brattonc avatar fantavlik avatar glennblock avatar itay avatar ljiang1 avatar martinmine avatar mryanmurphy avatar mtevenan-splunk avatar ncanumalla-splunk avatar pking70 avatar shakeelmohamed avatar shilpabijam avatar wimcolgate avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

splunk-sdk-csharp-pcl's Issues

Search with Push model .NET5

Hi there,

I'm just wondering where did the Subscribe() method go in a Push Model Search.

I'm using Splunk.Client.DotnetCore Version="1.0.7" nuget package.

This is what I get:

2022_04_06_15_44_22_ReportingRockwell_-_Microsoft_Visual_Studio

2022_04_06_15_57_14_splunk-sdk-csharp-pcl_-_Microsoft_Visual_Studio

Timeout exception on job.GetSearchResultsAsync

Hi,

is it possible to set a timeout for job.GetSearchResultAsync ? I was able to set the timeout on the context for the service, but that does not seem to have an effect on this call. I'm getting this exception

System.Threading.Tasks.TaskCanceledException occurred
  HResult=0x8013153B
  Message=A task was canceled.
  Source=<Cannot evaluate the exception source>
  StackTrace:
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Splunk.Client.Context.<SendAsync>d__37.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Splunk.Client.Context.<GetResponseAsync>d__36.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Splunk.Client.Context.<GetAsync>d__23.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Splunk.Client.Job.<GetAsync>d__111.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Splunk.Client.Job.<TransitionAsync>d__112.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Splunk.Client.Job.<GetSearchResultsAsync>d__142.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Splunk.Client.Job.<GetSearchResultsAsync>d__120.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Splunk.Client.Job.<GetSearchResultsAsync>d__121.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()

On the server side, i run the same query and it is done withing a minute. It also returns 4MB of data, so I don't see why this is an issue.

It looks to me like there is a fixed timeout of 30 seconds somewhere?

Is that the case, or am I going at it wrong?

saved-searches example program exception when calling AtomEntry.cs

When running the C# SDK release 2.2.2 against Splunk Server v6.3.3, the saved-searches example program fails and throws an exception when calling AtomEntry in Splunk.Client. See the exception details below. The cause appears to be an attempted duplicate propertyName in AtomEntry and its subsequent addition in the dictionary, at or around line 396.

System.AggregateException was unhandled
  HResult=-2146233088
  Message=One or more errors occurred.
  Source=mscorlib
  StackTrace:
       at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
       at System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout, CancellationToken cancellationToken)
       at System.Threading.Tasks.Task.Wait()
       at Splunk.Examples.saved_searches.Program.Main(String[] args) in C:\Users\jdhea\Documents\Visual Studio 2015\Projects\splunk-sdk-csharp-pcl-2.2.2\examples\saved-searches\Program.cs:line 33
       at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException: 
       HResult=-2146233087
       Message=Found invalid data while decoding.
       Source=Splunk.Client
       StackTrace:
            at Splunk.Client.AtomEntry.<ParseDictionaryAsync>d__32.MoveNext() in C:\Users\jdhea\Documents\Visual Studio 2015\Projects\splunk-sdk-csharp-pcl-2.2.2\src\Splunk.Client\Splunk\Client\AtomEntry.cs:line 396
         --- End of stack trace from previous location where exception was thrown ---
            at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
            at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
            at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1.ConfiguredTaskAwaiter.GetResult()
            at Splunk.Client.AtomEntry.<ParsePropertyValueAsync>d__34.MoveNext() in C:\Users\jdhea\Documents\Visual Studio 2015\Projects\splunk-sdk-csharp-pcl-2.2.2\src\Splunk.Client\Splunk\Client\AtomEntry.cs:line 468
         --- End of stack trace from previous location where exception was thrown ---
            at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
            at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
            at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1.ConfiguredTaskAwaiter.GetResult()
            at Splunk.Client.AtomEntry.<ReadXmlAsync>d__29.MoveNext() in C:\Users\jdhea\Documents\Visual Studio 2015\Projects\splunk-sdk-csharp-pcl-2.2.2\src\Splunk.Client\Splunk\Client\AtomEntry.cs:line 236
         --- End of stack trace from previous location where exception was thrown ---
            at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
            at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
            at System.Runtime.CompilerServices.ConfiguredTaskAwaitable.ConfiguredTaskAwaiter.GetResult()
            at Splunk.Client.AtomFeed.<ReadXmlAsync>d__40.MoveNext() in C:\Users\jdhea\Documents\Visual Studio 2015\Projects\splunk-sdk-csharp-pcl-2.2.2\src\Splunk.Client\Splunk\Client\AtomFeed.cs:line 259
         --- End of stack trace from previous location where exception was thrown ---
            at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
            at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
            at System.Runtime.CompilerServices.ConfiguredTaskAwaitable.ConfiguredTaskAwaiter.GetResult()
            at Splunk.Client.BaseEntity`1.<CreateAsync>d__18`1.MoveNext() in C:\Users\jdhea\Documents\Visual Studio 2015\Projects\splunk-sdk-csharp-pcl-2.2.2\src\Splunk.Client\Splunk\Client\BaseEntity.cs:line 221
         --- End of stack trace from previous location where exception was thrown ---
            at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
            at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
            at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1.ConfiguredTaskAwaiter.GetResult()
            at Splunk.Client.EntityCollection`2.<GetOrNullAsync>d__13.MoveNext() in C:\Users\jdhea\Documents\Visual Studio 2015\Projects\splunk-sdk-csharp-pcl-2.2.2\src\Splunk.Client\Splunk\Client\EntityCollection.cs:line 269
         --- End of stack trace from previous location where exception was thrown ---
            at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
            at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
            at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
            at Splunk.Examples.saved_searches.Program.<Run>d__1.MoveNext() in C:\Users\jdhea\Documents\Visual Studio 2015\Projects\splunk-sdk-csharp-pcl-2.2.2\examples\saved-searches\Program.cs:line 48
       InnerException:

Unit tests fail - localisation issues

I've just downloaded & built the Splunk C# SDK - on running unit tests I get 4 failures. All seem to be related to my locale - I'm in the United Kingdom.


---  Splunk.Client.UnitTests.TestAtomFeed.CanReadAtomEntry
Exception
Xunit.Sdk.EqualException: Assert.Equal() Failure
Position: First difference is at position 196
Expected: AtomEntry(Title=search search index=_internal | head 1000, Author=admin, Id=https://localhost:8089/services/search/jobs/scheduler__admin__search__RMD50aa4c13eb03d1730_at_1401390000_866, Published=5/29/2014 12:00:01 PM, Updated=5/29/2014 1:01:08 PM)
Actual:   AtomEntry(Title=search search index=_internal | head 1000, Author=admin, Id=https://localhost:8089/services/search/jobs/scheduler__admin__search__RMD50aa4c13eb03d1730_at_1401390000_866, Published=29/05/2014 20:00:01, Updated=29/05/2014 21:01:08)
   at Splunk.Client.UnitTests.TestAtomFeed.<CanReadAtomEntry>d__1.MoveNext() in C:\DevWork\Experiments\Splink\splunk-sdk-csharp-pcl-2.2.5\test\unit-tests\TestAtomFeed.cs:line 38

--- Splunk.Client.UnitTests.TestAtomFeed.CanReadAtomFeed
Exception
Xunit.Sdk.EqualException: Assert.Equal() Failure
Position: First difference is at position 92
Expected: AtomFeed(Title=jobs, Author=Splunk, Id=https://localhost:8089/services/search/jobs, Updated=5/29/2014 12:13:01 PM)
Actual:   AtomFeed(Title=jobs, Author=Splunk, Id=https://localhost:8089/services/search/jobs, Updated=29/05/2014 20:13:01)
   at Splunk.Client.UnitTests.TestAtomFeed.<CanReadAtomFeed>d__2.MoveNext() in C:\DevWork\Experiments\Splink\splunk-sdk-csharp-pcl-2.2.5\test\unit-tests\TestAtomFeed.cs:line 48

--- Splunk.Client.UnitTests.TestServerMessageCollection.CanConstructServerMessage
Exception
Xunit.Sdk.EqualException: Assert.Equal() Failure
Position: First difference is at position 11
Expected: 2014-05-27 15:28:02Z
Actual:   2014-05-27 23:28:02Z
   at Splunk.Client.UnitTests.TestServerMessageCollection.<CanConstructServerMessage>d__0.MoveNext() in C:\DevWork\Experiments\Splink\splunk-sdk-csharp-pcl-2.2.5\test\unit-tests\TestServerMessageCollection.cs:line 50


--- Splunk.ModularInputs.UnitTests.TestModularInputs.EventWriterReportsOnWrite 
Exception
Xunit.Sdk.TrueException: Assert.True() Failure
   at Splunk.ModularInputs.UnitTests.TestModularInputs.<EventWriterReportsOnWrite>d__17.MoveNext() in C:\DevWork\Experiments\Splink\splunk-sdk-csharp-pcl-2.2.5\test\unit-tests\TestModularInputs.cs:line 568


Empty string value causing error - Read </value> where </text> was expected.

Version 2.2.2

I'm getting a InvalidDataException: Read </value> where <text> was expected. error when the returned data has a empty string value. Ex. Caption="".

I started receiving this error only after upgrading from version 2.1.2.

Stack Trace-
[InvalidDataException: Read </value> where </text> was expected.] Splunk.Client.SearchResultStream.EnsureAwaiterSucceeded() +87 Splunk.Client.<GetEnumerator>d__11.MoveNext() +237..........

Different time formats returned with the same query

Hi,

i ran into a strange behavior when trying different ways of data export from Splunk.
I tried to use jobs to do searches with service.GetSearchResultsAsync and service.ExportSearchPreviewsAsync but it seems that they format time differently.
Here are the examples of what i did.

First the job version.

using (var httpClientHandler = new WebRequestHandler())
{
	httpClientHandler.CachePolicy = new RequestCachePolicy(RequestCacheLevel.NoCacheNoStore);
	httpClientHandler.ReadWriteTimeout = (int)TimeSpan.FromMinutes(10).TotalMilliseconds;

	using (var context = new Context(Scheme.Https, _configuration.SplunkHost, _configuration.SplunkPort, TimeSpan.FromMinutes(5), httpClientHandler))
	{
		using (var service = new Service(context))
		{
			try
			{
				await service.LogOnAsync(_configuration.SplunkUsername, _configuration.SplunkPassword);
			}
			catch (AuthenticationFailureException authException)
			{
				_logger.Error("Splunk server: Login error", authException);
				throw;
			}

			var job = await service.Jobs.CreateAsync(query);

			using (var stream = await job.GetSearchResultsAsync())
			{
				foreach (var item in stream)
				{
					resultFiller(item);
				}
			}                         
		}
	}
}

In this case item will have _time formatted like this

"2017-01-24T11:46:59.997+01:00"

Then if we use export,

using (var httpClientHandler = new WebRequestHandler())
{
	httpClientHandler.CachePolicy = new RequestCachePolicy(RequestCacheLevel.NoCacheNoStore);
	httpClientHandler.ReadWriteTimeout = (int)TimeSpan.FromMinutes(10).TotalMilliseconds;

	using (var context = new Context(Scheme.Https, _configuration.SplunkHost, _configuration.SplunkPort, TimeSpan.FromMinutes(5), httpClientHandler))
	{
		using (var service = new Service(context))
		{
			try
			{
				await service.LogOnAsync(_configuration.SplunkUsername, _configuration.SplunkPassword);
			}
			catch (AuthenticationFailureException authException)
			{
				_logger.Error("Splunk server: Login error", authException);
				throw;
			}

			using (var searchPreviewStream = await service.ExportSearchPreviewsAsync(query))
			{
				foreach (var preview in searchPreviewStream)
				{
					foreach (var item in preview.Results)
					{
						resultFiller(item);
					}
				}
			}
		}
	}
}

we get _time in another format with zone designated with codes and not hours.

"2017-01-24 11:46:59.997 CET"

Is there a concrete reason for this, or is this a bug?

I would expect both of them to have the same default behavior.

SavedSearches.CreateAsync(string, string) Fails with System.ArgumentException : An item with the same key has already been added

Calling the SavedSearches.CreateAsync method with a name and search, creates the search but throws an exception, regardless of the name you send

System.ArgumentException : An item with the same key has already been added.

Sample code:

        using (var service = new Service(
            Scheme.Https,
            server,
            8089,
            new Namespace(user: "nobody", app: "itsi")
            ))
        {
            await service.LogOnAsync(username, password);

            await service.SavedSearches.CreateAsync("test search via api4", "index= test"); //fails regardless of name but saved search _is_ created

            await service.SavedSearches.GetAllAsync();

            foreach(var ss in service.SavedSearches.Where(i=>i.Namespace.App == "itsi"))
            {
                Console.WriteLine($"{ss.Name} {ss.Namespace}");
            }
        }

No suport for System.Collections.Immutable v1.2?

The nuget package for Splunk.Client lists as a dependency:

System.Collections.Immutable (>= 1.1.37 && < 1.2.0)

The latest .Net Core for UWP (5.2.2) comes with System.Collections.Immutable 1.2 therefore Nuget refuses to install Splunk.Client. Will there be an update that bumps the dependency on Systems.Collections.Immutable to 1.2.0 or higher?

How do you use MultiValueParameters?

I can't find any examples or documentation that explains how to configure a MultiValueParameter in a modular input's scheme. I would think there would be some property of the argument class to denote that an argument is multivalue.

Any advice would be appreciated. Thanks!

Splunk Client is missing an implementation of IDataReader to consume from SearchResultStream

As a consumer of your Client API.

I want to load data into SqlServer using Bulk Copy

Therefore I need a IDataReader instead of SearchResultStream.

Please add https://github.com/YulerB/SplunkClientDataReader/blob/main/SearchResultStreamDataReader.cs

So that clients can execute SQL-Server database loading in streaming mode using 1 implementation:

  using(SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(connectionString, SqlBulkCopyOptions.Default)){
    sqlBulkCopy.BatchSize = 5000;
    sqlBulkCopy.EnableStreaming = true;
    sqlBulkCopy.BulkCopyTimeout = 360;
    sqlBulkCopy.DestinationTableName = "dbo.SplunkData";

    using (var context = new Context(Scheme.Https, endPoint.Host, endPoint.Port))
    {
      using (var client = new Service(context))
      {
        await client.LogOnAsync(credential.UserName, credential.Password).ConfigureAwait(false);

        using(var results = await client.ExportSearchResultsAsync(search, searchExportArgs).ConfigureAwait(false))
        {
          using(var reader = new SearchResultStreamDataReader(results))
          {
            await sqlBlockCopy.WriteToServerAsync(reader).ConfigureAwait(false);
          }
        }
      }
    }
  }

Hangs when enumerating stream

Version: 2.2.3
Platform: ASP.NET MVC 5
Framework: .Net 4.5 Visual Studio 2015
Splunk: 6.3.3

After performing a one shot search that returns no results (e.g. <results />) and then enumerating over the SearchResultStream the application hangs. No exception is thrown.

LogOnAsync("hostname", "password") is returning null response

Hi All,

I am using Spluck C# SDK 2.2.5 with Visual Studio 2017. Below is the code,

Service service = new Service(Scheme.Https, "localhost", 8089);
await service.LogOnAsync("admin", "adminone");
var searchResults = await service.SearchOneShotAsync("search index=_internal | head 10");

I am getting Null response for await service.LogOnAsync("username", "password") method.

The Splunk REST API is working fine. I verified it by running it through curl command,
curl -k https://localhost:8089/services/auth/login -d username=admin -d password=adminone

I am able to get sessionKey using above curl command, however I am getting null response for LogOnAsync method.

Any suggestion on what could be missing here and how to fix it?

Thanks in advance.

Regards,
Sai

Splunk.Client is not the signed assembly

Splunk.Client is not the signed assembly.
So this cannot be used in other signed assemblies.
This problem means there is a limit to where this library can be used.
Recommend distributing a Nuget containing a signed assembly.

Q: Xamarin/Mono support

Tried to build the project using Xamarin Studio, which did not work. Is it a goal that the SDK can be build on Mono as well?

ExportSearchResultsAsync returns InvalidDataException when no data

After call ExportSearchResultsAsync and this search not found data, I try to get a list of results with
var results = searchResultStream.AsEnumerable().ToList()

This error is raised:
System.IO.InvalidDataException: Read where or was expected.

I am using package 2.2.5

How to deal with "The request was aborted: Could not create SSL/TLS secure channel" error?

I am trying to run search example

static void Main(string[] args)
        {
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
            using (var service = new Service(new Uri("https://splunk.tsi.lan")))
            {
                Run(service).Wait();
            }


            Console.Write("Press return to exit: ");
            Console.ReadLine();
        }

        static async Task Run(Service service)
        {
            await service.LogOnAsync(<user>, <password>); // error happen here

But I keep getting exception:

The request was aborted: Could not create SSL/TLS secure channel

How do I deal with it? Since sdk targets portable library, I can't use this workaround:

var handler = new WebRequestHandler();
handler.ServerCertificateValidationCallback = delegate { return true; };

Full stack trace:

System.AggregateException was unhandled
  HResult=-2146233088
  Message=One or more errors occurred.
  Source=mscorlib
  StackTrace:
       at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
       at System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout, CancellationToken cancellationToken)
       at System.Threading.Tasks.Task.Wait()
       at Splunk.Client.Examples.Program.Main(String[] args) in D:\Work\splunk-sdk-csharp-pcl-master\examples\normal-search\Program.cs:line 36
       at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException: 
       HResult=-2146233088
       Message=An error occurred while sending the request.
       Source=mscorlib
       StackTrace:
            at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
            at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
            at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1.ConfiguredTaskAwaiter.GetResult()
            at Splunk.Client.Context.<SendAsync>d__37.MoveNext() in D:\Work\splunk-sdk-csharp-pcl-master\src\Splunk.Client\Splunk\Client\Context.cs:line 538
         --- End of stack trace from previous location where exception was thrown ---
            at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
            at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
            at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
            at Splunk.Client.Context.<GetResponseAsync>d__36.MoveNext() in D:\Work\splunk-sdk-csharp-pcl-master\src\Splunk.Client\Splunk\Client\Context.cs:line 504
         --- End of stack trace from previous location where exception was thrown ---
            at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
            at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
            at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1.ConfiguredTaskAwaiter.GetResult()
            at Splunk.Client.Context.<PostAsync>d__27.MoveNext() in D:\Work\splunk-sdk-csharp-pcl-master\src\Splunk.Client\Splunk\Client\Context.cs:line 382
         --- End of stack trace from previous location where exception was thrown ---
            at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
            at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
            at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1.ConfiguredTaskAwaiter.GetResult()
            at Splunk.Client.Context.<PostAsync>d__26.MoveNext() in D:\Work\splunk-sdk-csharp-pcl-master\src\Splunk.Client\Splunk\Client\Context.cs:line 357
         --- End of stack trace from previous location where exception was thrown ---
            at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
            at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
            at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1.ConfiguredTaskAwaiter.GetResult()
            at Splunk.Client.Service.<LogOnAsync>d__35.MoveNext() in D:\Work\splunk-sdk-csharp-pcl-master\src\Splunk.Client\Splunk\Client\Service.cs:line 283
         --- End of stack trace from previous location where exception was thrown ---
            at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
            at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
            at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
            at Splunk.Client.Examples.Program.<Run>d__1.MoveNext() in D:\Work\splunk-sdk-csharp-pcl-master\examples\normal-search\Program.cs:line 46
       InnerException: 
            HResult=-2146233079
            Message=The request was aborted: Could not create SSL/TLS secure channel.
            Source=System
            StackTrace:
                 at System.Net.HttpWebRequest.EndGetRequestStream(IAsyncResult asyncResult, TransportContext& context)
                 at System.Net.Http.HttpClientHandler.GetRequestStreamCallback(IAsyncResult ar)
            InnerException: 

InvalidDataException while retrieving a list of saved searches for the specific app

I'm experiencing a problem using SDK v2.2.5 while retrieving a list of saved searches for the specific app. I've gone through your code and seems like this is happening right here. A problematic name is different for different apps (for example: "action.customsearchbuilder.enabled", "action.slack.param.channel").

It is hard to say something about server version right now, but it should be quite old. But seems like on SDK v1.x everything was fine.

I'm not sure that this is your problem, but could you give any advice or workaround for such case?

Stack trace is always the same:
at Splunk.Client.AtomEntry.<ParseDictionaryAsync>d__32.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.ConfiguredTaskAwaitable1.ConfiguredTaskAwaiter.GetResult()
at Splunk.Client.AtomEntry.d__34.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.ConfiguredTaskAwaitable1.ConfiguredTaskAwaiter.GetResult() at Splunk.Client.AtomEntry.<ReadXmlAsync>d__29.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Splunk.Client.AtomFeed.<ReadXmlAsync>d__40.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Splunk.Client.BaseEntity1.d__25.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.ConfiguredTaskAwaitable1.ConfiguredTaskAwaiter.GetResult() at Splunk.Client.EntityCollection2.d__12.MoveNext()`

another issue in the Atomic reader

this Entry
name ".execute_input.flush_prestats" string
causes a failure in the normalise dictionary name method...

This happens whenever the Tstats command is used in a returned search

Have fix:
will open a pull request soon.

Not working as Expected with MVC Project

Not working with ASP.NET MVC project, you could reproduce this issue by your self.
You guys using ConfigureAwaiter(false); in most of async methods but I think you lost in some cases, I'm not sure where it is. It's hanging when SendAsync called...

I used your PCL library in here: https://github.com/efaruk/playground/tree/master/log4net.Appender.SplunkAppenders. But I changed back to old sdk now. You can pick from history and try to reproduce issue...

Regards...
EFP

JobCollection CreateAsync mode

Version: 2.2.3
Does not look like mode is being used in the CreateAsync method on line 172 in JobCollection.cs. I did not see when I set the value to blocking and observed the request with Fiddler.

C# SDK, XmlReaderExtensions throws exception when reading fields that use tags

When getting started with the Splunk C# SDK I ran into an issue where the following exception would be thrown for certain search queries:

"Read charater data where or was expected"

Upon further investigation I determined that the issue was occurring when reading fields that made use of tags:

xboxvideoXBV

When removing the tag from this field, search results were parsed without exception.

Is this a known issue with the C# SDK? Right now I’ve worked around this by removing tags from our fields, but that’s obviously not a preferable solution as tags are quite handy for writing more complicated queries.

Thanks,
-travis

How to deal with non default base path ?

Security have blocked the api port and made it available on a different url but i dont see any options on how to set that .. The path from the Uri overload seems to be ignored.

I dont see this documented anywhere... though i can hit the url with curl / raw http. Was thinking a custom MessageHandler but that seems pretty ugly..

Stats Query in SDK - Task Cancelled error

Hi Team,

I am trying to run stats splunk query using c# SDK and getting task cancelled error. Kindly help me on this. I have tried with/without sleep too.

await service.LogOnAsync("USERNAME", "PASSWORD");
                Job job = await service.Jobs.CreateAsync("search index=windows_inetpub cs_uri_stem=\"*/search\" | stats count", 10);
                SearchResultStream stream;

                while (!job.IsDone)
                {
                    Thread.Sleep(1000);
                }

                using (stream = await job.GetSearchResultsAsync(1))
                {
                    try
                    {
                        foreach (SearchResult result in stream)
                        {
                            Console.WriteLine(string.Format("{0:D8}: {1}", stream.ReadCount, result));
                        }

                        Console.WriteLine("End of search results");
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(string.Format("SearchResults error: {0}", e.Message));
                    }
                }

Compile to .net Standard 2.0

I want to use this Nuget from a .NET Core 2.0 application.
Do you have any plans to build the code to .NET Standard 2.0?

Issue in Search with Push model

In Search with Push Model, when you subscribe to the stream, the onNext is never called unless you iterate over all the result.

stream.Subscribe(new Observer<SearchResult>(

That means if you comment out lines 56-59, the observable stream will never be executed

foreach (SearchResult result in stream)
{
Console.WriteLine(string.Format("{0:D8}: {1}", stream.ReadCount, result));
}

Review snippets for using the SDK with RX.

We are developing a set of Visual Studio snippets for use with the SDK. One of things we'd like to have is snippets for using the SDK with RX.

Here is a link to a commit in my fork with the snippets we were thinking of. Please take a look and give us feedback. You can use the inline commenting feature.

Memory leak with Expando object

Hi,

We are using Splunk.Client to export data from our Splunk instalation.
At this moment we are querying our instance every minute for the previous minute of data. We are running a "Normal" search as demonstrated in you documentation.

It looks like we are running into a memory leak when doing this.

Our result set contains 12 columns and between 20000 - 50000 records per query.

Here is the code we run:

try
{
    using (var service = new Service(Scheme.Https, _configuration.SplunkHost, _configuration.SplunkPort))
    {
        try
        {
            await service.LogOnAsync(_configuration.SplunkUsername, _configuration.SplunkPassword);
        }
        catch (AuthenticationFailureException authException)
        {
            _logger.Error("Splunk server: Login error", authException);
            throw;
        }

        var job = await service.Jobs.CreateAsync(query, mode: ExecutionMode.Normal);

        using (var stream = await job.GetSearchResultsAsync())
        {
            foreach (var result in stream)
            {
                var row = resultTransformer(result);
                tableResult.Rows.Add(row);
            }
        }

        return tableResult;
    }
}
catch (Exception ex)
{
    _logger.Error("Splunk server: query management error", ex);
    throw;
}

This code is running in a loop. We are seeing a big number of objects being created, and not collected by GC (even when forcing on all generations).

While investigating we ran into this .NET bug report

The pattern used in your SearchResult class looks to be exactly what that bug report is explaining.

Do you have any insight that might help us?
Maybe an alternative way to do the query that does not use SearchResult, but gets raw string data (in CSV or some other format)?

Failure running unit tests: "ProcessInvocation86.exe - Precondition failed"

I am getting the following failure while running the unit tests on the develop branch. This is happening on multiple computers, and I am running into the issue while using TestDriven.net and the xUnit.net test runners. Being that these are unit tests, I expect that the unit tests would not be connecting to a Splunk server.

Exception Image

.NET CORE 2.0 Compatability

It would be nice to have a .NET CORE 2.0 NuGet since new development in Visual Studio will be utilizing these standards.

ModularInput: Events in the EventWriter queue are lost when Splunk shuts down.

I ran in to this issue while working on a modular input that processes a large amount of data and subsequently runs for an extended period of time. If Splunkd shuts down while a modular input is running and events are sitting in the EventWriter queue, these events are lost and never logged to Splunk. Additionally, the events are sent to the IProgress< EventWrittenProgressReport > as if they were successfully written. This makes it impossible to create a checkpoint for the file being processed because there's no way to tell how many events actually made it to Splunk.

Steps to reproduce:

  1. Create a modular input that continuously logs events.
  2. Run the modular input using Splunk and let the EventWriter queue fill up with at least 100,000+ events.
  3. Stop the Splunk windows service while the modular input is running.

At this point Splunk will send a ctrl+break signal to the modular input. I have the modular input trap this signal and stop writing events. The EventWriter continues writing events to stdout and sending the Events to the progress reporter, but none of these events reach Splunkd. In fact, events written to stdout for up to 500ms (the amount of time varies from run to run) before the ctrl+break is received are lost as well.

Exception Value does not fall within the expected range with Splunk version 8.1.4

Need help from the community. We are using Splunk Client for csharp, Splunk client version 2.2.9.0
on .net framework 4.5
After the Splunk version was upgraded to 8.1.4 we are getting the following exception.
Exception: “Value does not fall within the expected range.”
The code is as follows, the same code gets the search results for the same dataset for data prior to the Splunk version upgrade. I can provide stack trace if needed. Here is the code snippet

using Splunk.Client;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Net;
using System.Threading.Tasks;

namespace Integration_Service
{
    class SplunkQueryManager
    {
        public static async Task<SplunkQueryManager.SplunkSearchResult> Get(String query, StreamWriter logfile, string server, string[] pwd)
        {

            logfile.WriteLine("Beginning Splunk Search at: " + DateTime.Now.ToString());

            string job_id = "none";

            try
            {
                SplunkSearchResult SearchInfo = new SplunkSearchResult();

                using (var service = new Service(new Uri(server)))
                {
                    //Login to Splunk
                    ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

                    await service.LogOnAsync(pwd[0], pwd[1]);


                    //create job, set searchstream variable, and collect job ID
                    Job job = await service.Jobs.CreateAsync(query);
                    await job.SetTtlAsync(60);
                    SearchResultStream stream;
                    job_id = job.Sid;
                    SearchInfo.SplunkSearchID = job_id;


// The next line caused the exception
                    using (stream = await job.GetSearchResultsAsync())
                   
                    {
                        //count number of results for future reference
                        SearchInfo.EventCount = job.EventCount;

                        //log search ID


                        logfile.WriteLine("Getting events from Splunk Search: " + SearchInfo.SplunkSearchID);

                        SearchInfo.Data = GetDataFromStream(stream);

                        //log success
                        logfile.WriteLine("Splunk Search: " + SearchInfo.SplunkSearchID + " returned " + SearchInfo.EventCount + " events at: " + DateTime.Now.ToString());

                        await job.RemoveAsync();

                        SearchInfo.error = "no";
                        return SearchInfo;
                    }
                }
            }
            catch (Exception e)
            {
                //log errors
                logfile.WriteLine("Splunk search failed at: " + DateTime.Now.ToString());
                logfile.WriteLine("SearchResults error: \r\n" + e);
                logfile.WriteLine("Results not returned for Splunk Search: " + job_id + " at: " + DateTime.Now.ToString());

                SplunkSearchResult searchError;
                searchError.Data = new List<Dictionary<string, string>>();
                searchError.SplunkSearchID = job_id;
                searchError.EventCount = 0;
                searchError.error = "yes";

                System.Threading.Thread.Sleep(30000);

                return searchError;
            }
        }

Long argument value causes UriFormatException Exception

Uri.EscapeDataString fails if the string is longer than 32k characters (depending on framework?)

This causes an exception to be thrown in Splunk.Client.Context.CreateStringContent while the API can accept the long value.

Fix by splitting the string and looping?

        /// <summary>
        /// deal with long searches
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        private static string EscapeDataString(string value)
        {
            int limit = 20000;

            StringBuilder sb = new StringBuilder();
            int loops = value.Length / limit;

            for (int i = 0; i <= loops; i++)
            {
                if (i < loops)
                {
                    sb.Append(Uri.EscapeDataString(value.Substring(limit * i, limit)));
                }
                else
                {
                    sb.Append(Uri.EscapeDataString(value.Substring(limit * i)));
                }
            }
            return sb.ToString();
        }

https://docs.microsoft.com/en-us/dotnet/api/system.uri.escapedatastring?view=netframework-4.8

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.