Commit 567cdf73 authored by Nick Craver's avatar Nick Craver

Code cleanup and C#6 feature use

parent 470898c9
......@@ -46,7 +46,7 @@ public ResponseException(string code)
public Redis(string host, int port)
{
if (host == null)
throw new ArgumentNullException("host");
throw new ArgumentNullException(nameof(host));
Host = host;
Port = port;
......@@ -94,9 +94,9 @@ public int Db
public void Set(string key, string value)
{
if (key == null)
throw new ArgumentNullException("key");
throw new ArgumentNullException(nameof(key));
if (value == null)
throw new ArgumentNullException("value");
throw new ArgumentNullException(nameof(value));
Set(key, Encoding.UTF8.GetBytes(value));
}
......@@ -104,12 +104,12 @@ public void Set(string key, string value)
public void Set(string key, byte[] value)
{
if (key == null)
throw new ArgumentNullException("key");
throw new ArgumentNullException(nameof(key));
if (value == null)
throw new ArgumentNullException("value");
throw new ArgumentNullException(nameof(value));
if (value.Length > 1073741824)
throw new ArgumentException("value exceeds 1G", "value");
throw new ArgumentException("value exceeds 1G", nameof(value));
if (!SendDataCommand(value, "SET {0} {1}\r\n", key, value.Length))
throw new Exception("Unable to connect");
......@@ -119,9 +119,9 @@ public void Set(string key, byte[] value)
public bool SetNX(string key, string value)
{
if (key == null)
throw new ArgumentNullException("key");
throw new ArgumentNullException(nameof(key));
if (value == null)
throw new ArgumentNullException("value");
throw new ArgumentNullException(nameof(value));
return SetNX(key, Encoding.UTF8.GetBytes(value));
}
......@@ -129,12 +129,12 @@ public bool SetNX(string key, string value)
public bool SetNX(string key, byte[] value)
{
if (key == null)
throw new ArgumentNullException("key");
throw new ArgumentNullException(nameof(key));
if (value == null)
throw new ArgumentNullException("value");
throw new ArgumentNullException(nameof(value));
if (value.Length > 1073741824)
throw new ArgumentException("value exceeds 1G", "value");
throw new ArgumentException("value exceeds 1G", nameof(value));
return SendDataExpectInt(value, "SETNX {0} {1}\r\n", key, value.Length) > 0 ? true : false;
}
......@@ -147,7 +147,7 @@ public void Set(IDictionary<string, string> dict)
public void Set(IDictionary<string, byte[]> dict)
{
if (dict == null)
throw new ArgumentNullException("dict");
throw new ArgumentNullException(nameof(dict));
var nl = Encoding.UTF8.GetBytes("\r\n");
......@@ -173,14 +173,14 @@ public void Set(IDictionary<string, byte[]> dict)
public byte[] Get(string key)
{
if (key == null)
throw new ArgumentNullException("key");
throw new ArgumentNullException(nameof(key));
return SendExpectData(null, "GET " + key + "\r\n");
}
public string GetString(string key)
{
if (key == null)
throw new ArgumentNullException("key");
throw new ArgumentNullException(nameof(key));
return Encoding.UTF8.GetString(Get(key));
}
......@@ -192,12 +192,12 @@ public byte[][] Sort(SortOptions options)
public byte[] GetSet(string key, byte[] value)
{
if (key == null)
throw new ArgumentNullException("key");
throw new ArgumentNullException(nameof(key));
if (value == null)
throw new ArgumentNullException("value");
throw new ArgumentNullException(nameof(value));
if (value.Length > 1073741824)
throw new ArgumentException("value exceeds 1G", "value");
throw new ArgumentException("value exceeds 1G", nameof(value));
if (!SendDataCommand(value, "GETSET {0} {1}\r\n", key, value.Length))
throw new Exception("Unable to connect");
......@@ -208,9 +208,9 @@ public byte[] GetSet(string key, byte[] value)
public string GetSet(string key, string value)
{
if (key == null)
throw new ArgumentNullException("key");
throw new ArgumentNullException(nameof(key));
if (value == null)
throw new ArgumentNullException("value");
throw new ArgumentNullException(nameof(value));
return Encoding.UTF8.GetString(GetSet(key, Encoding.UTF8.GetBytes(value)));
}
......@@ -466,56 +466,56 @@ byte[] ReadData()
public bool ContainsKey(string key)
{
if (key == null)
throw new ArgumentNullException("key");
throw new ArgumentNullException(nameof(key));
return SendExpectInt("EXISTS " + key + "\r\n") == 1;
}
public bool Remove(string key)
{
if (key == null)
throw new ArgumentNullException("key");
throw new ArgumentNullException(nameof(key));
return SendExpectInt("DEL " + key + "\r\n", key) == 1;
}
public int Remove(params string[] args)
{
if (args == null)
throw new ArgumentNullException("args");
throw new ArgumentNullException(nameof(args));
return SendExpectInt("DEL " + string.Join(" ", args) + "\r\n");
}
public int Increment(string key)
{
if (key == null)
throw new ArgumentNullException("key");
throw new ArgumentNullException(nameof(key));
return SendExpectInt("INCR " + key + "\r\n");
}
public int Increment(string key, int count)
{
if (key == null)
throw new ArgumentNullException("key");
throw new ArgumentNullException(nameof(key));
return SendExpectInt("INCRBY {0} {1}\r\n", key, count);
}
public int Decrement(string key)
{
if (key == null)
throw new ArgumentNullException("key");
throw new ArgumentNullException(nameof(key));
return SendExpectInt("DECR " + key + "\r\n");
}
public int Decrement(string key, int count)
{
if (key == null)
throw new ArgumentNullException("key");
throw new ArgumentNullException(nameof(key));
return SendExpectInt("DECRBY {0} {1}\r\n", key, count);
}
public KeyType TypeOf(string key)
{
if (key == null)
throw new ArgumentNullException("key");
throw new ArgumentNullException(nameof(key));
switch (SendExpectString("TYPE {0}\r\n", key))
{
case "none":
......@@ -538,30 +538,30 @@ public string RandomKey()
public bool Rename(string oldKeyname, string newKeyname)
{
if (oldKeyname == null)
throw new ArgumentNullException("oldKeyname");
throw new ArgumentNullException(nameof(oldKeyname));
if (newKeyname == null)
throw new ArgumentNullException("newKeyname");
throw new ArgumentNullException(nameof(newKeyname));
return SendGetString("RENAME {0} {1}\r\n", oldKeyname, newKeyname)[0] == '+';
}
public bool Expire(string key, int seconds)
{
if (key == null)
throw new ArgumentNullException("key");
throw new ArgumentNullException(nameof(key));
return SendExpectInt("EXPIRE {0} {1}\r\n", key, seconds) == 1;
}
public bool ExpireAt(string key, int time)
{
if (key == null)
throw new ArgumentNullException("key");
throw new ArgumentNullException(nameof(key));
return SendExpectInt("EXPIREAT {0} {1}\r\n", key, time) == 1;
}
public int TimeToLive(string key)
{
if (key == null)
throw new ArgumentNullException("key");
throw new ArgumentNullException(nameof(key));
return SendExpectInt("TTL {0}\r\n", key);
}
......@@ -778,13 +778,13 @@ public byte[][] GetUnionOfSets(params string[] keys)
void StoreSetCommands(string cmd, string destKey, params string[] keys)
{
if (String.IsNullOrEmpty(cmd))
throw new ArgumentNullException("cmd");
throw new ArgumentNullException(nameof(cmd));
if (String.IsNullOrEmpty(destKey))
throw new ArgumentNullException("destKey");
throw new ArgumentNullException(nameof(destKey));
if (keys == null)
throw new ArgumentNullException("keys");
throw new ArgumentNullException(nameof(keys));
SendExpectSuccess("{0} {1} {2}\r\n", cmd, destKey, String.Join(" ", keys));
}
......
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Linq;
using NUnit.Framework;
namespace StackExchange.Redis.Tests
......
#if FEATURE_MOQ
using System;
using Moq;
using NUnit.Framework;
using StackExchange.Redis.KeyspaceIsolation;
......
using System.Linq;
using NUnit.Framework;
using NUnit.Framework;
namespace StackExchange.Redis.Tests
{
......
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
......@@ -555,7 +554,7 @@ public void GetFromRightNodeBasedOnFlags(CommandFlags flags, bool isSlave)
private static string Describe(EndPoint endpoint)
{
return endpoint == null ? "(unknown)" : endpoint.ToString();
return endpoint?.ToString() ?? "(unknown)";
}
class TestProfiler : IProfiler
......
using System;
using System.Threading;
using System.Threading;
using NUnit.Framework;
namespace StackExchange.Redis.Tests
......
using NUnit.Framework;
using System;
using System.Diagnostics;
using System.Threading;
......
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NUnit.Framework;
using StackExchange.Redis;
namespace StackExchange.Redis.Tests.Issues
{
......@@ -32,7 +27,7 @@ public void ConfigurationOptions_UnspecifiedDefaultDb()
var log = new StringWriter();
try
{
using (var conn = ConnectionMultiplexer.Connect(string.Format("{0}:{1}", PrimaryServer, PrimaryPort), log)) {
using (var conn = ConnectionMultiplexer.Connect($"{PrimaryServer}:{PrimaryPort}", log)) {
var db = conn.GetDatabase();
Assert.AreEqual(0, db.Database);
}
......@@ -49,7 +44,7 @@ public void ConfigurationOptions_SpecifiedDefaultDb()
var log = new StringWriter();
try
{
using (var conn = ConnectionMultiplexer.Connect(string.Format("{0}:{1},defaultDatabase=3", PrimaryServer, PrimaryPort), log)) {
using (var conn = ConnectionMultiplexer.Connect($"{PrimaryServer}:{PrimaryPort},defaultDatabase=3", log)) {
var db = conn.GetDatabase();
Assert.AreEqual(3, db.Database);
}
......
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StackExchange.Redis.Tests.Issues
namespace StackExchange.Redis.Tests.Issues
{
class Issue118
{
......
using System;
using System.Diagnostics;
using System.Diagnostics;
using System.Linq;
using NUnit.Framework;
......
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
#if CORE_CLR
using System.Reflection;
#endif
......
......@@ -28,7 +28,7 @@ static TaskCompletionSource<T> Create<T>(SourceOrign origin)
case SourceOrign.NewTCS: return new TaskCompletionSource<T>();
case SourceOrign.Create: return TaskSource.Create<T>(null);
case SourceOrign.CreateDenyExec: return TaskSource.CreateDenyExecSync<T>(null);
default: throw new ArgumentOutOfRangeException("origin");
default: throw new ArgumentOutOfRangeException(nameof(origin));
}
}
[Test]
......@@ -78,7 +78,7 @@ public enum AttachMode
}
class AwaitState
{
public int Thread { get { return continuationThread; } }
public int Thread => continuationThread;
volatile int continuationThread = -1;
private ManualResetEventSlim evt = new ManualResetEventSlim();
public void Wait()
......@@ -99,7 +99,7 @@ public void Attach(Task task, AttachMode attachMode)
DoAwait(task);
break;
default:
throw new ArgumentOutOfRangeException("attachMode");
throw new ArgumentOutOfRangeException(nameof(attachMode));
}
}
private void Continue(Task task)
......
<wpf:ResourceDictionary xml:space="preserve" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:ss="urn:shemas-jetbrains-com:settings-storage-xaml" xmlns:wpf="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=OK/@EntryIndexedValue">OK</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=PONG/@EntryIndexedValue">PONG</s:String></wpf:ResourceDictionary>
\ No newline at end of file
using System;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
#if !STRONG_NAME
using System.Runtime.CompilerServices;
#endif
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
......
......@@ -9,9 +9,22 @@ namespace StackExchange.Redis
/// </summary>
public sealed class CommandMap
{
private static readonly CommandMap
@default = CreateImpl(null, null),
twemproxy = CreateImpl(null, exclusions: new HashSet<RedisCommand>
private readonly byte[][] map;
internal CommandMap(byte[][] map)
{
this.map = map;
}
/// <summary>
/// The default commands specified by redis
/// </summary>
public static CommandMap Default { get; } = CreateImpl(null, null);
/// <summary>
/// The commands available to <a href="twemproxy">https://github.com/twitter/twemproxy</a>
/// </summary>
/// <remarks>https://github.com/twitter/twemproxy/blob/master/notes/redis.md</remarks>
public static CommandMap Twemproxy { get; } = CreateImpl(null, exclusions: new HashSet<RedisCommand>
{
// see https://github.com/twitter/twemproxy/blob/master/notes/redis.md
RedisCommand.KEYS, RedisCommand.MIGRATE, RedisCommand.MOVE, RedisCommand.OBJECT, RedisCommand.RANDOMKEY,
......@@ -38,45 +51,28 @@ private static readonly CommandMap
RedisCommand.BGREWRITEAOF, RedisCommand.BGSAVE, RedisCommand.CLIENT, RedisCommand.CLUSTER, RedisCommand.CONFIG, RedisCommand.DBSIZE,
RedisCommand.DEBUG, RedisCommand.FLUSHALL, RedisCommand.FLUSHDB, RedisCommand.INFO, RedisCommand.LASTSAVE, RedisCommand.MONITOR, RedisCommand.SAVE,
RedisCommand.SHUTDOWN, RedisCommand.SLAVEOF, RedisCommand.SLOWLOG, RedisCommand.SYNC, RedisCommand.TIME
}), ssdb = Create(new HashSet<string> {
});
/// <summary>
/// The commands available to <a href="ssdb">http://www.ideawu.com/ssdb/</a>
/// </summary>
/// <remarks>http://www.ideawu.com/ssdb/docs/redis-to-ssdb.html</remarks>
public static CommandMap SSDB { get; } = Create(new HashSet<string> {
// see http://www.ideawu.com/ssdb/docs/redis-to-ssdb.html
"ping",
"get", "set", "del", "incr", "incrby", "mget", "mset", "keys", "getset", "setnx",
"hget", "hset", "hdel", "hincrby", "hkeys", "hvals", "hmget", "hmset", "hlen",
"zscore", "zadd", "zrem", "zrange", "zrangebyscore", "zincrby", "zdecrby", "zcard",
"llen", "lpush", "rpush", "lpop", "rpop", "lrange", "lindex"
}, true),
sentinel = Create(new HashSet<string> {
// see http://redis.io/topics/sentinel
"ping", "info", "sentinel", "subscribe", "psubscribe", "unsubscribe", "punsubscribe" }, true);
private readonly byte[][] map;
internal CommandMap(byte[][] map)
{
this.map = map;
}
/// <summary>
/// The default commands specified by redis
/// </summary>
public static CommandMap Default { get { return @default; } }
/// <summary>
/// The commands available to <a href="twemproxy">https://github.com/twitter/twemproxy</a>
/// </summary>
/// <remarks>https://github.com/twitter/twemproxy/blob/master/notes/redis.md</remarks>
public static CommandMap Twemproxy { get { return twemproxy; } }
/// <summary>
/// The commands available to <a href="ssdb">http://www.ideawu.com/ssdb/</a>
/// </summary>
/// <remarks>http://www.ideawu.com/ssdb/docs/redis-to-ssdb.html</remarks>
public static CommandMap SSDB { get { return ssdb; } }
}, true);
/// <summary>
/// The commands available to <a href="Sentinel">http://redis.io/topics/sentinel</a>
/// </summary>
/// <remarks>http://redis.io/topics/sentinel</remarks>
public static CommandMap Sentinel { get { return sentinel; } }
public static CommandMap Sentinel { get; } = Create(new HashSet<string> {
// see http://redis.io/topics/sentinel
"ping", "info", "sentinel", "subscribe", "psubscribe", "unsubscribe", "punsubscribe" }, true);
/// <summary>
/// Create a new CommandMap, customizing some commands
......@@ -208,13 +204,13 @@ private static CommandMap CreateImpl(Dictionary<string, string> caseInsensitiveO
}
}
if (value != name) haveDelta = true;
// TODO: bug?
haveDelta = true;
byte[] val = string.IsNullOrWhiteSpace(value) ? null : Encoding.UTF8.GetBytes(value);
map[idx] = val;
}
}
if (!haveDelta && @default != null) return @default;
if (!haveDelta && Default != null) return Default;
return new CommandMap(map);
}
......
......@@ -11,13 +11,13 @@ public sealed class CommandTrace
internal CommandTrace(long uniqueId, long time, long duration, RedisValue[] arguments)
{
this.UniqueId = uniqueId;
this.Time = RedisBase.UnixEpoch.AddSeconds(time);
UniqueId = uniqueId;
Time = RedisBase.UnixEpoch.AddSeconds(time);
// duration = The amount of time needed for its execution, in microseconds.
// A tick is equal to 100 nanoseconds, or one ten-millionth of a second.
// So 1 microsecond = 10 ticks
this.Duration = TimeSpan.FromTicks(duration * 10);
this.Arguments = arguments;
Duration = TimeSpan.FromTicks(duration * 10);
Arguments = arguments;
}
/// <summary>
......
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StackExchange.Redis
{
......
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StackExchange.Redis
namespace StackExchange.Redis
{
internal static class VolatileWrapper
{
......
......@@ -4,7 +4,7 @@ namespace StackExchange.Redis
{
internal static class CompletedTask<T>
{
private readonly static Task<T> @default = FromResult(default(T), null);
private static readonly Task<T> @default = FromResult(default(T), null);
public static Task<T> Default(object asyncState)
{
......
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace StackExchange.Redis
{
......@@ -31,8 +27,8 @@ public struct Enumerator : IEnumerator<IProfiledCommand>
ProfileStorage Head;
ProfileStorage CurrentBacker;
bool IsEmpty { get { return Head == null; } }
bool IsUnstartedOrFinished { get { return CurrentBacker == null; } }
bool IsEmpty => Head == null;
bool IsUnstartedOrFinished => CurrentBacker == null;
internal Enumerator(ProfileStorage head)
{
......@@ -43,15 +39,9 @@ internal Enumerator(ProfileStorage head)
/// <summary>
/// The current element.
/// </summary>
public IProfiledCommand Current
{
get { return CurrentBacker; }
}
public IProfiledCommand Current => CurrentBacker;
object System.Collections.IEnumerator.Current
{
get { return CurrentBacker; }
}
object System.Collections.IEnumerator.Current => CurrentBacker;
/// <summary>
/// Advances the enumeration, returning true if there is a new element to consume and false
......
......@@ -18,7 +18,7 @@ public abstract class Condition
/// </summary>
public static Condition HashEqual(RedisKey key, RedisValue hashField, RedisValue value)
{
if (hashField.IsNull) throw new ArgumentNullException("hashField");
if (hashField.IsNull) throw new ArgumentNullException(nameof(hashField));
if (value.IsNull) return HashNotExists(key, hashField);
return new EqualsCondition(key, hashField, true, value);
}
......@@ -28,7 +28,7 @@ public static Condition HashEqual(RedisKey key, RedisValue hashField, RedisValue
/// </summary>
public static Condition HashExists(RedisKey key, RedisValue hashField)
{
if (hashField.IsNull) throw new ArgumentNullException("hashField");
if (hashField.IsNull) throw new ArgumentNullException(nameof(hashField));
return new ExistsCondition(key, hashField, true);
}
......@@ -37,7 +37,7 @@ public static Condition HashExists(RedisKey key, RedisValue hashField)
/// </summary>
public static Condition HashNotEqual(RedisKey key, RedisValue hashField, RedisValue value)
{
if (hashField.IsNull) throw new ArgumentNullException("hashField");
if (hashField.IsNull) throw new ArgumentNullException(nameof(hashField));
if (value.IsNull) return HashExists(key, hashField);
return new EqualsCondition(key, hashField, false, value);
}
......@@ -47,7 +47,7 @@ public static Condition HashNotEqual(RedisKey key, RedisValue hashField, RedisVa
/// </summary>
public static Condition HashNotExists(RedisKey key, RedisValue hashField)
{
if (hashField.IsNull) throw new ArgumentNullException("hashField");
if (hashField.IsNull) throw new ArgumentNullException(nameof(hashField));
return new ExistsCondition(key, hashField, false);
}
......@@ -136,7 +136,7 @@ public static Message CreateMessage(Condition condition, int db, CommandFlags fl
protected override bool SetResultCore(PhysicalConnection connection, Message message, RawResult result)
{
var msg = message as ConditionMessage;
var condition = msg == null ? null : msg.Condition;
var condition = msg?.Condition;
bool final;
if (condition != null && condition.TryValidate(result, out final))
{
......@@ -307,7 +307,7 @@ internal override Condition MapKeys(Func<RedisKey,RedisKey> map)
private readonly RedisKey key;
public ListCondition(RedisKey key, long index, bool expectedResult, RedisValue? expectedValue)
{
if (key.IsNull) throw new ArgumentException("key");
if (key.IsNull) throw new ArgumentException(nameof(key));
this.key = key;
this.index = index;
this.expectedResult = expectedResult;
......@@ -371,7 +371,7 @@ internal override bool TryValidate(RawResult result, out bool value)
/// </summary>
public sealed class ConditionResult
{
internal readonly Condition Condition;
internal readonly Condition Condition;
private ResultBox<bool> resultBox;
......@@ -386,7 +386,8 @@ internal ConditionResult(Condition condition)
/// <summary>
/// Indicates whether the condition was satisfied
/// </summary>
public bool WasSatisfied { get { return wasSatisfied; } }
public bool WasSatisfied => wasSatisfied;
internal IEnumerable<Message> CreateMessages(int db)
{
return Condition.CreateMessages(db, resultBox);
......
......@@ -178,7 +178,7 @@ public CommandMap CommandMap
if (commandMap != null) return commandMap;
switch (Proxy)
{
case Redis.Proxy.Twemproxy:
case Proxy.Twemproxy:
return CommandMap.Twemproxy;
default:
return CommandMap.Default;
......@@ -186,7 +186,7 @@ public CommandMap CommandMap
}
set
{
if (value == null) throw new ArgumentNullException("value");
if (value == null) throw new ArgumentNullException(nameof(value));
commandMap = value;
}
}
......@@ -215,7 +215,7 @@ public CommandMap CommandMap
/// <summary>
/// The endpoints defined for this configuration
/// </summary>
public EndPointCollection EndPoints { get { return endpoints; } }
public EndPointCollection EndPoints => endpoints;
/// <summary>
/// Use ThreadPriority.AboveNormal for SocketManager reader and writer threads (true by default). If false, ThreadPriority.Normal will be used.
......@@ -397,7 +397,7 @@ public override string ToString()
Append(sb, OptionKeys.ConfigCheckSeconds, configCheckSeconds);
Append(sb, OptionKeys.ResponseTimeout, responseTimeout);
Append(sb, OptionKeys.DefaultDatabase, defaultDatabase);
if (commandMap != null) commandMap.AppendDeltas(sb);
commandMap?.AppendDeltas(sb);
return sb.ToString();
}
......@@ -466,8 +466,7 @@ static void Append(StringBuilder sb, object value)
static void Append(StringBuilder sb, string prefix, object value)
{
if (value == null) return;
string s = value.ToString();
string s = value?.ToString();
if (!string.IsNullOrWhiteSpace(s))
{
if (sb.Length != 0) sb.Append(',');
......@@ -509,7 +508,7 @@ private void DoParse(string configuration, bool ignoreUnknown)
{
if (configuration == null)
{
throw new ArgumentNullException("configuration");
throw new ArgumentNullException(nameof(configuration));
}
if (string.IsNullOrWhiteSpace(configuration))
......@@ -629,7 +628,7 @@ private void DoParse(string configuration, bool ignoreUnknown)
}
if (map != null && map.Count != 0)
{
this.CommandMap = CommandMap.Create(map);
CommandMap = CommandMap.Create(map);
}
}
......
......@@ -7,11 +7,9 @@ namespace StackExchange.Redis
/// </summary>
public class ConnectionCounters
{
private readonly ConnectionType connectionType;
internal ConnectionCounters(ConnectionType connectionType)
{
this.connectionType = connectionType;
ConnectionType = connectionType;
}
/// <summary>
......@@ -27,7 +25,8 @@ internal ConnectionCounters(ConnectionType connectionType)
/// <summary>
/// The type of this connection
/// </summary>
public ConnectionType ConnectionType { get { return connectionType; } }
public ConnectionType ConnectionType { get; }
/// <summary>
/// The number of operations that failed to complete asynchronously
/// </summary>
......@@ -36,10 +35,7 @@ internal ConnectionCounters(ConnectionType connectionType)
/// <summary>
/// Indicates if there are any pending items or failures on this connection
/// </summary>
public bool IsEmpty
{
get { return PendingUnsentItems == 0 && SentItemsAwaitingResponse == 0 && ResponsesAwaitingAsyncCompletion == 0 && FailedAsynchronously == 0; }
}
public bool IsEmpty => PendingUnsentItems == 0 && SentItemsAwaitingResponse == 0 && ResponsesAwaitingAsyncCompletion == 0 && FailedAsynchronously == 0;
/// <summary>
/// Indicates the total number of messages despatched to a non-preferred endpoint, for example sent to a master
......@@ -80,7 +76,7 @@ public bool IsEmpty
/// <summary>
/// Indicates the total number of outstanding items against this connection
/// </summary>
public int TotalOutstanding { get { return PendingUnsentItems + SentItemsAwaitingResponse + ResponsesAwaitingAsyncCompletion; } }
public int TotalOutstanding => PendingUnsentItems + SentItemsAwaitingResponse + ResponsesAwaitingAsyncCompletion;
/// <summary>
/// Indicates the total number of writers items against this connection
......@@ -100,17 +96,17 @@ public override string ToString()
internal void Add(ConnectionCounters other)
{
if (other == null) return;
this.CompletedAsynchronously += other.CompletedAsynchronously;
this.CompletedSynchronously += other.CompletedSynchronously;
this.FailedAsynchronously += other.FailedAsynchronously;
this.OperationCount += other.OperationCount;
this.PendingUnsentItems += other.PendingUnsentItems;
this.ResponsesAwaitingAsyncCompletion += other.ResponsesAwaitingAsyncCompletion;
this.SentItemsAwaitingResponse += other.SentItemsAwaitingResponse;
this.SocketCount += other.SocketCount;
this.Subscriptions += other.Subscriptions;
this.WriterCount += other.WriterCount;
this.NonPreferredEndpointCount += other.NonPreferredEndpointCount;
CompletedAsynchronously += other.CompletedAsynchronously;
CompletedSynchronously += other.CompletedSynchronously;
FailedAsynchronously += other.FailedAsynchronously;
OperationCount += other.OperationCount;
PendingUnsentItems += other.PendingUnsentItems;
ResponsesAwaitingAsyncCompletion += other.ResponsesAwaitingAsyncCompletion;
SentItemsAwaitingResponse += other.SentItemsAwaitingResponse;
SocketCount += other.SocketCount;
Subscriptions += other.Subscriptions;
WriterCount += other.WriterCount;
NonPreferredEndpointCount += other.NonPreferredEndpointCount;
}
internal bool Any()
......@@ -135,5 +131,4 @@ internal void Append(StringBuilder sb)
if (NonPreferredEndpointCount != 0) sb.Append(", non-pref=").Append(NonPreferredEndpointCount);
}
}
}
......@@ -9,57 +9,43 @@ namespace StackExchange.Redis
/// </summary>
public sealed class ConnectionFailedEventArgs : EventArgs, ICompletable
{
private readonly ConnectionType connectionType;
private readonly EndPoint endpoint;
private readonly Exception exception;
private readonly ConnectionFailureType failureType;
private readonly EventHandler<ConnectionFailedEventArgs> handler;
private readonly object sender;
internal ConnectionFailedEventArgs(EventHandler<ConnectionFailedEventArgs> handler, object sender, EndPoint endPoint, ConnectionType connectionType, ConnectionFailureType failureType, Exception exception)
{
this.handler = handler;
this.sender = sender;
this.endpoint = endPoint;
this.connectionType = connectionType;
this.exception = exception;
this.failureType = failureType;
EndPoint = endPoint;
ConnectionType = connectionType;
Exception = exception;
FailureType = failureType;
}
/// <summary>
/// Gets the connection-type of the failing connection
/// </summary>
public ConnectionType ConnectionType
{
get { return connectionType; }
}
public ConnectionType ConnectionType { get; }
/// <summary>
/// Gets the failing server-endpoint
/// </summary>
public EndPoint EndPoint
{
get { return endpoint; }
}
public EndPoint EndPoint { get; }
/// <summary>
/// Gets the exception if available (this can be null)
/// </summary>
public Exception Exception
{
get { return exception; }
}
public Exception Exception { get; }
/// <summary>
/// The type of failure
/// </summary>
public ConnectionFailureType FailureType
{
get { return failureType; }
}
public ConnectionFailureType FailureType { get; }
void ICompletable.AppendStormLog(StringBuilder sb)
{
sb.Append("event, connection-failed: ");
if (endpoint == null) sb.Append("n/a");
else sb.Append(Format.ToString(endpoint));
if (EndPoint == null) sb.Append("n/a");
else sb.Append(Format.ToString(EndPoint));
}
bool ICompletable.TryComplete(bool isAsync)
......
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace StackExchange.Redis
{
......@@ -24,7 +18,7 @@ partial class ConnectionMultiplexer
/// </summary>
public void RegisterProfiler(IProfiler profiler)
{
if (profiler == null) throw new ArgumentNullException("profiler");
if (profiler == null) throw new ArgumentNullException(nameof(profiler));
if (this.profiler != null) throw new InvalidOperationException("IProfiler already registered for this ConnectionMultiplexer");
this.profiler = profiler;
......@@ -44,8 +38,8 @@ public void RegisterProfiler(IProfiler profiler)
public void BeginProfiling(object forContext)
{
if (profiler == null) throw new InvalidOperationException("Cannot begin profiling if no IProfiler has been registered with RegisterProfiler");
if (forContext == null) throw new ArgumentNullException("forContext");
if (forContext is WeakReference) throw new ArgumentException("Context object cannot be a WeakReference", "forContext");
if (forContext == null) throw new ArgumentNullException(nameof(forContext));
if (forContext is WeakReference) throw new ArgumentException("Context object cannot be a WeakReference", nameof(forContext));
if (!profiledCommands.TryCreate(forContext))
{
......@@ -61,7 +55,7 @@ public void BeginProfiling(object forContext)
public ProfiledCommandEnumerable FinishProfiling(object forContext, bool allowCleanupSweep = true)
{
if (profiler == null) throw new InvalidOperationException("Cannot begin profiling if no IProfiler has been registered with RegisterProfiler");
if (forContext == null) throw new ArgumentNullException("forContext");
if (forContext == null) throw new ArgumentNullException(nameof(forContext));
ProfiledCommandEnumerable ret;
if (!profiledCommands.TryRemove(forContext, out ret))
......
......@@ -2,20 +2,20 @@
{
partial class ConnectionMultiplexer
{
internal SocketManager SocketManager { get { return socketManager; } }
internal SocketManager SocketManager => socketManager;
private SocketManager socketManager;
private bool ownsSocketManager;
partial void OnCreateReaderWriter(ConfigurationOptions configuration)
{
this.ownsSocketManager = configuration.SocketManager == null;
this.socketManager = configuration.SocketManager ?? new SocketManager(ClientName, configuration.HighPrioritySocketThreads);
ownsSocketManager = configuration.SocketManager == null;
socketManager = configuration.SocketManager ?? new SocketManager(ClientName, configuration.HighPrioritySocketThreads);
}
partial void OnCloseReaderWriter()
{
if (ownsSocketManager && socketManager != null) socketManager.Dispose();
if (ownsSocketManager) socketManager?.Dispose();
socketManager = null;
}
......@@ -30,7 +30,5 @@ internal void RequestWrite(PhysicalBridge bridge, bool forced)
}
}
partial void OnWriterCreated();
}
}
......@@ -17,7 +17,7 @@ public static long GetAllocationCount()
}
static partial void OnAllocated()
{
Interlocked.Increment(ref ResultBox.allocations);
Interlocked.Increment(ref allocations);
}
}
partial interface IServer
......@@ -103,17 +103,17 @@ partial class ServerEndPoint
internal void SimulateConnectionFailure()
{
var tmp = interactive;
if (tmp != null) tmp.SimulateConnectionFailure();
tmp?.SimulateConnectionFailure();
tmp = subscription;
if (tmp != null) tmp.SimulateConnectionFailure();
tmp?.SimulateConnectionFailure();
}
internal string ListPending(int maxCount)
{
var sb = new StringBuilder();
var tmp = interactive;
if (tmp != null) tmp.ListPending(sb, maxCount);
tmp?.ListPending(sb, maxCount);
tmp = subscription;
if (tmp != null) tmp.ListPending(sb, maxCount);
tmp?.ListPending(sb, maxCount);
return sb.ToString();
}
}
......@@ -231,12 +231,11 @@ partial class PhysicalBridge
{
internal void SimulateConnectionFailure()
{
if (!multiplexer.RawConfig.AllowAdmin)
if (!Multiplexer.RawConfig.AllowAdmin)
{
throw ExceptionFactory.AdminModeNotEnabled(multiplexer.IncludeDetailInExceptions, RedisCommand.DEBUG, null, serverEndPoint); // close enough
throw ExceptionFactory.AdminModeNotEnabled(Multiplexer.IncludeDetailInExceptions, RedisCommand.DEBUG, null, ServerEndPoint); // close enough
}
var tmp = physical;
if (tmp != null) tmp.RecordConnectionFailed(ConnectionFailureType.SocketFailure);
physical?.RecordConnectionFailed(ConnectionFailureType.SocketFailure);
}
internal void ListPending(StringBuilder sb, int maxCount)
{
......@@ -248,20 +247,18 @@ partial class PhysicalConnection
{
partial void OnDebugAbort()
{
if (!multiplexer.AllowConnect)
if (!Multiplexer.AllowConnect)
{
throw new RedisConnectionException(ConnectionFailureType.InternalFailure, "debugging");
}
}
bool ISocketCallback.IgnoreConnect
{
get { return multiplexer.IgnoreConnect; }
}
bool ISocketCallback.IgnoreConnect => Multiplexer.IgnoreConnect;
private volatile static bool emulateStaleConnection;
private static volatile bool emulateStaleConnection;
public static bool EmulateStaleConnection
{ get
{
get
{
return emulateStaleConnection;
}
......
......@@ -16,6 +16,7 @@ public sealed class EndPointCollection : Collection<EndPoint>
public EndPointCollection() : base()
{
}
/// <summary>
/// Create a new EndPointCollection
/// </summary>
......@@ -63,16 +64,14 @@ public void Add(IPAddress host, int port)
{
Add(new IPEndPoint(host, port));
}
/// <summary>
/// See Collection&lt;T&gt;.InsertItem()
/// </summary>
protected override void InsertItem(int index, EndPoint item)
{
if (item == null) throw new ArgumentNullException("item");
if (Contains(item)) throw new ArgumentException("EndPoints must be unique", "item");
if (item == null) throw new ArgumentNullException(nameof(item));
if (Contains(item)) throw new ArgumentException("EndPoints must be unique", nameof(item));
base.InsertItem(index, item);
}
/// <summary>
......@@ -80,7 +79,7 @@ protected override void InsertItem(int index, EndPoint item)
/// </summary>
protected override void SetItem(int index, EndPoint item)
{
if (item == null) throw new ArgumentNullException("item");
if (item == null) throw new ArgumentNullException(nameof(item));
int existingIndex;
try
{
......@@ -90,7 +89,7 @@ protected override void SetItem(int index, EndPoint item)
// mono has a nasty bug in DnsEndPoint.Equals; if they do bad things here: sorry, I can't help
existingIndex = -1;
}
if (existingIndex >= 0 && existingIndex != index) throw new ArgumentException("EndPoints must be unique", "item");
if (existingIndex >= 0 && existingIndex != index) throw new ArgumentException("EndPoints must be unique", nameof(item));
base.SetItem(index, item);
}
......@@ -100,22 +99,16 @@ internal void SetDefaultPorts(int defaultPort)
{
var endpoint = this[i];
var dns = endpoint as DnsEndPoint;
if (dns != null)
if (dns?.Port == 0)
{
if (dns.Port == 0)
{
this[i] = new DnsEndPoint(dns.Host, defaultPort, dns.AddressFamily);
continue;
}
this[i] = new DnsEndPoint(dns.Host, defaultPort, dns.AddressFamily);
continue;
}
var ip = endpoint as IPEndPoint;
if (ip != null)
if (ip?.Port == 0)
{
if (ip.Port == 0)
{
this[i] = new IPEndPoint(ip.Address, defaultPort);
continue;
}
this[i] = new IPEndPoint(ip.Address, defaultPort);
continue;
}
}
}
......
......@@ -9,28 +9,25 @@ namespace StackExchange.Redis
/// </summary>
public class EndPointEventArgs : EventArgs, ICompletable
{
private readonly EndPoint endpoint;
private readonly EventHandler<EndPointEventArgs> handler;
private readonly object sender;
internal EndPointEventArgs(EventHandler<EndPointEventArgs> handler, object sender, EndPoint endpoint)
{
this.handler = handler;
this.sender = sender;
this.endpoint = endpoint;
EndPoint = endpoint;
}
/// <summary>
/// The endpoint involved in this event (this can be null)
/// </summary>
public EndPoint EndPoint
{
get { return endpoint; }
}
public EndPoint EndPoint { get; }
void ICompletable.AppendStormLog(StringBuilder sb)
{
sb.Append("event, endpoint: ");
if (endpoint == null) sb.Append("n/a");
else sb.Append(Format.ToString(endpoint));
if (EndPoint == null) sb.Append("n/a");
else sb.Append(Format.ToString(EndPoint));
}
bool ICompletable.TryComplete(bool isAsync)
......
......@@ -90,7 +90,7 @@ internal static string ToString(EndPoint endpoint)
if (ip.Port == 0) return ip.Address.ToString();
return ip.Address.ToString() + ":" + Format.ToString(ip.Port);
}
return endpoint == null ? "" : endpoint.ToString();
return endpoint?.ToString() ?? "";
}
internal static string ToStringHostOnly(EndPoint endpoint)
{
......@@ -118,7 +118,7 @@ internal static bool TryGetHostPort(EndPoint endpoint, out string host, out int
port = ip.Port;
return true;
}
else if (endpoint is DnsEndPoint)
if (endpoint is DnsEndPoint)
{
DnsEndPoint dns = (DnsEndPoint)endpoint;
host = dns.Host;
......
......@@ -22,11 +22,12 @@ public HashEntry(RedisValue name, RedisValue value)
/// <summary>
/// The name of the hash field
/// </summary>
public RedisValue Name { get { return name; } }
public RedisValue Name => name;
/// <summary>
/// The value of the hash field
/// </summary>
public RedisValue Value{ get { return value; } }
public RedisValue Value => value;
/// <summary>
/// The name of the hash field
......@@ -79,7 +80,7 @@ public override bool Equals(object obj)
/// </summary>
public bool Equals(HashEntry value)
{
return this.name == value.name && this.value == value.value;
return name == value.name && this.value == value.value;
}
/// <summary>
/// Compares two values for equality
......
......@@ -9,31 +9,31 @@ namespace StackExchange.Redis
/// </summary>
public sealed class HashSlotMovedEventArgs : EventArgs, ICompletable
{
private readonly int hashSlot;
private readonly EndPoint old, @new;
private readonly object sender;
private readonly EventHandler<HashSlotMovedEventArgs> handler;
/// <summary>
/// The hash-slot that was relocated
/// </summary>
public int HashSlot { get { return hashSlot; } }
public int HashSlot { get; }
/// <summary>
/// The old endpoint for this hash-slot (if known)
/// </summary>
public EndPoint OldEndPoint { get { return old; } }
public EndPoint OldEndPoint { get; }
/// <summary>
/// The new endpoint for this hash-slot (if known)
/// </summary>
public EndPoint NewEndPoint { get { return @new; } }
public EndPoint NewEndPoint { get; }
internal HashSlotMovedEventArgs(EventHandler<HashSlotMovedEventArgs> handler, object sender,
int hashSlot, EndPoint old, EndPoint @new)
{
this.handler = handler;
this.sender = sender;
this.hashSlot = hashSlot;
this.old = old;
this.@new = @new;
HashSlot = hashSlot;
OldEndPoint = old;
NewEndPoint = @new;
}
bool ICompletable.TryComplete(bool isAsync)
......@@ -43,7 +43,7 @@ bool ICompletable.TryComplete(bool isAsync)
void ICompletable.AppendStormLog(StringBuilder sb)
{
sb.Append("event, slot-moved: ").Append(hashSlot);
sb.Append("event, slot-moved: ").Append(HashSlot);
}
}
}
......@@ -909,21 +909,20 @@ public interface IDatabaseAsync : IRedisAsync
/// </summary>
public struct RedisValueWithExpiry
{
private readonly TimeSpan? expiry;
private readonly RedisValue value;
internal RedisValueWithExpiry(RedisValue value, TimeSpan? expiry)
{
this.value = value;
this.expiry = expiry;
Value = value;
Expiry = expiry;
}
/// <summary>
/// The expiry of this record
/// </summary>
public TimeSpan? Expiry { get { return expiry; } }
public TimeSpan? Expiry { get; }
/// <summary>
/// The value of this record
/// </summary>
public RedisValue Value { get { return value; } }
public RedisValue Value { get; }
}
}
......@@ -3,6 +3,7 @@
namespace StackExchange.Redis
{
internal interface IMultiMessage
{ IEnumerable<Message> GetMessages(PhysicalConnection connection);
{
IEnumerable<Message> GetMessages(PhysicalConnection connection);
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace StackExchange.Redis
{
......
......@@ -43,7 +43,7 @@ internal class IgnoreNamePrefixAttribute : Attribute
{
public IgnoreNamePrefixAttribute(bool ignoreEntireMethod = false)
{
this.IgnoreEntireMethod = ignoreEntireMethod;
IgnoreEntireMethod = ignoreEntireMethod;
}
public bool IgnoreEntireMethod { get; private set; }
......
......@@ -9,55 +9,41 @@ namespace StackExchange.Redis
/// </summary>
public class InternalErrorEventArgs : EventArgs, ICompletable
{
private readonly ConnectionType connectionType;
private readonly EndPoint endpoint;
private readonly Exception exception;
private readonly EventHandler<InternalErrorEventArgs> handler;
private readonly string origin;
private readonly object sender;
internal InternalErrorEventArgs(EventHandler<InternalErrorEventArgs> handler, object sender, EndPoint endpoint, ConnectionType connectionType, Exception exception, string origin)
{
this.handler = handler;
this.sender = sender;
this.endpoint = endpoint;
this.connectionType = connectionType;
this.exception = exception;
this.origin = origin;
EndPoint = endpoint;
ConnectionType = connectionType;
Exception = exception;
Origin = origin;
}
/// <summary>
/// Gets the connection-type of the failing connection
/// </summary>
public ConnectionType ConnectionType
{
get { return connectionType; }
}
public ConnectionType ConnectionType { get; }
/// <summary>
/// Gets the failing server-endpoint (this can be null)
/// </summary>
public EndPoint EndPoint
{
get { return endpoint; }
}
public EndPoint EndPoint { get; }
/// <summary>
/// Gets the exception if available (this can be null)
/// </summary>
public Exception Exception
{
get { return exception; }
}
public Exception Exception { get; }
/// <summary>
/// The underlying origin of the error
/// </summary>
public string Origin
{
get { return origin; }
}
public string Origin { get; }
void ICompletable.AppendStormLog(StringBuilder sb)
{
sb.Append("event, internal-error: ").Append(origin);
if (endpoint != null) sb.Append(", ").Append(Format.ToString(endpoint));
sb.Append("event, internal-error: ").Append(Origin);
if (EndPoint != null) sb.Append(", ").Append(Format.ToString(EndPoint));
}
bool ICompletable.TryComplete(bool isAsync)
......
using System;
using System.Text.RegularExpressions;
using System.Text.RegularExpressions;
#if CORE_CLR
using System;
#endif
namespace StackExchange.Redis
{
......
......@@ -2,14 +2,13 @@
{
internal sealed class BatchWrapper : WrapperBase<IBatch>, IBatch
{
public BatchWrapper(IBatch inner, byte[] prefix)
: base(inner, prefix)
public BatchWrapper(IBatch inner, byte[] prefix) : base(inner, prefix)
{
}
public void Execute()
{
this.Inner.Execute();
Inner.Execute();
}
}
}
......@@ -41,12 +41,12 @@ public static IDatabase WithKeyPrefix(this IDatabase database, RedisKey keyPrefi
{
if (database == null)
{
throw new ArgumentNullException("database");
throw new ArgumentNullException(nameof(database));
}
if (keyPrefix.IsNull)
{
throw new ArgumentNullException("keyPrefix");
throw new ArgumentNullException(nameof(keyPrefix));
}
if (keyPrefix.IsEmpty)
......
......@@ -4,29 +4,28 @@ namespace StackExchange.Redis.KeyspaceIsolation
{
internal sealed class TransactionWrapper : WrapperBase<ITransaction>, ITransaction
{
public TransactionWrapper(ITransaction inner, byte[] prefix)
: base(inner, prefix)
public TransactionWrapper(ITransaction inner, byte[] prefix) : base(inner, prefix)
{
}
public ConditionResult AddCondition(Condition condition)
{
return this.Inner.AddCondition(condition == null ? null : condition.MapKeys(GetMapFunction()));
return Inner.AddCondition(condition?.MapKeys(GetMapFunction()));
}
public bool Execute(CommandFlags flags = CommandFlags.None)
{
return this.Inner.Execute(flags);
return Inner.Execute(flags);
}
public Task<bool> ExecuteAsync(CommandFlags flags = CommandFlags.None)
{
return this.Inner.ExecuteAsync(flags);
return Inner.ExecuteAsync(flags);
}
public void Execute()
{
this.Inner.Execute();
Inner.Execute();
}
}
}
......@@ -37,7 +37,7 @@ public sealed class LuaScript
// Arguments are in the order they have to passed to the script in
internal string[] Arguments { get; private set; }
bool HasArguments { get { return Arguments != null && Arguments.Length > 0; } }
bool HasArguments => Arguments != null && Arguments.Length > 0;
Hashtable ParameterMappers;
......@@ -106,7 +106,7 @@ internal void ExtractParameters(object ps, RedisKey? keyPrefix, out RedisKey[] k
{
if (HasArguments)
{
if (ps == null) throw new ArgumentNullException("ps", "Script requires parameters");
if (ps == null) throw new ArgumentNullException(nameof(ps), "Script requires parameters");
var psType = ps.GetType();
var mapper = (Func<object, RedisKey?, ScriptParameterMapper.ScriptParameters>)ParameterMappers[psType];
......@@ -179,7 +179,7 @@ public LoadedLuaScript Load(IServer server, CommandFlags flags = CommandFlags.No
{
if (flags.HasFlag(CommandFlags.FireAndForget))
{
throw new ArgumentOutOfRangeException("flags", "Loading a script cannot be FireAndForget");
throw new ArgumentOutOfRangeException(nameof(flags), "Loading a script cannot be FireAndForget");
}
var hash = server.ScriptLoad(ExecutableScript, flags);
......@@ -197,7 +197,7 @@ public async Task<LoadedLuaScript> LoadAsync(IServer server, CommandFlags flags
{
if (flags.HasFlag(CommandFlags.FireAndForget))
{
throw new ArgumentOutOfRangeException("flags", "Loading a script cannot be FireAndForget");
throw new ArgumentOutOfRangeException(nameof(flags), "Loading a script cannot be FireAndForget");
}
var hash = await server.ScriptLoadAsync(ExecutableScript, flags);
......@@ -228,12 +228,12 @@ public sealed class LoadedLuaScript
/// <summary>
/// The original script that was used to create this LoadedLuaScript.
/// </summary>
public string OriginalScript { get { return Original.OriginalScript; } }
public string OriginalScript => Original.OriginalScript;
/// <summary>
/// The script that will actually be sent to Redis for execution.
/// </summary>
public string ExecutableScript { get { return Original.ExecutableScript; } }
public string ExecutableScript => Original.ExecutableScript;
/// <summary>
/// The SHA1 hash of ExecutableScript.
......
......@@ -9,7 +9,7 @@ sealed partial class MessageQueue
regular = new Queue<Message>(),
high = new Queue<Message>();
public object SyncLock { get { return regular; } }
public object SyncLock => regular;
public Message Dequeue()
{
......
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace StackExchange.Redis
{
......@@ -140,7 +137,7 @@ public int GetHashCode(ProfileContextCell obj)
private long lastCleanupSweep;
private ConcurrentDictionary<ProfileContextCell, ConcurrentProfileStorageCollection> profiledCommands;
public int ContextCount { get { return profiledCommands.Count; } }
public int ContextCount => profiledCommands.Count;
public ProfileContextTracker()
{
......
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace StackExchange.Redis
{
class ProfileStorage : IProfiledCommand
{
#region IProfiledCommand Impl
public EndPoint EndPoint
{
get { return Server.EndPoint; }
}
public EndPoint EndPoint => Server.EndPoint;
public int Db
{
get { return Message.Db; }
}
public int Db => Message.Db;
public string Command
{
get { return Message.Command.ToString(); }
}
public string Command => Message.Command.ToString();
public CommandFlags Flags
{
get { return Message.Flags; }
}
public CommandFlags Flags => Message.Flags;
public DateTime CommandCreated
{
get { return MessageCreatedDateTime; }
}
public DateTime CommandCreated => MessageCreatedDateTime;
public TimeSpan CreationToEnqueued
{
get { return TimeSpan.FromTicks(EnqueuedTimeStamp - MessageCreatedTimeStamp); }
}
public TimeSpan CreationToEnqueued => TimeSpan.FromTicks(EnqueuedTimeStamp - MessageCreatedTimeStamp);
public TimeSpan EnqueuedToSending
{
get { return TimeSpan.FromTicks(RequestSentTimeStamp - EnqueuedTimeStamp); }
}
public TimeSpan EnqueuedToSending => TimeSpan.FromTicks(RequestSentTimeStamp - EnqueuedTimeStamp);
public TimeSpan SentToResponse
{
get { return TimeSpan.FromTicks(ResponseReceivedTimeStamp - RequestSentTimeStamp); }
}
public TimeSpan SentToResponse => TimeSpan.FromTicks(ResponseReceivedTimeStamp - RequestSentTimeStamp);
public TimeSpan ResponseToCompletion
{
get { return TimeSpan.FromTicks(CompletedTimeStamp - ResponseReceivedTimeStamp); }
}
public TimeSpan ResponseToCompletion => TimeSpan.FromTicks(CompletedTimeStamp - ResponseReceivedTimeStamp);
public TimeSpan ElapsedTime
{
get { return TimeSpan.FromTicks(CompletedTimeStamp - MessageCreatedTimeStamp); }
}
public TimeSpan ElapsedTime => TimeSpan.FromTicks(CompletedTimeStamp - MessageCreatedTimeStamp);
public IProfiledCommand RetransmissionOf
{
get { return OriginalProfiling; }
}
public IProfiledCommand RetransmissionOf => OriginalProfiling;
public RetransmissionReasonType? RetransmissionReason { get; }
public RetransmissionReasonType? RetransmissionReason
{
get { return Reason; }
}
#endregion
public ProfileStorage NextElement { get; set; }
......@@ -79,7 +39,6 @@ public IProfiledCommand RetransmissionOf
private Message Message;
private ServerEndPoint Server;
private ProfileStorage OriginalProfiling;
private RetransmissionReasonType? Reason;
private DateTime MessageCreatedDateTime;
private long MessageCreatedTimeStamp;
......@@ -95,7 +54,7 @@ private ProfileStorage(ConcurrentProfileStorageCollection pushTo, ServerEndPoint
PushToWhenFinished = pushTo;
OriginalProfiling = resentFor;
Server = server;
Reason = reason;
RetransmissionReason = reason;
}
public static ProfileStorage NewWithContext(ConcurrentProfileStorageCollection pushTo, ServerEndPoint server)
......@@ -159,30 +118,17 @@ public void SetCompleted()
public override string ToString()
{
return
string.Format(
@"EndPoint = {0}
Db = {1}
Command = {2}
CommandCreated = {3:u}
CreationToEnqueued = {4}
EnqueuedToSending = {5}
SentToResponse = {6}
ResponseToCompletion = {7}
ElapsedTime = {8}
Flags = {9}
RetransmissionOf = ({10})",
EndPoint,
Db,
Command,
CommandCreated,
CreationToEnqueued,
EnqueuedToSending,
SentToResponse,
ResponseToCompletion,
ElapsedTime,
Flags,
RetransmissionOf
);
$@"EndPoint = {EndPoint}
Db = {Db}
Command = {Command}
CommandCreated = {CommandCreated:u}
CreationToEnqueued = {CreationToEnqueued}
EnqueuedToSending = {EnqueuedToSending}
SentToResponse = {SentToResponse}
ResponseToCompletion = {ResponseToCompletion}
ElapsedTime = {ElapsedTime}
Flags = {Flags}
RetransmissionOf = ({RetransmissionOf})";
}
}
}
......@@ -11,7 +11,6 @@ internal struct RawResult
public static readonly RawResult Nil = new RawResult();
private static readonly byte[] emptyBlob = new byte[0];
private readonly int offset, count;
private readonly ResultType resultType;
private Array arr;
public RawResult(ResultType resultType, byte[] buffer, int offset, int count)
{
......@@ -23,29 +22,30 @@ public RawResult(ResultType resultType, byte[] buffer, int offset, int count)
case ResultType.BulkString:
break;
default:
throw new ArgumentOutOfRangeException("resultType");
throw new ArgumentOutOfRangeException(nameof(resultType));
}
this.resultType = resultType;
this.arr = buffer;
Type = resultType;
arr = buffer;
this.offset = offset;
this.count = count;
}
public RawResult(RawResult[] arr)
{
if (arr == null) throw new ArgumentNullException("arr");
this.resultType = ResultType.MultiBulk;
this.offset = 0;
this.count = arr.Length;
if (arr == null) throw new ArgumentNullException(nameof(arr));
Type = ResultType.MultiBulk;
offset = 0;
count = arr.Length;
this.arr = arr;
}
public bool HasValue { get { return resultType != ResultType.None; } }
public bool HasValue => Type != ResultType.None;
public bool IsError { get { return resultType == ResultType.Error; } }
public bool IsError => Type == ResultType.Error;
public ResultType Type { get { return resultType; } }
internal bool IsNull { get { return arr == null; } }
public ResultType Type { get; }
internal bool IsNull => arr == null;
public override string ToString()
{
......@@ -53,23 +53,23 @@ public override string ToString()
{
return "(null)";
}
switch (resultType)
switch (Type)
{
case ResultType.SimpleString:
case ResultType.Integer:
case ResultType.Error:
return string.Format("{0}: {1}", resultType, GetString());
return $"{Type}: {GetString()}";
case ResultType.BulkString:
return string.Format("{0}: {1} bytes", resultType, count);
return $"{Type}: {count} bytes";
case ResultType.MultiBulk:
return string.Format("{0}: {1} items", resultType, count);
return $"{Type}: {count} items";
default:
return "(unknown)";
}
}
internal RedisChannel AsRedisChannel(byte[] channelPrefix, RedisChannel.PatternMode mode)
{
switch (resultType)
switch (Type)
{
case ResultType.SimpleString:
case ResultType.BulkString:
......@@ -87,24 +87,24 @@ internal RedisChannel AsRedisChannel(byte[] channelPrefix, RedisChannel.PatternM
}
return default(RedisChannel);
default:
throw new InvalidCastException("Cannot convert to RedisChannel: " + resultType);
throw new InvalidCastException("Cannot convert to RedisChannel: " + Type);
}
}
internal RedisKey AsRedisKey()
{
switch (resultType)
switch (Type)
{
case ResultType.SimpleString:
case ResultType.BulkString:
return (RedisKey)GetBlob();
default:
throw new InvalidCastException("Cannot convert to RedisKey: " + resultType);
throw new InvalidCastException("Cannot convert to RedisKey: " + Type);
}
}
internal RedisValue AsRedisValue()
{
switch (resultType)
switch (Type)
{
case ResultType.Integer:
long i64;
......@@ -114,12 +114,12 @@ internal RedisValue AsRedisValue()
case ResultType.BulkString:
return (RedisValue)GetBlob();
}
throw new InvalidCastException("Cannot convert to RedisValue: " + resultType);
throw new InvalidCastException("Cannot convert to RedisValue: " + Type);
}
internal unsafe bool IsEqual(byte[] expected)
{
if (expected == null) throw new ArgumentNullException("expected");
if (expected == null) throw new ArgumentNullException(nameof(expected));
if (expected.Length != count) return false;
var actual = arr as byte[];
if (actual == null) return false;
......@@ -146,7 +146,7 @@ internal unsafe bool IsEqual(byte[] expected)
internal bool AssertStarts(byte[] expected)
{
if (expected == null) throw new ArgumentNullException("expected");
if (expected == null) throw new ArgumentNullException(nameof(expected));
if (expected.Length > count) return false;
var actual = arr as byte[];
if (actual == null) return false;
......@@ -171,7 +171,7 @@ internal byte[] GetBlob()
internal bool GetBoolean()
{
if (this.count != 1) throw new InvalidCastException();
if (count != 1) throw new InvalidCastException();
byte[] actual = arr as byte[];
if (actual == null) throw new InvalidCastException();
switch (actual[offset])
......
......@@ -16,7 +16,8 @@ internal RedisBase(ConnectionMultiplexer multiplexer, object asyncState)
this.asyncState = asyncState;
}
ConnectionMultiplexer IRedisAsync.Multiplexer { get { return multiplexer; } }
ConnectionMultiplexer IRedisAsync.Multiplexer => multiplexer;
public virtual TimeSpan Ping(CommandFlags flags = CommandFlags.None)
{
var msg = GetTimerMessage(flags);
......@@ -163,14 +164,14 @@ internal abstract class CursorEnumerable<T> : IEnumerable<T>, IScanningCursor
protected CursorEnumerable(RedisBase redis, ServerEndPoint server, int db, int pageSize, long cursor, int pageOffset, CommandFlags flags)
{
if (pageOffset < 0) throw new ArgumentOutOfRangeException("pageOffset");
if (pageOffset < 0) throw new ArgumentOutOfRangeException(nameof(pageOffset));
this.redis = redis;
this.server = server;
this.db = db;
this.pageSize = pageSize;
this.flags = flags;
this.initialCursor = cursor;
this.initialOffset = pageOffset;
initialCursor = cursor;
initialOffset = pageOffset;
}
public IEnumerator<T> GetEnumerator()
......@@ -187,8 +188,8 @@ internal struct ScanResult
public readonly T[] Values;
public ScanResult(long cursor, T[] values)
{
this.Cursor = cursor;
this.Values = values;
Cursor = cursor;
Values = values;
}
}
......@@ -199,12 +200,12 @@ public ScanResult(long cursor, T[] values)
protected ScanResult GetNextPageSync(IScanningCursor obj, long cursor)
{
this.activeCursor = obj;
activeCursor = obj;
return redis.ExecuteSync(CreateMessage(cursor), Processor, server);
}
protected Task<ScanResult> GetNextPageAsync(IScanningCursor obj, long cursor)
{
this.activeCursor = obj;
activeCursor = obj;
return redis.ExecuteAsync(CreateMessage(cursor), Processor, server);
}
protected ScanResult Wait(Task<ScanResult> pending)
......@@ -217,21 +218,15 @@ class CursorEnumerator : IEnumerator<T>, IScanningCursor
private CursorEnumerable<T> parent;
public CursorEnumerator(CursorEnumerable<T> parent)
{
if (parent == null) throw new ArgumentNullException("parent");
if (parent == null) throw new ArgumentNullException(nameof(parent));
this.parent = parent;
Reset();
}
public T Current
{
get { return page[pageIndex]; }
}
public T Current => page[pageIndex];
void IDisposable.Dispose() { parent = null; state = State.Disposed; }
object System.Collections.IEnumerator.Current
{
get { return page[pageIndex]; }
}
object System.Collections.IEnumerator.Current => page[pageIndex];
private void LoadNextPageAsync()
{
......@@ -322,34 +317,23 @@ public void Reset()
pending = null;
}
long IScanningCursor.Cursor
{
get { return currentCursor; }
}
long IScanningCursor.Cursor => currentCursor;
int IScanningCursor.PageSize
{
get { return parent.pageSize; }
}
int IScanningCursor.PageSize => parent.pageSize;
int IScanningCursor.PageOffset
{
get { return pageIndex; }
}
int IScanningCursor.PageOffset => pageIndex;
}
long IScanningCursor.Cursor
{
get { var tmp = activeCursor; return tmp == null ? initialCursor : tmp.Cursor; }
get { var tmp = activeCursor; return tmp?.Cursor ?? initialCursor; }
}
int IScanningCursor.PageSize
{
get { return pageSize; }
}
int IScanningCursor.PageSize => pageSize;
int IScanningCursor.PageOffset
{
get { var tmp = activeCursor; return tmp == null ? initialOffset : tmp.PageOffset; }
get { var tmp = activeCursor; return tmp?.PageOffset ?? initialOffset; }
}
}
}
......
......@@ -8,7 +8,6 @@ namespace StackExchange.Redis
/// </summary>
public struct RedisChannel : IEquatable<RedisChannel>
{
internal static readonly RedisChannel[] EmptyArray = new RedisChannel[0];
private readonly byte[] value;
......@@ -30,7 +29,7 @@ public RedisChannel(string value, PatternMode mode) : this(value == null ? null
private RedisChannel(byte[] value, bool isPatternBased)
{
this.value = value;
this.IsPatternBased = isPatternBased;
IsPatternBased = isPatternBased;
}
private static bool DeterminePatternBased(byte[] value, PatternMode mode)
{
......@@ -41,27 +40,18 @@ private static bool DeterminePatternBased(byte[] value, PatternMode mode)
case PatternMode.Literal: return false;
case PatternMode.Pattern: return true;
default:
throw new ArgumentOutOfRangeException("mode");
throw new ArgumentOutOfRangeException(nameof(mode));
}
}
/// <summary>
/// Indicates whether the channel-name is either null or a zero-length value
/// </summary>
public bool IsNullOrEmpty
{
get
{
return value == null || value.Length == 0;
}
}
public bool IsNullOrEmpty => value == null || value.Length == 0;
internal bool IsNull
{
get { return value == null; }
}
internal bool IsNull => value == null;
internal byte[] Value { get { return value; } }
internal byte[] Value => value;
/// <summary>
/// Indicate whether two channel names are not equal
......@@ -150,15 +140,15 @@ public override bool Equals(object obj)
{
if (obj is RedisChannel)
{
return RedisValue.Equals(this.value, ((RedisChannel)obj).value);
return RedisValue.Equals(value, ((RedisChannel)obj).value);
}
if (obj is string)
{
return RedisValue.Equals(this.value, Encoding.UTF8.GetBytes((string)obj));
return RedisValue.Equals(value, Encoding.UTF8.GetBytes((string)obj));
}
if (obj is byte[])
{
return RedisValue.Equals(this.value, (byte[])obj);
return RedisValue.Equals(value, (byte[])obj);
}
return false;
}
......@@ -168,8 +158,8 @@ public override bool Equals(object obj)
/// </summary>
public bool Equals(RedisChannel other)
{
return this.IsPatternBased == other.IsPatternBased &&
RedisValue.Equals(this.value, other.value);
return IsPatternBased == other.IsPatternBased &&
RedisValue.Equals(value, other.value);
}
/// <summary>
......@@ -177,7 +167,7 @@ public bool Equals(RedisChannel other)
/// </summary>
public override int GetHashCode()
{
return RedisValue.GetHashCode(this.value) + (IsPatternBased ? 1 : 0);
return RedisValue.GetHashCode(value) + (IsPatternBased ? 1 : 0);
}
/// <summary>
......@@ -204,7 +194,7 @@ internal void AssertNotNull()
internal RedisChannel Clone()
{
byte[] clone = value == null ? null : (byte[])value.Clone();
byte[] clone = (byte[]) value?.Clone();
return clone;
}
......
......@@ -9,9 +9,7 @@ namespace StackExchange.Redis
/// </summary>
public sealed class RedisErrorEventArgs : EventArgs, ICompletable
{
private readonly EndPoint endpoint;
private readonly EventHandler<RedisErrorEventArgs> handler;
private readonly string message;
private readonly object sender;
internal RedisErrorEventArgs(
EventHandler<RedisErrorEventArgs> handler, object sender,
......@@ -19,29 +17,28 @@ public sealed class RedisErrorEventArgs : EventArgs, ICompletable
{
this.handler = handler;
this.sender = sender;
this.message = message;
this.endpoint = endpoint;
Message = message;
EndPoint = endpoint;
}
/// <summary>
/// The origin of the message
/// </summary>
public EndPoint EndPoint { get { return endpoint; } }
public EndPoint EndPoint { get; }
/// <summary>
/// The message from the server
/// </summary>
public string Message { get { return message; } }
public string Message { get; }
void ICompletable.AppendStormLog(StringBuilder sb)
{
sb.Append("event, error: ").Append(message);
sb.Append("event, error: ").Append(Message);
}
bool ICompletable.TryComplete(bool isAsync)
{
return ConnectionMultiplexer.TryCompleteHandler(handler, sender, this, isAsync);
}
}
}
......@@ -102,7 +102,7 @@ internal static RedisValue Get(Bitwise operation)
case Bitwise.Or: return OR;
case Bitwise.Xor: return XOR;
case Bitwise.Not: return NOT;
default: throw new ArgumentOutOfRangeException("operation");
default: throw new ArgumentOutOfRangeException(nameof(operation));
}
}
}
......
......@@ -23,7 +23,7 @@ public RedisTransaction(RedisDatabase wrapped, object asyncState) : base(wrapped
public ConditionResult AddCondition(Condition condition)
{
if (condition == null) throw new ArgumentNullException("condition");
if (condition == null) throw new ArgumentNullException(nameof(condition));
var commandMap = multiplexer.CommandMap;
if (conditions == null)
......@@ -146,7 +146,8 @@ public bool WasQueued
set { wasQueued = value; }
}
public Message Wrapped { get { return wrapped; } }
public Message Wrapped => wrapped;
internal override void WriteImpl(PhysicalConnection physical)
{
wrapped.WriteImpl(physical);
......@@ -189,12 +190,9 @@ public TransactionMessage(int db, CommandFlags flags, List<ConditionResult> cond
this.conditions = (conditions == null || conditions.Count == 0) ? NixConditions : conditions.ToArray();
}
public QueuedMessage[] InnerOperations { get { return operations; } }
public QueuedMessage[] InnerOperations => operations;
public bool IsAborted
{
get { return command != RedisCommand.EXEC; }
}
public bool IsAborted => command != RedisCommand.EXEC;
public override void AppendStormLog(StringBuilder sb)
{
......
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