Commit 5214df34 authored by Marc Gravell's avatar Marc Gravell

Initial push

parent 01490da8
.hg
bin
obj
*.suo
*.user
*.nupkg
packages/NuGet.CommandLine.*
*.sln.docstates
_ReSharper.*
Mono/
*.sln.ide
*.rdb
*.orig
\ No newline at end of file
syntax: glob
*/bin/
*/obj/
Tests/bin/
Tests/obj/
*.suo
Async/bin/
Async/obj/
*.user
*.nupkg
packages/NuGet.CommandLine.*
*.sln.docstates
_ReSharper.*
Mono/
*.sln.ide
*.rdb
*.orig
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="NuGet.CommandLine" version="2.8.0" />
<package id="Redis-64" version="2.6.12.1" />
</packages>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
</configuration>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{6756F911-BD09-4226-B597-67871DEB8ED5}</ProjectGuid>
<OutputType>WinExe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>ConnectionWatcher</RootNamespace>
<AssemblyName>ConnectionWatcher</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<UseVSHostingProcess>false</UseVSHostingProcess>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Verbose\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<UseVSHostingProcess>false</UseVSHostingProcess>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Verbose|AnyCPU'">
<DebugSymbols>true</DebugSymbols>
<OutputPath>bin\Verbose\</OutputPath>
<DefineConstants>TRACE;DEBUG;VERBOSE</DefineConstants>
<DebugType>full</DebugType>
<PlatformTarget>AnyCPU</PlatformTarget>
<UseVSHostingProcess>false</UseVSHostingProcess>
<ErrorReport>prompt</ErrorReport>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
<Prefer32Bit>true</Prefer32Bit>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Log Output|AnyCPU'">
<DebugSymbols>true</DebugSymbols>
<OutputPath>bin\Log Output\</OutputPath>
<DefineConstants>TRACE;DEBUG;LOGOUTPUT</DefineConstants>
<DebugType>full</DebugType>
<PlatformTarget>AnyCPU</PlatformTarget>
<UseVSHostingProcess>false</UseVSHostingProcess>
<ErrorReport>prompt</ErrorReport>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
<Prefer32Bit>true</Prefer32Bit>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Deployment" />
<Reference Include="System.Drawing" />
<Reference Include="System.Windows.Forms" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Form1.cs">
<SubType>Form</SubType>
</Compile>
<Compile Include="Form1.Designer.cs">
<DependentUpon>Form1.cs</DependentUpon>
</Compile>
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<EmbeddedResource Include="Form1.resx">
<DependentUpon>Form1.cs</DependentUpon>
</EmbeddedResource>
<EmbeddedResource Include="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
<SubType>Designer</SubType>
</EmbeddedResource>
<Compile Include="Properties\Resources.Designer.cs">
<AutoGen>True</AutoGen>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
<None Include="Properties\Settings.settings">
<Generator>SettingsSingleFileGenerator</Generator>
<LastGenOutput>Settings.Designer.cs</LastGenOutput>
</None>
<Compile Include="Properties\Settings.Designer.cs">
<AutoGen>True</AutoGen>
<DependentUpon>Settings.settings</DependentUpon>
<DesignTimeSharedInput>True</DesignTimeSharedInput>
</Compile>
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\StackExchange.Redis\StackExchange.Redis.csproj">
<Project>{7cec07f2-8c03-4c42-b048-738b215824c1}</Project>
<Name>StackExchange.Redis</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>
\ No newline at end of file
This diff is collapsed.
This diff is collapsed.
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<metadata name="label1.GenerateMember" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>False</value>
</metadata>
<metadata name="label2.GenerateMember" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>False</value>
</metadata>
<metadata name="label3.GenerateMember" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>False</value>
</metadata>
<metadata name="label4.GenerateMember" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>False</value>
</metadata>
<metadata name="label5.GenerateMember" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>False</value>
</metadata>
<metadata name="ticker.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</metadata>
</root>
\ No newline at end of file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ConnectionWatcher
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("ConnectionWatcher")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ConnectionWatcher")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("f494c35a-e665-4f46-9906-dbb873e00b51")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.34011
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace ConnectionWatcher.Properties
{
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources
{
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources()
{
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager
{
get
{
if ((resourceMan == null))
{
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("ConnectionWatcher.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture
{
get
{
return resourceCulture;
}
set
{
resourceCulture = value;
}
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>
\ No newline at end of file
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.34011
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace ConnectionWatcher.Properties
{
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
{
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default
{
get
{
return defaultInstance;
}
}
}
}
<?xml version='1.0' encoding='utf-8'?>
<SettingsFile xmlns="http://schemas.microsoft.com/VisualStudio/2004/01/settings" CurrentProfile="(Default)">
<Profiles>
<Profile Name="(Default)" />
</Profiles>
<Settings />
</SettingsFile>
This diff is collapsed.
This diff is collapsed.
using System.Net;
using NUnit.Framework;
namespace StackExchange.Redis.Tests
{
[TestFixture]
public class Commands
{
[Test]
public void Basic()
{
var config = ConfigurationOptions.Parse(".,$PING=p");
Assert.AreEqual(1, config.EndPoints.Count);
Assert.Contains(new DnsEndPoint(".",6379), config.EndPoints);
var map = config.CommandMap;
Assert.AreEqual("$PING=p", map.ToString());
Assert.AreEqual(".:6379,$PING=p", config.ToString());
}
}
}
This diff is collapsed.
using NUnit.Framework;
namespace StackExchange.Redis.Tests
{
[TestFixture]
public class Databases : TestBase
{
[Test]
public void CountKeys()
{
using (var muxer = Create(allowAdmin:true))
{
var server = GetServer(muxer);
server.FlushDatabase(0, CommandFlags.FireAndForget);
server.FlushDatabase(1, CommandFlags.FireAndForget);
}
using (var muxer = Create())
{
RedisKey key = Me();
var db0 = muxer.GetDatabase(0);
var db1 = muxer.GetDatabase(1);
db0.StringSet("abc", "def", flags: CommandFlags.FireAndForget);
db0.StringIncrement(key, flags: CommandFlags.FireAndForget);
db1.StringIncrement(key, flags: CommandFlags.FireAndForget);
var server = GetServer(muxer);
var c0 = server.DatabaseSizeAsync(0);
var c1 = server.DatabaseSizeAsync(1);
Assert.AreEqual(2, muxer.Wait(c0));
Assert.AreEqual(1, muxer.Wait(c1));
}
}
[Test]
public void MultiDatabases()
{
using (var muxer = Create())
{
RedisKey key = Me();
var db0 = muxer.GetDatabase(0);
var db1 = muxer.GetDatabase(1);
var db2 = muxer.GetDatabase(2);
db0.Ping();
db0.KeyDelete(key, CommandFlags.FireAndForget);
db1.KeyDelete(key, CommandFlags.FireAndForget);
db2.KeyDelete(key, CommandFlags.FireAndForget);
muxer.WaitAll(
db0.StringSetAsync(key, "a"),
db1.StringSetAsync(key, "b"),
db2.StringSetAsync(key, "c")
);
var a = db0.StringGetAsync(key);
var b = db1.StringGetAsync(key);
var c = db2.StringGetAsync(key);
muxer.WaitAll(a, b, c);
Assert.AreEqual("a", (string)muxer.Wait(a), "db:0");
Assert.AreEqual("b", (string)muxer.Wait(b), "db:1");
Assert.AreEqual("c", (string)muxer.Wait(c), "db:2");
}
}
}
}
using System;
using NUnit.Framework;
namespace StackExchange.Redis.Tests
{
[TestFixture]
public class Expiry : TestBase
{
static string[] GetMap(bool disablePTimes)
{
if(disablePTimes)
{
return new[] { "pexpire", "pexpireat", "pttl" };
}
return null;
}
[Test]
[TestCase(true)]
[TestCase(false)]
public void TestBasicExpiryTimeSpan(bool disablePTimes)
{
using(var muxer = Create(disabledCommands: GetMap(disablePTimes)))
{
RedisKey key = Me();
var conn = muxer.GetDatabase();
conn.KeyDelete(key, CommandFlags.FireAndForget);
conn.StringSet(key, "new value", flags: CommandFlags.FireAndForget);
var a = conn.KeyTimeToLiveAsync(key);
conn.KeyExpire(key, TimeSpan.FromHours(1), CommandFlags.FireAndForget);
var b = conn.KeyTimeToLiveAsync(key);
conn.KeyExpire(key, (TimeSpan?)null, CommandFlags.FireAndForget);
var c = conn.KeyTimeToLiveAsync(key);
conn.KeyExpire(key, TimeSpan.FromHours(1.5), CommandFlags.FireAndForget);
var d = conn.KeyTimeToLiveAsync(key);
conn.KeyExpire(key, TimeSpan.MaxValue, CommandFlags.FireAndForget);
var e = conn.KeyTimeToLiveAsync(key);
Assert.IsNull(muxer.Wait(a));
var time = muxer.Wait(b);
Assert.IsNotNull(time);
Assert.IsTrue(time > TimeSpan.FromMinutes(59.9) && time <= TimeSpan.FromMinutes(60));
Assert.IsNull(muxer.Wait(c));
time = muxer.Wait(d);
Assert.IsNotNull(time);
Assert.IsTrue(time > TimeSpan.FromMinutes(89.9) && time <= TimeSpan.FromMinutes(90));
Assert.IsNull(muxer.Wait(e));
}
}
[Test]
[TestCase(true, true)]
[TestCase(false, true)]
[TestCase(true, false)]
[TestCase(false, false)]
public void TestBasicExpiryDateTime(bool disablePTimes, bool utc)
{
using (var muxer = Create(disabledCommands: GetMap(disablePTimes)))
{
RedisKey key = Me();
var conn = muxer.GetDatabase();
conn.KeyDelete(key, CommandFlags.FireAndForget);
var now = utc ? DateTime.UtcNow : DateTime.Now;
conn.StringSet(key, "new value", flags: CommandFlags.FireAndForget);
var a = conn.KeyTimeToLiveAsync(key);
conn.KeyExpire(key, now.AddHours(1), CommandFlags.FireAndForget);
var b = conn.KeyTimeToLiveAsync(key);
conn.KeyExpire(key, (DateTime?)null, CommandFlags.FireAndForget);
var c = conn.KeyTimeToLiveAsync(key);
conn.KeyExpire(key, now.AddHours(1.5), CommandFlags.FireAndForget);
var d = conn.KeyTimeToLiveAsync(key);
conn.KeyExpire(key, DateTime.MaxValue, CommandFlags.FireAndForget);
var e = conn.KeyTimeToLiveAsync(key);
Assert.IsNull(muxer.Wait(a));
var time = muxer.Wait(b);
Assert.IsNotNull(time);
Console.WriteLine(time);
Assert.IsTrue(time > TimeSpan.FromMinutes(59.9) && time <= TimeSpan.FromMinutes(60));
Assert.IsNull(muxer.Wait(c));
time = muxer.Wait(d);
Assert.IsNotNull(time);
Assert.IsTrue(time > TimeSpan.FromMinutes(89.9) && time <= TimeSpan.FromMinutes(90));
Assert.IsNull(muxer.Wait(e));
}
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NUnit.Framework;
namespace StackExchange.Redis.Tests
{
[TestFixture]
public class FloatingPoint : TestBase
{
static bool Within(double x, double y, double delta)
{
return Math.Abs(x - y) <= delta;
}
[Test]
public void IncrDecrFloatingPoint()
{
using (var conn = Create())
{
var db = conn.GetDatabase();
RedisKey key = Me();
db.KeyDelete(key, CommandFlags.FireAndForget);
double[] incr =
{
12.134,
-14561.0000002,
125.3421,
-2.49892498
}, decr =
{
99.312,
12,
-35
};
double sum = 0;
foreach (var value in incr)
{
db.StringIncrement(key, value, CommandFlags.FireAndForget);
sum += value;
}
foreach (var value in decr)
{
db.StringDecrement(key, value, CommandFlags.FireAndForget);
sum -= value;
}
var val = (double)db.StringGet(key);
Assert.IsTrue(Within(sum, val, 0.0001));
}
}
[Test]
public async void IncrDecrFloatingPointAsync()
{
using (var conn = Create())
{
var db = conn.GetDatabase();
RedisKey key = Me();
db.KeyDelete(key, CommandFlags.FireAndForget);
double[] incr =
{
12.134,
-14561.0000002,
125.3421,
-2.49892498
}, decr =
{
99.312,
12,
-35
};
double sum = 0;
foreach (var value in incr)
{
await db.StringIncrementAsync(key, value);
sum += value;
}
foreach (var value in decr)
{
await db.StringDecrementAsync(key, value);
sum -= value;
}
var val = (double)await db.StringGetAsync(key);
Assert.IsTrue(Within(sum, val, 0.0001));
}
}
[Test]
public void HashIncrDecrFloatingPoint()
{
using (var conn = Create())
{
var db = conn.GetDatabase();
RedisKey key = Me();
RedisValue field = "foo";
db.KeyDelete(key, CommandFlags.FireAndForget);
double[] incr =
{
12.134,
-14561.0000002,
125.3421,
-2.49892498
}, decr =
{
99.312,
12,
-35
};
double sum = 0;
foreach (var value in incr)
{
db.HashIncrement(key, field, value, CommandFlags.FireAndForget);
sum += value;
}
foreach (var value in decr)
{
db.HashDecrement(key, field, value, CommandFlags.FireAndForget);
sum -= value;
}
var val = (double)db.HashGet(key, field);
Assert.IsTrue(Within(sum, val, 0.0001));
}
}
[Test]
public async void HashIncrDecrFloatingPointAsync()
{
using (var conn = Create())
{
var db = conn.GetDatabase();
RedisKey key = Me();
RedisValue field = "bar";
db.KeyDelete(key, CommandFlags.FireAndForget);
double[] incr =
{
12.134,
-14561.0000002,
125.3421,
-2.49892498
}, decr =
{
99.312,
12,
-35
};
double sum = 0;
foreach (var value in incr)
{
await db.HashIncrementAsync(key, field, value);
sum += value;
}
foreach (var value in decr)
{
await db.HashDecrementAsync(key, field, value);
sum -= value;
}
var val = (double)await db.HashGetAsync(key, field);
Assert.IsTrue(Within(sum, val, 0.0001));
}
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NUnit.Framework;
namespace StackExchange.Redis.Tests
{
[TestFixture]
public class Keys : TestBase
{
[Test]
public void TestScan()
{
using(var muxer = Create(allowAdmin: true))
{
const int Database = 4;
var db = muxer.GetDatabase(Database);
GetServer(muxer).FlushDatabase(flags: CommandFlags.FireAndForget);
const int Count = 1000;
for (int i = 0; i < Count; i++)
db.StringSet("x" + i, "y" + i, flags: CommandFlags.FireAndForget);
var count = GetServer(muxer).Keys(Database).Count();
Assert.AreEqual(Count, count);
}
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NUnit.Framework;
namespace StackExchange.Redis.Tests
{
[TestFixture]
public class KeysAndValues
{
[Test]
public void TestValues()
{
RedisValue @default = default(RedisValue);
CheckNull(@default);
RedisValue nullString = (string)null;
CheckNull(nullString);
RedisValue nullBlob = (byte[])null;
CheckNull(nullBlob);
RedisValue emptyString = "";
CheckNotNull(emptyString);
RedisValue emptyBlob = new byte[0];
CheckNotNull(emptyBlob);
RedisValue a0 = new string('a', 1);
CheckNotNull(a0);
RedisValue a1 = new string('a', 1);
CheckNotNull(a1);
RedisValue b0 = new [] { (byte)'b' };
CheckNotNull(b0);
RedisValue b1 = new [] { (byte)'b' };
CheckNotNull(b1);
RedisValue i4 = 1;
CheckNotNull(i4);
RedisValue i8 = 1L;
CheckNotNull(i8);
CheckSame(a0, a0);
CheckSame(a1, a1);
CheckSame(a0, a1);
CheckSame(b0, b0);
CheckSame(b1, b1);
CheckSame(b0, b1);
CheckSame(i4, i4);
CheckSame(i8, i8);
CheckSame(i4, i8);
}
private void CheckSame(RedisValue x, RedisValue y)
{
Assert.IsTrue(Equals(x, y));
Assert.IsTrue(x.Equals(y));
Assert.IsTrue(y.Equals(x));
Assert.IsTrue(x.GetHashCode() == y.GetHashCode());
}
private void CheckNotSame(RedisValue x, RedisValue y)
{
Assert.IsFalse(Equals(x, y));
Assert.IsFalse(x.Equals(y));
Assert.IsFalse(y.Equals(x));
Assert.IsFalse(x.GetHashCode() == y.GetHashCode()); // well, very unlikely
}
private void CheckNotNull(RedisValue value)
{
Assert.IsFalse(value.IsNull);
Assert.IsNotNull((byte[])value);
Assert.IsNotNull((string)value);
Assert.AreNotEqual(-1, value.GetHashCode());
Assert.IsNotNull((string)value);
Assert.IsNotNull((byte[])value);
CheckSame(value, value);
CheckNotSame(value, default(RedisValue));
CheckNotSame(value, (string)null);
CheckNotSame(value, (byte[])null);
}
private void CheckNull(RedisValue value)
{
Assert.IsTrue(value.IsNull);
Assert.IsTrue(value.IsNullOrEmpty);
Assert.IsFalse(value.IsInteger);
Assert.AreEqual(-1, value.GetHashCode());
Assert.IsNull((string)value);
Assert.IsNull((byte[])value);
Assert.AreEqual(0, (int)value);
Assert.AreEqual(0L, (long)value);
CheckSame(value, value);
CheckSame(value, default(RedisValue));
CheckSame(value, (string)null);
CheckSame(value, (byte[])null);
}
}
}
using System;
using System.Threading;
using System.Threading.Tasks;
using NUnit.Framework;
namespace StackExchange.Redis.Tests
{
[TestFixture]
public class Locking : TestBase
{
[Test]
public void AggressiveParallel()
{
int count = 2;
int errorCount = 0;
ManualResetEvent evt = new ManualResetEvent(false);
using (var c1 = Create())
using (var c2 = Create())
{
WaitCallback cb = obj =>
{
var conn = (IDatabase)obj;
conn.Multiplexer.ErrorMessage += delegate { Interlocked.Increment(ref errorCount); };
for (int i = 0; i < 1000; i++)
{
conn.LockTakeAsync("abc", "def", TimeSpan.FromSeconds(5));
}
conn.Ping();
if (Interlocked.Decrement(ref count) == 0) evt.Set();
};
const int db = 2;
ThreadPool.QueueUserWorkItem(cb, c1.GetDatabase(db));
ThreadPool.QueueUserWorkItem(cb, c2.GetDatabase(db));
evt.WaitOne(8000);
}
Assert.AreEqual(0, Interlocked.CompareExchange(ref errorCount, 0, 0));
}
protected override string GetConfiguration()
{
return PrimaryServer + ":" + PrimaryPortString;
}
[Test]
public void TestOpCountByVersionLocal_UpLevel()
{
using (var conn = Create())
{
TestLockOpCountByVersion(conn, 1, false);
TestLockOpCountByVersion(conn, 1, true);
//TestManualLockOpCountByVersion(conn, 5, false);
//TestManualLockOpCountByVersion(conn, 3, true);
}
}
//[Test]
//public void TestOpCountByVersionLocal_DownLevel()
//{
// using (var conn = Config.GetUnsecuredConnection(open: false))
// {
// conn.SetServerVersion(new Version(2, 6, 0), ServerType.Master);
// TestLockOpCountByVersion(conn, 5, false);
// TestLockOpCountByVersion(conn, 3, true);
// //TestManualLockOpCountByVersion(conn, 5, false);
// //TestManualLockOpCountByVersion(conn, 3, true);
// }
//}
//[Test]
//public void TestOpCountByVersionRemote()
//{
// using (var conn = Config.GetRemoteConnection(open: false))
// {
// TestLockOpCountByVersion(conn, 1, false);
// TestLockOpCountByVersion(conn, 1, true);
// //TestManualLockOpCountByVersion(conn, 1, false);
// //TestManualLockOpCountByVersion(conn, 1, true);
// }
//}
public void TestLockOpCountByVersion(ConnectionMultiplexer conn, int expected, bool existFirst)
{
const int DB = 0, LockDuration = 30;
RedisKey Key = Me();
var db = conn.GetDatabase(DB);
db.KeyDelete(Key);
RedisValue newVal = "us:" + Guid.NewGuid().ToString();
RedisValue expectedVal = newVal;
if (existFirst)
{
expectedVal = "other:" + Guid.NewGuid().ToString();
db.StringSet(Key, expectedVal, TimeSpan.FromSeconds(LockDuration));
}
long countBefore = GetServer(conn).GetCounters().Interactive.OperationCount;
var taken = db.LockTake(Key, newVal, TimeSpan.FromSeconds(LockDuration));
long countAfter = GetServer(conn).GetCounters().Interactive.OperationCount;
var valAfter = db.StringGet(Key);
Assert.AreEqual(!existFirst, taken, "lock taken");
Assert.AreEqual(expectedVal, valAfter, "taker");
Assert.AreEqual(expected, countAfter - countBefore, "expected ops");
// note we get a ping from GetCounters
}
[Test]
public void TakeLockAndExtend()
{
using (var conn = Create())
{
RedisValue right = Guid.NewGuid().ToString(),
wrong = Guid.NewGuid().ToString();
const int DB = 7;
RedisKey Key = "lock-key";
var db = conn.GetDatabase(DB);
db.KeyDelete(Key);
var t1 = db.LockTakeAsync(Key, right, TimeSpan.FromSeconds(20));
var t1b = db.LockTakeAsync(Key, wrong, TimeSpan.FromSeconds(10));
var t2 = db.LockQueryAsync(Key);
var t3 = db.LockReleaseAsync(Key, wrong);
var t4 = db.LockQueryAsync(Key);
var t5 = db.LockExtendAsync(Key, wrong, TimeSpan.FromSeconds(60));
var t6 = db.LockQueryAsync(Key);
var t7 = db.KeyTimeToLiveAsync(Key);
var t8 = db.LockExtendAsync(Key, right, TimeSpan.FromSeconds(60));
var t9 = db.LockQueryAsync(Key);
var t10 = db.KeyTimeToLiveAsync(Key);
var t11 = db.LockReleaseAsync(Key, right);
var t12 = db.LockQueryAsync(Key);
var t13 = db.LockTakeAsync(Key, wrong, TimeSpan.FromSeconds(10));
Assert.IsNotNull(right);
Assert.IsNotNull(wrong);
Assert.AreNotEqual(right, wrong);
Assert.IsTrue(conn.Wait(t1), "1");
Assert.IsFalse(conn.Wait(t1b), "1b");
Assert.AreEqual(right, conn.Wait(t2), "2");
Assert.IsFalse(conn.Wait(t3), "3");
Assert.AreEqual(right, conn.Wait(t4), "4");
Assert.IsFalse(conn.Wait(t5), "5");
Assert.AreEqual(right, conn.Wait(t6), "6");
var ttl = conn.Wait(t7).Value.TotalSeconds;
Assert.IsTrue(ttl > 0 && ttl <= 20, "7");
Assert.IsTrue(conn.Wait(t8), "8");
Assert.AreEqual(right, conn.Wait(t9), "9");
ttl = conn.Wait(t10).Value.TotalSeconds;
Assert.IsTrue(ttl > 50 && ttl <= 60, "10");
Assert.IsTrue(conn.Wait(t11), "11");
Assert.IsNull((string)conn.Wait(t12), "12");
Assert.IsTrue(conn.Wait(t13), "13");
}
}
//public void TestManualLockOpCountByVersion(RedisConnection conn, int expected, bool existFirst)
//{
// const int DB = 0, LockDuration = 30;
// const string Key = "TestManualLockOpCountByVersion";
// conn.Wait(conn.Open());
// conn.Keys.Remove(DB, Key);
// var newVal = "us:" + Config.CreateUniqueName();
// string expectedVal = newVal;
// if (existFirst)
// {
// expectedVal = "other:" + Config.CreateUniqueName();
// conn.Strings.Set(DB, Key, expectedVal, LockDuration);
// }
// int countBefore = conn.GetCounters().MessagesSent;
// var tran = conn.CreateTransaction();
// tran.AddCondition(Condition.KeyNotExists(DB, Key));
// tran.Strings.Set(DB, Key, newVal, LockDuration);
// var taken = conn.Wait(tran.Execute());
// int countAfter = conn.GetCounters().MessagesSent;
// var valAfter = conn.Wait(conn.Strings.GetString(DB, Key));
// Assert.AreEqual(!existFirst, taken, "lock taken (manual)");
// Assert.AreEqual(expectedVal, valAfter, "taker (manual)");
// Assert.AreEqual(expected, (countAfter - countBefore) - 1, "expected ops (including ping) (manual)");
// // note we get a ping from GetCounters
//}
[Test]
public void TestBasicLockNotTaken()
{
using (var conn = Create())
{
int errorCount = 0;
conn.ErrorMessage += delegate { Interlocked.Increment(ref errorCount); };
Task<bool> taken = null;
Task<RedisValue> newValue = null;
Task<TimeSpan?> ttl = null;
const int LOOP = 50;
var db = conn.GetDatabase(0);
for (int i = 0; i < LOOP; i++)
{
db.KeyDeleteAsync("lock-not-exists");
taken = db.LockTakeAsync("lock-not-exists", "new-value", TimeSpan.FromSeconds(10));
newValue = db.StringGetAsync("lock-not-exists");
ttl = db.KeyTimeToLiveAsync("lock-not-exists");
}
Assert.IsTrue(conn.Wait(taken), "taken");
Assert.AreEqual("new-value", (string)conn.Wait(newValue));
var ttlValue = conn.Wait(ttl).Value.TotalSeconds;
Assert.IsTrue(ttlValue >= 8 && ttlValue <= 10, "ttl");
Assert.AreEqual(0, errorCount);
}
}
[Test]
public void TestBasicLockTaken()
{
using (var conn = Create())
{
var db = conn.GetDatabase(0);
db.KeyDelete("lock-exists");
db.StringSet("lock-exists", "old-value", TimeSpan.FromSeconds(20));
var taken = db.LockTakeAsync("lock-exists", "new-value", TimeSpan.FromSeconds(10));
var newValue = db.StringGetAsync("lock-exists");
var ttl = db.KeyTimeToLiveAsync("lock-exists");
Assert.IsFalse(conn.Wait(taken), "taken");
Assert.AreEqual("old-value", (string)conn.Wait(newValue));
var ttlValue = conn.Wait(ttl).Value.TotalSeconds;
Assert.IsTrue(ttlValue >= 18 && ttlValue <= 20, "ttl");
}
}
}
}
using System;
using System.IO;
using System.Linq;
using System.Net;
using NUnit.Framework;
namespace StackExchange.Redis.Tests
{
[TestFixture]
public class MultiMaster : TestBase
{
protected override string GetConfiguration()
{
return PrimaryServer + ":" + SecurePort + "," + PrimaryServer + ":" + PrimaryPort + ",password=" + SecurePassword;
}
[Test, ExpectedException(typeof(RedisCommandException), ExpectedMessage = "FLUSHDB cannot be issued to a slave")]
public void CannotFlushSlave()
{
ConfigurationOptions config = GetMasterSlaveConfig();
using (var conn = ConnectionMultiplexer.Connect(config))
{
var servers = Array.ConvertAll(conn.GetEndPoints(), e => conn.GetServer(e));
var slave = servers.First(x => x.IsSlave);
slave.FlushDatabase();
}
}
[Test]
public void DeslaveGoesToPrimary()
{
ConfigurationOptions config = GetMasterSlaveConfig();
using (var conn = ConnectionMultiplexer.Connect(config))
{
var primary = conn.GetServer(new IPEndPoint(IPAddress.Parse(PrimaryServer), PrimaryPort));
var secondary = conn.GetServer(new IPEndPoint(IPAddress.Parse(PrimaryServer), SlavePort));
primary.Ping();
secondary.Ping();
primary.MakeMaster(ReplicationChangeOptions.SetTiebreaker);
secondary.MakeMaster(ReplicationChangeOptions.None);
primary.Ping();
secondary.Ping();
using (var writer = new StringWriter())
{
conn.Configure(writer);
string log = writer.ToString();
Assert.IsTrue(log.Contains("tie-break is unanimous at " + PrimaryServer + ":" + PrimaryPort), "unanimous");
}
// k, so we know everyone loves 6379; is that what we get?
var db = conn.GetDatabase();
RedisKey key = Me();
EndPoint demandMaster, preferMaster, preferSlave, demandSlave;
preferMaster = db.IdentifyEndpoint(key, CommandFlags.PreferMaster);
demandMaster = db.IdentifyEndpoint(key, CommandFlags.DemandMaster);
preferSlave = db.IdentifyEndpoint(key, CommandFlags.PreferSlave);
Assert.AreEqual(primary.EndPoint, demandMaster, "demand master");
Assert.AreEqual(primary.EndPoint, preferMaster, "prefer master");
Assert.AreEqual(primary.EndPoint, preferSlave, "prefer slave");
try
{
demandSlave = db.IdentifyEndpoint(key, CommandFlags.DemandSlave);
Assert.Fail("this should not have worked");
}
catch (RedisConnectionException ex)
{
Assert.AreEqual("No connection is available to service this operation: EXISTS", ex.Message);
}
primary.MakeMaster(ReplicationChangeOptions.Broadcast | ReplicationChangeOptions.EnslaveSubordinates | ReplicationChangeOptions.SetTiebreaker);
primary.Ping();
secondary.Ping();
preferMaster = db.IdentifyEndpoint(key, CommandFlags.PreferMaster);
demandMaster = db.IdentifyEndpoint(key, CommandFlags.DemandMaster);
preferSlave = db.IdentifyEndpoint(key, CommandFlags.PreferSlave);
demandSlave = db.IdentifyEndpoint(key, CommandFlags.DemandSlave);
Assert.AreEqual(primary.EndPoint, demandMaster, "demand master");
Assert.AreEqual(primary.EndPoint, preferMaster, "prefer master");
Assert.AreEqual(secondary.EndPoint, preferSlave, "prefer slave");
Assert.AreEqual(secondary.EndPoint, preferSlave, "demand slave slave");
}
}
private static ConfigurationOptions GetMasterSlaveConfig()
{
return new ConfigurationOptions
{
AllowAdmin = true,
SyncTimeout = 100000,
EndPoints =
{
{ PrimaryServer, PrimaryPort },
{ PrimaryServer, SlavePort },
}
};
}
[Test]
public void TestMultiNoTieBreak()
{
using (var log = new StringWriter())
using (var conn = Create(log: log, tieBreaker: ""))
{
Console.WriteLine(log);
Assert.IsTrue(log.ToString().Contains("Choosing master arbitrarily"));
}
}
[Test]
[TestCase(PrimaryServer + ":" + PrimaryPortString, PrimaryServer + ":" + PrimaryPortString, PrimaryServer + ":" + PrimaryPortString)]
[TestCase(PrimaryServer + ":" + SecurePortString, PrimaryServer + ":" + SecurePortString, PrimaryServer + ":" + SecurePortString)]
[TestCase(PrimaryServer + ":" + SecurePortString, PrimaryServer + ":" + PrimaryPortString, null)]
[TestCase(PrimaryServer + ":" + PrimaryPortString, PrimaryServer + ":" + SecurePortString, null)]
[TestCase(null, PrimaryServer + ":" + PrimaryPortString, PrimaryServer + ":" + PrimaryPortString)]
[TestCase(PrimaryServer + ":" + PrimaryPortString, null, PrimaryServer + ":" + PrimaryPortString)]
[TestCase(null, PrimaryServer + ":" + SecurePortString, PrimaryServer + ":" + SecurePortString)]
[TestCase(PrimaryServer + ":" + SecurePortString, null, PrimaryServer + ":" + SecurePortString)]
[TestCase(null, null, null)]
public void TestMultiWithTiebreak(string a, string b, string elected)
{
const string TieBreak = "__tie__";
// set the tie-breakers to the expected state
using(var aConn = ConnectionMultiplexer.Connect(PrimaryServer + ":" + PrimaryPort))
{
aConn.GetDatabase().StringSet(TieBreak, a);
}
using (var aConn = ConnectionMultiplexer.Connect(PrimaryServer + ":" + SecurePort + ",password=" + SecurePassword))
{
aConn.GetDatabase().StringSet(TieBreak, b);
}
// see what happens
using (var log = new StringWriter())
using (var conn = Create(log: log, tieBreaker: TieBreak))
{
string text = log.ToString();
Console.WriteLine(text);
Assert.IsFalse(text.Contains("failed to nominate"), "failed to nominate");
if (elected != null)
{
Assert.IsTrue(text.Contains("Elected: " + elected), "elected");
}
int nullCount = (a == null ? 1 : 0) + (b == null ? 1 : 0);
if((a == b && nullCount == 0) || nullCount == 1)
{
Assert.IsTrue(text.Contains("tie-break is unanimous"), "unanimous");
Assert.IsFalse(text.Contains("Choosing master arbitrarily"), "arbitrarily");
}
else
{
Assert.IsFalse(text.Contains("tie-break is unanimous"), "unanimous");
Assert.IsTrue(text.Contains("Choosing master arbitrarily"), "arbitrarily");
}
}
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using NUnit.Framework;
namespace StackExchange.Redis.Tests
{
[TestFixture]
public class Naming
{
[Test]
[TestCase(typeof(IDatabase), false)]
[TestCase(typeof(IDatabaseAsync), true)]
[TestCase(typeof(Condition), false)]
public void CheckSignatures(Type type, bool isAsync)
{
// check that all methods and interfaces look appropriate for their sync/async nature
CheckName(type, isAsync);
var members = type.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly);
foreach(var member in members)
{
if (member.Name.StartsWith("get_") || member.Name.StartsWith("set_") || member.Name.StartsWith("add_") || member.Name.StartsWith("remove_")) continue;
CheckMethod(member, isAsync);
}
}
[Test]
public void ShowReadOnlyOperations()
{
var msg = typeof(ConnectionMultiplexer).Assembly.GetType("StackExchange.Redis.Message");
Assert.IsNotNull(msg, "Message");
var cmd = typeof(ConnectionMultiplexer).Assembly.GetType("StackExchange.Redis.RedisCommand");
Assert.IsNotNull(cmd, "RedisCommand");
var method = msg.GetMethod("IsMasterOnly", BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public);
Assert.IsNotNull(method, "IsMasterOnly");
object[] args = new object[1];
List<object> masterSlave = new List<object>();
List<object> masterOnly = new List<object>();
foreach (var val in Enum.GetValues(cmd))
{
args[0] = val;
bool isMasterOnly = (bool)method.Invoke(null, args);
(isMasterOnly ? masterOnly : masterSlave).Add(val);
if(!isMasterOnly)
{
Console.WriteLine(val);
}
}
Console.WriteLine("master-only: {0}, vs master/slave: {1}", masterOnly.Count, masterSlave.Count);
Console.WriteLine();
Console.WriteLine("master-only:");
foreach (var val in masterOnly) Console.WriteLine(val);
Console.WriteLine();
Console.WriteLine("master/slave:");
foreach (var val in masterSlave) Console.WriteLine(val);
}
[Test]
[TestCase(typeof(IDatabase))]
[TestCase(typeof(IDatabaseAsync))]
public void CheckDatabaseMethodsUseKeys(Type type)
{
foreach (var method in type.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly))
{
if (IgnoreMethodConventions(method)) continue;
switch(method.Name)
{
case "RandomKey":
case "RandomKeyAsync":
continue; // they're fine, but don't want to widen check to return type
}
bool usesKey = method.GetParameters().Any(p => UsesKey(p.ParameterType));
Assert.IsTrue(usesKey, type.Name + ":" + method.Name);
}
}
static bool UsesKey(Type type)
{
if (type == typeof(RedisKey)) return true;
if(type.IsArray)
{
if (UsesKey(type.GetElementType())) return true;
}
if(type.IsGenericType) // KVP, etc
{
var args = type.GetGenericArguments();
if (args.Any(UsesKey)) return true;
}
return false;
}
static bool IgnoreMethodConventions(MethodInfo method)
{
string name = method.Name;
if (name.StartsWith("get_") || name.StartsWith("set_") || name.StartsWith("add_") || name.StartsWith("remove_")) return true;
switch(name)
{
case "CreateBatch":
case "CreateTransaction":
case "IsConnected":
case "SetScan":
return true;
}
return false;
}
[Test]
[TestCase(typeof(IDatabase), typeof(IDatabaseAsync))]
[TestCase(typeof(IDatabaseAsync), typeof(IDatabase))]
public void CheckSyncAsyncMethodsMatch(Type from, Type to)
{
const BindingFlags flags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly;
int count = 0;
foreach (var method in from.GetMethods(flags))
{
if (IgnoreMethodConventions(method)) continue;
string name = method.Name, huntName;
if (name.EndsWith("Async")) huntName = name.Substring(0, name.Length - 5);
else huntName = name + "Async";
Type huntType;
if (method.ReturnType == null || method.ReturnType == typeof(void))
{
huntType = typeof(Task);
}
else if (method.ReturnType == typeof(Task))
{
huntType = null;
}
else if (method.ReturnType.IsSubclassOf(typeof(Task)))
{
huntType = method.ReturnType.GetGenericArguments()[0];
}
else
{
huntType = typeof(Task<>).MakeGenericType(method.ReturnType);
}
var pFrom = method.GetParameters();
Type[] args = Array.ConvertAll(pFrom, x => x.ParameterType);
Assert.AreEqual(typeof(CommandFlags), args.Last());
var found = to.GetMethod(huntName, flags, null, method.CallingConvention, args, null);
Assert.IsNotNull(found, "Found " + name + ", no " + huntName);
var pTo = found.GetParameters();
for(int i = 0; i < pFrom.Length;i++)
{
Assert.AreEqual(pFrom[i].Name, pTo[i].Name, method.Name + ":" + pFrom[i].Name);
Assert.AreEqual(pFrom[i].ParameterType, pTo[i].ParameterType, method.Name + ":" + pFrom[i].Name);
}
count++;
}
Console.WriteLine("Validated: {0} ({1} methods)", from.Name, count);
}
static readonly Type ignoreType = typeof(ConnectionMultiplexer).Assembly.GetType("StackExchange.Redis.IgnoreNamePrefixAttribute");
void CheckMethod(MethodInfo method, bool isAsync)
{
#if DEBUG
bool ignorePrefix = ignoreType != null && Attribute.IsDefined(method, ignoreType);
if(ignorePrefix)
{
Attribute attrib = Attribute.GetCustomAttribute(method, ignoreType);
if((bool)attrib.GetType().GetProperty("IgnoreEntireMethod").GetValue(attrib))
{
return;
}
}
string shortName = method.Name, fullName = method.DeclaringType.Name + "." + shortName;
CheckName(method, isAsync);
if (!ignorePrefix)
{
Assert.IsTrue(shortName.StartsWith("Hash") || shortName.StartsWith("Key")
|| shortName.StartsWith("String") || shortName.StartsWith("List")
|| shortName.StartsWith("SortedSet") || shortName.StartsWith("Set")
|| shortName.StartsWith("Debug") || shortName.StartsWith("Lock")
, fullName + ":Prefix");
}
Assert.IsFalse(shortName.Contains("If"), fullName + ":If"); // should probably be a When option
var returnType = method.ReturnType ?? typeof(void);
if (isAsync)
{
Assert.IsTrue(typeof(Task).IsAssignableFrom(returnType), fullName + ":Task");
}
else
{
Assert.IsFalse(typeof(Task).IsAssignableFrom(returnType), fullName + ":Task");
}
#endif
}
void CheckName(MemberInfo member, bool isAsync)
{
if (isAsync) Assert.IsTrue(member.Name.EndsWith("Async"), member.Name + ":Name - end *Async");
else Assert.IsFalse(member.Name.EndsWith("Async"), member.Name + ":Name - don't end *Async");
}
}
}
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("StackExchange.Redis.Tests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("StackExchange.Redis.Tests")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("70fae8f5-4f2f-4422-92c6-05bde74cdd52")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
This diff is collapsed.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using NUnit.Framework;
namespace StackExchange.Redis.Tests
{
[TestFixture]
public class RealWorld
{
[Test]
public void WhyDoesThisNotWork()
{
var sw = new StringWriter();
Console.WriteLine("first:");
using (var conn = ConnectionMultiplexer.Connect("localhost:6379,localhost:6380,name=Core (Q&A),tiebreaker=:RedisMaster,abortConnect=False", sw))
{
Console.WriteLine(sw);
Console.WriteLine();
Console.WriteLine("pausing...");
Thread.Sleep(200);
Console.WriteLine("second:");
sw = new StringWriter();
bool result = conn.Configure(sw);
Console.WriteLine("Returned: {0}", result);
Console.WriteLine(sw);
}
}
}
}
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net;
using NUnit.Framework;
namespace StackExchange.Redis.Tests
{
[TestFixture]
public class SSL : TestBase
{
[Test]
[TestCase(6379, null)]
[TestCase(6380, "as if we care")]
public void ConnectToSSLServer(int port, string sslHost)
{
var config = new ConfigurationOptions
{
CommandMap = CommandMap.Create( // looks like "config" is disabled
new Dictionary<string, string>
{
{ "config", null },
{ "cluster", null }
}
),
SslHost = sslHost,
EndPoints = { { "sslredis", port} },
AllowAdmin = true,
SyncTimeout = 5000
};
config.CertificateValidation += (sender, cert, chain, errors) =>
{
Console.WriteLine("cert issued to: " + cert.Subject);
return true; // fingers in ears, pretend we don't know this is wrong
};
using (var muxer = ConnectionMultiplexer.Connect(config, Console.Out))
{
var db = muxer.GetDatabase();
db.Ping();
using (var file = File.Create("ssl" + port + ".zip"))
{
muxer.ExportConfiguration(file);
}
RedisKey key = "SE.Redis";
const int AsyncLoop = 2000;
// perf; async
db.KeyDelete(key, CommandFlags.FireAndForget);
var watch = Stopwatch.StartNew();
for (int i = 0; i < AsyncLoop; i++)
{
db.StringIncrement(key, flags: CommandFlags.FireAndForget);
}
// need to do this inside the timer to measure the TTLB
long value = (long)db.StringGet(key);
watch.Stop();
Assert.AreEqual(AsyncLoop, value);
Console.WriteLine("F&F: {0} INCR, {1:###,##0}ms, {2} ops/s; final value: {3}",
AsyncLoop,
(long)watch.ElapsedMilliseconds,
(long)(AsyncLoop / watch.Elapsed.TotalSeconds),
value);
// perf: sync/multi-threaded
TestConcurrent(db, key, 30, 10);
TestConcurrent(db, key, 30, 20);
TestConcurrent(db, key, 30, 30);
TestConcurrent(db, key, 30, 40);
TestConcurrent(db, key, 30, 50);
}
}
private static void TestConcurrent(IDatabase db, RedisKey key, int SyncLoop, int Threads)
{
long value;
db.KeyDelete(key, CommandFlags.FireAndForget);
var time = RunConcurrent(delegate
{
for (int i = 0; i < SyncLoop; i++)
{
db.StringIncrement(key);
}
}, Threads, timeout: 45000);
value = (long)db.StringGet(key);
Assert.AreEqual(SyncLoop * Threads, value);
Console.WriteLine("Sync: {0} INCR using {1} threads, {2:###,##0}ms, {3} ops/s; final value: {4}",
SyncLoop * Threads, Threads,
(long)time.TotalMilliseconds,
(long)((SyncLoop * Threads) / time.TotalSeconds),
value);
}
}
}
using System;
using System.Diagnostics;
using NUnit.Framework;
namespace StackExchange.Redis.Tests
{
[TestFixture]
public class Secure : TestBase
{
protected override string GetConfiguration()
{
return PrimaryServer + ":" + SecurePort + ",password=" + SecurePassword +",name=MyClient";
}
[Test]
[TestCase(true)]
[TestCase(false)]
public void MassiveBulkOpsFireAndForgetSecure(bool preserveOrder)
{
using (var muxer = Create())
{
muxer.PreserveAsyncOrder = preserveOrder;
#if DEBUG
long oldAlloc = ConnectionMultiplexer.GetResultBoxAllocationCount();
#endif
RedisKey key = "MBOF";
var conn = muxer.GetDatabase();
conn.Ping();
var watch = Stopwatch.StartNew();
for (int i = 0; i <= AsyncOpsQty; i++)
{
conn.StringSet(key, i, flags: CommandFlags.FireAndForget);
}
int val = (int)conn.StringGet(key);
Assert.AreEqual(AsyncOpsQty, val);
watch.Stop();
Console.WriteLine("{2}: Time for {0} ops: {1}ms ({3}); ops/s: {4}", AsyncOpsQty, watch.ElapsedMilliseconds, Me(),
preserveOrder ? "preserve order" : "any order",
AsyncOpsQty / watch.Elapsed.TotalSeconds);
#if DEBUG
long newAlloc = ConnectionMultiplexer.GetResultBoxAllocationCount();
Console.WriteLine("ResultBox allocations: {0}",
newAlloc - oldAlloc);
Assert.IsTrue(newAlloc - oldAlloc <= 2);
#endif
}
}
[Test]
public void CheckConfig()
{
var config = ConfigurationOptions.Parse(GetConfiguration());
foreach(var ep in config.EndPoints)
Console.WriteLine(ep);
Assert.AreEqual(1, config.EndPoints.Count);
Assert.AreEqual("changeme", config.Password);
}
[Test]
public void Connect()
{
using(var server = Create())
{
server.GetDatabase().Ping();
}
}
[Test]
[TestCase("wrong")]
[TestCase("")]
[ExpectedException(typeof(RedisConnectionException), ExpectedMessage = "No connection is available to service this operation: PING")]
public void ConnectWithWrongPassword(string password)
{
SetExpectedAmbientFailureCount(-1);
using (var server = Create(password: password, checkConnect: false))
{
server.GetDatabase().Ping();
}
}
}
}
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment