Here are the examples of the csharp api System.Collections.Generic.IEnumerable.ToArray() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
25251 Examples
19
View Source File : CacheManager.cs
License : MIT License
Project Creator : 0ffffffffh
License : MIT License
Project Creator : 0ffffffffh
private static void CheckSetKeys(HashSet<string> set)
{
var keys = set.ToArray();
foreach (var key in keys)
{
if (!CacheManager.TryGetCachedResult<object>(key,out object val))
{
set.Remove(key);
}
}
}
19
View Source File : CacheManager.cs
License : MIT License
Project Creator : 0ffffffffh
License : MIT License
Project Creator : 0ffffffffh
public static string[] GetKeysFromKeySet(KeysetId setId)
{
HashSet<string> set;
var cksc = CacheSet.GetKeysetContext(setId,false);
if (cksc == null)
return null;
TryGetCachedResult<HashSet<string>>(cksc.CacheSetKey, out set);
if (set == null)
return null;
return set.ToArray();
}
19
View Source File : FileSystemUserData.cs
License : MIT License
Project Creator : 0x0ade
License : MIT License
Project Creator : 0x0ade
public override string[] GetRegistered()
=> LoadRaw<Global>(GlobalPath).UIDs.Values.ToArray();
19
View Source File : FileSystemUserData.cs
License : MIT License
Project Creator : 0x0ade
License : MIT License
Project Creator : 0x0ade
public override string[] GetAll()
=> !Directory.Exists(UserRoot) ? Dummy<string>.EmptyArray : Directory.GetDirectories(UserRoot).Select(name => Path.GetFileName(name)).ToArray();
19
View Source File : RCEPControl.cs
License : MIT License
Project Creator : 0x0ade
License : MIT License
Project Creator : 0x0ade
[RCEndpoint(false, "/channels", null, null, "Channel List", "Basic channel list.")]
public static void Channels(Frontend f, HttpRequestEventArgs c) {
IEnumerable<Channel> channels = f.Server.Channels.All;
if (!f.IsAuthorized(c))
channels = channels.Where(c => !c.IsPrivate);
f.RespondJSON(c, channels.Select(c => new {
c.ID, c.Name, c.IsPrivate,
Players = c.Players.Select(p => p.ID).ToArray()
}).ToArray());
}
19
View Source File : Ribbon.cs
License : GNU General Public License v3.0
Project Creator : 0dteam
License : GNU General Public License v3.0
Project Creator : 0dteam
public static string[] Headers(this MailItem mailItem, string name)
{
var headers = mailItem.HeaderLookup();
if (headers.Contains(name))
return headers[name].ToArray();
return new string[0];
}
19
View Source File : CelesteNetUtils.cs
License : MIT License
Project Creator : 0x0ade
License : MIT License
Project Creator : 0x0ade
private static Type[] _GetTypes()
=> _Getreplacedemblies().SelectMany(_GetTypes).ToArray();
19
View Source File : DataContext.cs
License : MIT License
Project Creator : 0x0ade
License : MIT License
Project Creator : 0x0ade
public T[] GetRefs<T>() where T : DataType<T>
=> GetRefs(DataTypeToID[typeof(T)]).Cast<T>().ToArray();
19
View Source File : ModelClassGenerator.cs
License : MIT License
Project Creator : 0x1000000
License : MIT License
Project Creator : 0x1000000
private static ClreplacedDeclarationSyntax GenerateClreplaced(SqModelMeta meta, bool rwClreplacedes, ClreplacedDeclarationSyntax? existingClreplaced)
{
ClreplacedDeclarationSyntax result;
MemberDeclarationSyntax[]? oldMembers = null;
Dictionary<string,SyntaxList<AttributeListSyntax>>? oldAttributes = null;
if (existingClreplaced != null)
{
result = existingClreplaced;
oldMembers = result.Members
.Where(md =>
{
if (md is ConstructorDeclarationSyntax)
{
return false;
}
if (md is IncompleteMemberSyntax)
{
return false;
}
if (md is PropertyDeclarationSyntax p)
{
if (meta.Properties.Any(mp => mp.Name == p.Identifier.ValueText))
{
if (p.AttributeLists.Count > 0)
{
oldAttributes ??= new Dictionary<string, SyntaxList<AttributeListSyntax>>();
oldAttributes.Add(p.Identifier.ValueText, p.AttributeLists);
}
return false;
}
}
if (md is MethodDeclarationSyntax method)
{
var name = method.Identifier.ValueText;
if (name.StartsWith("With") || AllMethods.Contains(name) || name.StartsWith(MethodNameGetReader + "For") || name.StartsWith(MethodNameGetUpdater + "For"))
{
return false;
}
}
if (md is ClreplacedDeclarationSyntax clreplacedDeclaration)
{
var name = clreplacedDeclaration.Identifier.ValueText;
if (name == meta.Name + ReaderClreplacedSuffix || name.StartsWith(meta.Name + ReaderClreplacedSuffix + "For"))
{
return false;
}
if (name == meta.Name + UpdaterClreplacedSuffix || name.StartsWith(meta.Name + UpdaterClreplacedSuffix + "For"))
{
return false;
}
}
return true;
})
.ToArray();
result = result.RemoveNodes(result.DescendantNodes().OfType<MemberDeclarationSyntax>(), SyntaxRemoveOptions.KeepNoTrivia)!;
}
else
{
result = SyntaxFactory.ClreplacedDeclaration(meta.Name)
.WithModifiers(existingClreplaced?.Modifiers ?? Modifiers(SyntaxKind.PublicKeyword));
}
result = result
.AddMembers(Constructors(meta)
.Concat(GenerateStaticFactory(meta))
.Concat(rwClreplacedes ? GenerateOrdinalStaticFactory(meta) : Array.Empty<MemberDeclarationSyntax>())
.Concat(Properties(meta, oldAttributes))
.Concat(GenerateWithModifiers(meta))
.Concat(GenerateGetColumns(meta))
.Concat(GenerateMapping(meta))
.Concat(rwClreplacedes ? GenerateReaderClreplaced(meta): Array.Empty<MemberDeclarationSyntax>())
.Concat(rwClreplacedes ? GenerateWriterClreplaced(meta) : Array.Empty<MemberDeclarationSyntax>())
.ToArray());
if (oldMembers != null && oldMembers.Length > 0)
{
result = result.AddMembers(oldMembers);
}
return result;
}
19
View Source File : SqlExtensions.cs
License : MIT License
Project Creator : 1100100
License : MIT License
Project Creator : 1100100
public static string Splice(this string sql, params Func<bool>[] conditions)
{
return sql.Splice(conditions.Select(p => p()).ToArray());
}
19
View Source File : FileOrganization.cs
License : Apache License 2.0
Project Creator : 0xFireball
License : Apache License 2.0
Project Creator : 0xFireball
public static DirectoryStructure BuildStructure(IEnumerable<StoredFile> files)
{
var dirStructure = new DirectoryStructure
{
Path = "/"
};
foreach (var file in files)
{
var pathSegments = GetPathSegments(file.ParentDirPath);
var targetPathSegmentCount = pathSegments.Length;
var parent = dirStructure;
for (int i = 0; i < targetPathSegmentCount; i++)
{
var currentSegment = pathSegments[i];
var currentFullPath = JoinPathSegments(pathSegments.Take(i + 1).ToArray());
DirectoryStructure nextChild;
var existingChild = parent.SubDirectories.Where(x => x.Path == currentFullPath).FirstOrDefault();
if (existingChild != null)
{
nextChild = existingChild;
}
else
{
// Create and add next directory
nextChild = new DirectoryStructure
{
Name = currentSegment,
Path = parent.Path + currentSegment + "/"
};
parent.SubDirectories.Add(nextChild);
}
parent = nextChild;
}
parent.Files.Add(file);
}
return dirStructure;
}
19
View Source File : Dumper.cs
License : MIT License
Project Creator : 13xforever
License : MIT License
Project Creator : 13xforever
public void DetectDisc(string inDir = "", Func<Dumper, string> outputDirFormatter = null)
{
outputDirFormatter ??= d => $"[{d.ProductCode}] {d.replacedle}";
string discSfbPath = null;
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
var drives = DriveInfo.GetDrives().Where(d => d.DriveType == DriveType.CDRom && d.IsReady);
if (string.IsNullOrEmpty(inDir))
{
foreach (var drive in drives)
{
discSfbPath = Path.Combine(drive.Name, "PS3_DISC.SFB");
if (!File.Exists(discSfbPath))
continue;
input = drive.Name;
Drive = drive.Name[0];
break;
}
}
else
{
discSfbPath = Path.Combine(inDir, "PS3_DISC.SFB");
if (File.Exists(discSfbPath))
{
input = Path.GetPathRoot(discSfbPath);
Drive = discSfbPath[0];
}
}
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
if (string.IsNullOrEmpty(inDir))
inDir = "/media";
discSfbPath = IOEx.GetFilepaths(inDir, "PS3_DISC.SFB", 2).FirstOrDefault();
if (!string.IsNullOrEmpty(discSfbPath))
input = Path.GetDirectoryName(discSfbPath);
}
else
throw new NotImplementedException("Current OS is not supported");
if (string.IsNullOrEmpty(input) || string.IsNullOrEmpty(discSfbPath))
throw new DriveNotFoundException("No valid PS3 disc was detected. Disc must be detected and mounted.");
Log.Info("Selected disc: " + input);
discSfbData = File.ReadAllBytes(discSfbPath);
var replacedleId = CheckDiscSfb(discSfbData);
var paramSfoPath = Path.Combine(input, "PS3_GAME", "PARAM.SFO");
if (!File.Exists(paramSfoPath))
throw new InvalidOperationException($"Specified folder is not a valid PS3 disc root (param.sfo is missing): {input}");
using (var stream = File.Open(paramSfoPath, FileMode.Open, FileAccess.Read, FileShare.Read))
ParamSfo = ParamSfo.ReadFrom(stream);
CheckParamSfo(ParamSfo);
if (replacedleId != ProductCode)
Log.Warn($"Product codes in ps3_disc.sfb ({replacedleId}) and in param.sfo ({ProductCode}) do not match");
// todo: maybe use discutils instead to read TOC as one block
var files = IOEx.GetFilepaths(input, "*", SearchOption.AllDirectories);
DiscFilenames = new List<string>();
var totalFilesize = 0L;
var rootLength = input.Length;
foreach (var f in files)
{
try { totalFilesize += new FileInfo(f).Length; } catch { }
DiscFilenames.Add(f.Substring(rootLength));
}
TotalFileSize = totalFilesize;
TotalFileCount = DiscFilenames.Count;
OutputDir = new string(outputDirFormatter(this).ToCharArray().Where(c => !InvalidChars.Contains(c)).ToArray());
Log.Debug($"Output: {OutputDir}");
}
19
View Source File : ConsulServiceDiscovery.cs
License : MIT License
Project Creator : 1100100
License : MIT License
Project Creator : 1100100
public async Task NodeMonitor(CancellationToken cancellationToken)
{
Logger.LogTrace("Start refresh service status,waiting for locking...");
using (await AsyncLock.LockAsync(cancellationToken))
{
if (cancellationToken.IsCancellationRequested)
return;
foreach (var service in ServiceNodes)
{
Logger.LogTrace($"Service {service.Key} refreshing...");
try
{
var healthNodes = await QueryServiceAsync(service.Key, cancellationToken);
if (cancellationToken.IsCancellationRequested)
break;
var leavedNodes = service.Value.Where(p => healthNodes.All(a => a.ServiceId != p.ServiceId))
.Select(p => p.ServiceId).ToArray();
if (leavedNodes.Any())
{
//RemoveNode(service.Key, leavedNodes);
if (!ServiceNodes.TryGetValue(service.Key, out var services)) return;
services.RemoveAll(p => leavedNodes.Any(n => n == p.ServiceId));
OnNodeLeave?.Invoke(service.Key, leavedNodes);
Logger.LogTrace($"These nodes are gone:{string.Join(",", leavedNodes)}");
}
var addedNodes = healthNodes.Where(p =>
service.Value.All(e => e.ServiceId != p.ServiceId)).Select(p =>
new ServiceNodeInfo(p.ServiceId, p.Address, p.Port, p.Weight, p.EnableTls, p.Meta))
.ToList();
if (addedNodes.Any())
{
//AddNode(service.Key, addedNodes);
if (ServiceNodes.TryGetValue(service.Key, out var services))
services.AddRange(addedNodes);
else
ServiceNodes.TryAdd(service.Key, addedNodes);
OnNodeJoin?.Invoke(service.Key, addedNodes);
Logger.LogTrace(
$"New nodes added:{string.Join(",", addedNodes.Select(p => p.ServiceId))}");
}
}
catch
{
// ignored
}
}
Logger.LogTrace("Complete refresh.");
}
}
19
View Source File : Entry.cs
License : GNU General Public License v3.0
Project Creator : 1330-Studios
License : GNU General Public License v3.0
Project Creator : 1330-Studios
[HarmonyPostfix]
public static void Postfix(ref Game __instance) {
var ms = ScriptableObjectSingleton<GameData>._instance.mapSet.Maps.items;
for (var i = 0; i < ms.Length; i++) {
ms[i].isDebug = ms[i].isBrowserOnly = false;
}
var impls = new MapImpl[] { BigFoot.VALUE, Daffodils.VALUE, Shipwreck.VALUE };
ScriptableObjectSingleton<GameData>._instance.mapSet.Maps.items = ms.AddAll(impls.Select(impl => impl.GetCreated()).ToArray());
}
19
View Source File : PkgChecker.cs
License : MIT License
Project Creator : 13xforever
License : MIT License
Project Creator : 13xforever
private static byte[] GetSha1Hmac(Span<byte> data, Span<byte> key)
{
if (key.Length != 0x40)
throw new ArgumentException(nameof(key));
var ipad = new byte[0x40];
var tmp = new byte[0x40 + 0x14]; // opad + hash(ipad + message)
for (var i = 0; i < ipad.Length; i++)
{
tmp[i] = (byte)(key[i] ^ 0x5c); // opad
ipad[i] = (byte)(key[i] ^ 0x36);
}
using (var sha1 = SHA1.Create())
{
sha1.TransformBlock(ipad.ToArray(), 0, ipad.Length, null, 0);
sha1.TransformFinalBlock(data.ToArray(), 0, data.Length);
Buffer.BlockCopy(sha1.Hash, 0, tmp, 0x40, 0x14);
}
using (var sha1 = SHA1.Create())
return sha1.ComputeHash(tmp);
}
19
View Source File : RedisDatabase.cs
License : MIT License
Project Creator : 17MKH
License : MIT License
Project Creator : 17MKH
public async Task DeleteByPrefix(string prefix)
{
var pageSize = 1000;
var pageOffset = 0;
var hasEnd = false;
while (!hasEnd)
{
var keys = GetKeysByPrefix(prefix, pageSize, pageOffset);
if (keys == null || !keys.Any())
{
hasEnd = true;
}
else
{
try
{
await _db.KeyDeleteAsync(keys.ToArray());
}
catch (RedisCommandException ex)
{
if (ex.Message.StartsWith("Multi-key operations must involve a single slot;"))
{
await Task.WhenAll(keys.Select(m => _db.KeyDeleteAsync(m)));
}
else
{
throw ex;
}
}
}
}
}
19
View Source File : InterfaceImplementation.cs
License : MIT License
Project Creator : 1996v
License : MIT License
Project Creator : 1996v
public static Type CreateType(Type interfaceType)
{
try
{
TypeBuilder typeBuilder = Impreplacedembly.DefineInterfaceImpType(interfaceType);
List<MemberInfo> allMembers = interfaceType.GetAllInterfaceMembers();
List<MethodInfo> propertyInfos = new List<MethodInfo>();
foreach (PropertyInfo prop in allMembers.OfType<PropertyInfo>())
{
Type propType = prop.PropertyType;
PropertyBuilder propBuilder = typeBuilder.DefineProperty(prop.Name, prop.Attributes, propType, Type.EmptyTypes);
MethodInfo iGetter = prop.GetMethod;
MethodInfo iSetter = prop.SetMethod;
if (iGetter != null)
{
propertyInfos.Add(iGetter);
}
if (iSetter != null)
{
propertyInfos.Add(iSetter);
}
if (prop.Name == "Item")
{
if (iGetter != null)
{
MethodAttributes accessor = iGetter.Attributes;
accessor &= ~MethodAttributes.Abstract;
MethodBuilder methBuilder = typeBuilder.DefineMethod(iGetter.Name, accessor, iGetter.ReturnType, iGetter.GetParameters().Select(e => e.ParameterType).ToArray());
ILGenerator il = methBuilder.GetILGenerator();
il.Emit(OpCodes.Newobj, typeof(NotImplementedException).GetConstructors()[0]);
il.Emit(OpCodes.Throw);
propBuilder.SetGetMethod(methBuilder);
}
if (iSetter != null)
{
MethodAttributes accessor = iSetter.Attributes;
accessor &= ~MethodAttributes.Abstract;
MethodBuilder methBuilder = typeBuilder.DefineMethod(iSetter.Name, accessor, iSetter.ReturnType, iSetter.GetParameters().Select(e => e.ParameterType).ToArray());
ILGenerator il = methBuilder.GetILGenerator();
il.Emit(OpCodes.Newobj, typeof(NotImplementedException).GetConstructors()[0]);
il.Emit(OpCodes.Throw);
propBuilder.SetSetMethod(methBuilder);
}
continue;
}
Func<FieldInfo> getBackingField;
{
FieldInfo backingField = null;
getBackingField =
() =>
{
if (backingField == null)
{
backingField = typeBuilder.DefineField("_" + prop.Name + "_" + Guid.NewGuid(), propType, FieldAttributes.Private);
}
return backingField;
};
}
if (iGetter != null)
{
MethodAttributes accessor = iGetter.Attributes;
accessor &= ~MethodAttributes.Abstract;
MethodBuilder methBuilder = typeBuilder.DefineMethod(iGetter.Name, accessor, propType, Type.EmptyTypes);
ILGenerator il = methBuilder.GetILGenerator();
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldfld, getBackingField());
il.Emit(OpCodes.Ret);
propBuilder.SetGetMethod(methBuilder);
}
if (iGetter != null || iSetter != null)
{
MethodAttributes accessor = iSetter != null ? iSetter.Attributes : MethodAttributes.Private;
string name = iSetter != null ? iSetter.Name : "set_" + prop.Name;
accessor &= ~MethodAttributes.Abstract;
MethodBuilder methBuilder = typeBuilder.DefineMethod(name, accessor, typeof(void), new[] { propType });
ILGenerator il = methBuilder.GetILGenerator();
if (iGetter != null)
{
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldarg_1);
il.Emit(OpCodes.Stfld, getBackingField());
il.Emit(OpCodes.Ret);
}
else
{
il.Emit(OpCodes.Ret);
}
propBuilder.SetSetMethod(methBuilder);
}
}
foreach (MethodInfo method in allMembers.OfType<MethodInfo>().Except(propertyInfos))
{
MethodBuilder methBuilder = typeBuilder.DefineMethod(method.Name, MethodAttributes.Private | MethodAttributes.HideBySig | MethodAttributes.NewSlot | MethodAttributes.Virtual | MethodAttributes.Final, method.ReturnType, method.GetParameters().Select(e => e.ParameterType).ToArray());
if (method.IsGenericMethod)
{
methBuilder.DefineGenericParameters(method.GetGenericArguments().Select(e => e.Name).ToArray());
}
ILGenerator il = methBuilder.GetILGenerator();
il.Emit(OpCodes.Newobj, typeof(NotImplementedException).GetConstructors()[0]);
il.Emit(OpCodes.Throw);
typeBuilder.DefineMethodOverride(methBuilder, method);
}
return typeBuilder.CreateTypeInfo();
}
catch
{
throw BssomSerializationTypeFormatterException.UnsupportedType(interfaceType);
}
}
19
View Source File : MQTTClient.cs
License : MIT License
Project Creator : 1iveowl
License : MIT License
Project Creator : 1iveowl
private IList<string> WrapTopicFiltersToString(IEnumerable<ITopicFilter> topicFilters)
{
return WrapTopicFilters(topicFilters).Select(x => x.Topic).ToArray();
}
19
View Source File : MQTTClient.cs
License : MIT License
Project Creator : 1iveowl
License : MIT License
Project Creator : 1iveowl
private static byte[][] UnwrapCertificates(IEnumerable<byte[]> certificates)
{
return certificates?.ToArray();
}
19
View Source File : HttpStreamParser.cs
License : MIT License
Project Creator : 1iveowl
License : MIT License
Project Creator : 1iveowl
internal async Task<IHttpRequestResponse> ParseAsync(Stream stream, CancellationToken ct)
{
_disposableParserCompletion = _parserDelegate.ParserCompletionObservable
.Subscribe(parserState =>
{
switch (parserState)
{
case ParserState.Start:
break;
case ParserState.Parsing:
break;
case ParserState.Completed:
break;
case ParserState.Failed:
HasParsingError = true;
break;
default:
throw new ArgumentOutOfRangeException(nameof(parserState), parserState, null);
}
},
ex => throw ex,
() =>
{
IsDone = true;
});
await Observable.While(
() => !HasParsingError && !IsDone,
Observable.FromAsync(() => ReadBytesAsync(stream, ct)))
.Catch<byte[], SimpleHttpListenerException>(ex =>
{
HasParsingError = true;
return Observable.Return(Enumerable.Empty<byte>().ToArray());
})
.Where(b => b != Enumerable.Empty<byte>().ToArray())
.Where(bSegment => bSegment.Length > 0)
.Select(b => new ArraySegment<byte>(b, 0, b.Length))
.Select(bSegment => _parser.Execute(bSegment));
_parser.Execute(default);
_parserDelegate.RequestResponse.MajorVersion = _parser.MajorVersion;
_parserDelegate.RequestResponse.MinorVersion = _parser.MinorVersion;
_parserDelegate.RequestResponse.ShouldKeepAlive = _parser.ShouldKeepAlive;
return _parserDelegate.RequestResponse;
}
19
View Source File : HttpStreamParser.cs
License : MIT License
Project Creator : 1iveowl
License : MIT License
Project Creator : 1iveowl
private async Task<byte[]> ReadBytesAsync(Stream stream, CancellationToken ct)
{
if (_parserDelegate.RequestResponse.IsEndOfRequest || HasParsingError)
{
IsDone = true;
return Enumerable.Empty<byte>().ToArray();
}
if (ct.IsCancellationRequested)
{
return Enumerable.Empty<byte>().ToArray();
}
var b = new byte[1];
if (stream == null)
{
throw new Exception("Read stream cannot be null.");
}
if (!stream.CanRead)
{
throw new Exception("Stream connection have been closed.");
}
var bytesRead = 0;
try
{
//Debug.WriteLine("Reading byte.");
bytesRead = await stream.ReadAsync(b, 0, 1, ct).ConfigureAwait(false);
//Debug.WriteLine("Done reading byte.");
}
catch (Exception ex)
{
HasParsingError = true;
throw new SimpleHttpListenerException("Unable to read network stream.", ex);
}
if (bytesRead < b.Length)
{
IsDone = true;
}
return _errorCorrections.Contains(ErrorCorrection.HeaderCompletionError)
? ResilientHeader(b)
: b;
}
19
View Source File : HttpStreamParser.cs
License : MIT License
Project Creator : 1iveowl
License : MIT License
Project Creator : 1iveowl
private byte[] ResilientHeader(byte[] b)
{
if (!IsDone)
{
_last4BytesCircularBuffer.Enqueue(b[0]);
}
else
{
if (!_parserDelegate.IsHeaderDone)
{
var last4Byte = _last4BytesCircularBuffer.ToArray();
if (last4Byte != _correctLast4BytesReversed)
{
byte[] returnNewLine = { 0x0d, 0x0a };
var correctionList = new List<byte>();
if (last4Byte[0] != _correctLast4BytesReversed[0] || last4Byte[1] != _correctLast4BytesReversed[1])
{
correctionList.Add(returnNewLine[0]);
correctionList.Add(returnNewLine[1]);
}
if (last4Byte[2] != _correctLast4BytesReversed[2] || last4Byte[3] != _correctLast4BytesReversed[3])
{
correctionList.Add(returnNewLine[0]);
correctionList.Add(returnNewLine[1]);
}
if (correctionList.Any())
{
return correctionList.Concat(correctionList.Select(x => x)).ToArray();
}
}
}
}
return b;
}
19
View Source File : VerifyHelper.cs
License : MIT License
Project Creator : 1996v
License : MIT License
Project Creator : 1996v
public static T Is<T>(this T actual, T expected)
{
if (expected == null)
{
replacedert.Null(actual);
return actual;
}
if (typeof(T) != typeof(string) && typeof(IEnumerable).GetTypeInfo().IsreplacedignableFrom(typeof(T)))
{
replacedert.Equal(
((IEnumerable)expected).Cast<object>().ToArray(),
((IEnumerable)actual).Cast<object>().ToArray());
return actual;
}
replacedert.Equal(expected, actual);
return actual;
}
19
View Source File : TcpClientEx.cs
License : MIT License
Project Creator : 1iveowl
License : MIT License
Project Creator : 1iveowl
private static async Task<byte[]> ReadOneByteAtTheTimeAsync(Stream stream, CancellationToken ct)
{
if (ct.IsCancellationRequested)
{
return Enumerable.Empty<byte>().ToArray();
}
var oneByteArray = new byte[1];
try
{
if (stream == null)
{
throw new Exception("Read stream cannot be null.");
}
if (!stream.CanRead)
{
throw new Exception("Stream connection have been closed.");
}
var bytesRead = await stream.ReadAsync(oneByteArray, 0, 1, ct).ConfigureAwait(false);
if (bytesRead < oneByteArray.Length)
{
throw new Exception("Stream connection aborted unexpectedly. Check connection and socket security version/TLS version).");
}
}
catch (ObjectDisposedException)
{
Debug.WriteLine("Ignoring Object Disposed Exception - This is an expected exception.");
return Enumerable.Empty<byte>().ToArray();
}
catch (IOException)
{
return Enumerable.Empty<byte>().ToArray();
}
return oneByteArray;
}
19
View Source File : Encrypter.cs
License : MIT License
Project Creator : 1y0n
License : MIT License
Project Creator : 1y0n
public static byte[] Decrypt(byte[] key, byte[] data)
{
return EncryptOutput(key, data).ToArray();
}
19
View Source File : Encrypter.cs
License : MIT License
Project Creator : 1y0n
License : MIT License
Project Creator : 1y0n
private static byte[] EncryptInitalize(byte[] key)
{
byte[] s = Enumerable.Range(0, 256)
.Select(i => (byte)i)
.ToArray();
for (int i = 0, j = 0; i < 256; i++)
{
j = (j + key[i % key.Length] + s[i]) & 255;
Swap(s, i, j);
}
return s;
}
19
View Source File : TcpClientEx.cs
License : MIT License
Project Creator : 1iveowl
License : MIT License
Project Creator : 1iveowl
private static IObservable<byte[]> CreateByteStreamObservable2(Stream stream, TcpClient tcpClient, CancellationToken ct)
{
var observableBytes = Observable.Create<byte[]>(obs =>
{
while (!ct.IsCancellationRequested)
{
if (ct.IsCancellationRequested || !tcpClient.Connected)
{
obs.OnNext(Enumerable.Empty<byte>().ToArray());
}
var oneByteArray = new byte[1];
try
{
if (stream == null)
{
throw new Exception("Read stream cannot be null.");
}
if (!stream.CanRead)
{
throw new Exception("Stream connection have been closed.");
}
var bytesRead = stream.ReadByte();
; //var bytesRead = await stream.ReadAsync(oneByteArray, 0, 1, ct).ConfigureAwait(false);
if (bytesRead < oneByteArray.Length)
{
throw new Exception("Stream connection aborted unexpectedly. Check connection and socket security version/TLS version).");
}
}
catch (ObjectDisposedException)
{
Debug.WriteLine("Ignoring Object Disposed Exception - This is an expected exception.");
obs.OnNext(Enumerable.Empty<byte>().ToArray());
}
catch (IOException)
{
obs.OnNext(Enumerable.Empty<byte>().ToArray());
}
obs.OnNext(oneByteArray);
}
obs.OnCompleted();
return Disposable.Empty;
});
return observableBytes.SubscribeOn(Scheduler.Default);
}
19
View Source File : Encrypter.cs
License : MIT License
Project Creator : 1y0n
License : MIT License
Project Creator : 1y0n
public static byte[] Encrypt(byte[] key, byte[] data)
{
return EncryptOutput(key, data).ToArray();
}
19
View Source File : JScriptGenerator.cs
License : MIT License
Project Creator : 1y0n
License : MIT License
Project Creator : 1y0n
public static string[] BinToBase64Lines(byte[] serialized_object)
{
int ofs = serialized_object.Length % 3;
if (ofs != 0)
{
int length = serialized_object.Length + (3 - ofs);
Array.Resize(ref serialized_object, length);
}
string base64 = Convert.ToBase64String(serialized_object, Base64FormattingOptions.InsertLineBreaks);
return base64.Split(new string[] { Environment.NewLine }, StringSplitOptions.None).Select(s => String.Format("\"{0}\"", s)).ToArray();
}
19
View Source File : X86Assembly.cs
License : MIT License
Project Creator : 20chan
License : MIT License
Project Creator : 20chan
public static byte[] CompileToMachineCode(string asmcode)
{
var fullcode = $".intel_syntax noprefix\n_main:\n{asmcode}";
var path = Path.Combine(Directory.GetCurrentDirectory(), "temp");
var asmfile = $"{path}.s";
var objfile = $"{path}.o";
File.WriteAllText(asmfile, fullcode, new UTF8Encoding(false));
var psi = new ProcessStartInfo("gcc", $"-m32 -c {asmfile} -o {objfile}")
{
RedirectStandardError = true,
RedirectStandardOutput = true,
UseShellExecute = false,
CreateNoWindow = true
};
var gcc = Process.Start(psi);
gcc.WaitForExit();
if (gcc.ExitCode == 0)
{
psi.FileName = "objdump";
psi.Arguments = $"-z -M intel -d {objfile}";
var objdump = Process.Start(psi);
objdump.WaitForExit();
if (objdump.ExitCode == 0)
{
var output = objdump.StandardOutput.ReadToEnd();
var matches = Regex.Matches(output, @"\b[a-fA-F0-9]{2}(?!.*:)\b");
var result = new List<byte>();
foreach (Match match in matches)
{
result.Add((byte)Convert.ToInt32(match.Value, 16));
}
return result.TakeWhile(b => b != 0x90).ToArray();
}
}
else
{
var err = gcc.StandardError.ReadToEnd();
}
throw new ArgumentException();
}
19
View Source File : LandLord.cs
License : Apache License 2.0
Project Creator : 2881099
License : Apache License 2.0
Project Creator : 2881099
public static List<int> OrderPaiLordWithColor(List<int> paiarr)
{
List<int> _tempList = new List<int>(paiarr);
for (int i = 0; i < _tempList.Count; i++)
{
if (_tempList[i] > 100) _tempList[i] %= 100;
}
int[] temparr = _tempList.ToArray<int>();
Array.Sort<int>(temparr);
List<int> _ASCList = temparr.ToList<int>();
_ASCList.Reverse();//默认是升序反转一下就降序了
//带上花色,有点小复杂
Dictionary<int, int> _dicPoker2Count = GetPoker_Count(_ASCList);
Dictionary<int, int> _dicPoker2CountUsed = new Dictionary<int, int>();
for (int j = 0; j < _ASCList.Count; j++)
{
if (!_dicPoker2CountUsed.ContainsKey(_ASCList[j])) _dicPoker2CountUsed.Add(_ASCList[j], 1);
for (int c = _dicPoker2CountUsed[_ASCList[j]]; c <= 4; c++)
{
_dicPoker2CountUsed[_ASCList[j]]++;
if (paiarr.Contains(_ASCList[j] + 100 * c))
{
_ASCList[j] = _ASCList[j] + 100 * c;
break;
}
}
}
return _ASCList;
}
19
View Source File : Serializer.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
static Func<Dictionary<string, string>, T> CompilePropertyDeserializer()
{
var o_t = typeof(T);
var o = Expression.Variable(o_t, "o");
var o_new = Expression.New(typeof(T));
var d_t = typeof(Dictionary<string, string>);
var d = Expression.Parameter(d_t, "d");
var d_mi_try_get_value = d_t.GetMethod("TryGetValue");
var item_t = typeof(String);
var item = Expression.Variable(item_t, "item");
var tc_t = typeof(TypeConverter);
var tc = Expression.Variable(tc_t, "tc");
var tc_mi_can_convert_from = tc_t.GetMethod("CanConvertFrom", new[] { typeof(Type) });
var tc_mi_convert_from = tc_t.GetMethod("ConvertFrom", new[] { typeof(Object) });
var td_t = typeof(TypeDescriptor);
var td_mi_get_converter = td_t.GetMethod("GetConverter", new[] { typeof(Type) });
var binds = o_t.GetProperties(BindingFlags.Public | BindingFlags.Instance)
.Where(x => x.CanRead)
.Select(x =>
{
var value_t = x.PropertyType;
var value = Expression.Variable(value_t, "value");
var target = Expression.Label(x.PropertyType);
return Expression.Bind(x, Expression.Block(new[] { item, value },
Expression.replacedign(tc, Expression.Call(null, td_mi_get_converter, Expression.Constant(x.PropertyType))),
Expression.IfThen(
Expression.Call(d, d_mi_try_get_value, Expression.Constant(x.Name), item),
Expression.IfThen(
Expression.NotEqual(item, Expression.Constant(null)),
Expression.IfThen(
Expression.Call(tc, tc_mi_can_convert_from, Expression.Constant(typeof(String))),
Expression.Block(
Expression.replacedign(value, Expression.Convert(Expression.Call(tc, tc_mi_convert_from, item), x.PropertyType)),
Expression.Return(target, value, x.PropertyType))))),
Expression.Label(target, value)
));
}).ToArray();
var body = Expression.Block(new[] { o, tc },
Expression.MemberInit(o_new, binds)
);
return Expression.Lambda<Func<Dictionary<string, string>, T>>(body, d)
.Compile();
}
19
View Source File : PubSub.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
void OnData(string pattern, string key, object data)
{
var regkey = pattern == null ? key : $"{_psub_regkey_prefix}{pattern}";
if (_registers.TryGetValue(regkey, out var tryval) == false) return;
var multirecvs = tryval.Values.OrderBy(a => a.RegTime).ToArray(); //Execute in order
foreach (var recv in multirecvs)
recv.Handler(pattern, key, data);
}
19
View Source File : Streams.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
public StreamsEntryResult[] XRead(long count, long block, Dictionary<string, string> keyIds)
{
var kikeys = keyIds.Keys.ToArray();
return Call("XREAD".SubCommand(null)
.InputIf(count != 0, "COUNT", count)
.InputIf(block > 0, "BLOCK", block)
.InputRaw("STREAMS")
.InputKey(kikeys)
.Input(keyIds.Values.ToArray()), rt => rt.ThrowOrValueToXRead());
}
19
View Source File : Streams.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
public StreamsEntryResult[] XReadGroup(string group, string consumer, long count, long block, bool noack, Dictionary<string, string> keyIds)
{
var kikeys = keyIds.Keys.ToArray();
return Call("XREADGROUP"
.Input("GROUP", group, consumer)
.InputIf(count != 0, "COUNT", count)
.InputIf(block > 0, "BLOCK", block)
.InputIf(noack, "NOACK")
.InputRaw("STREAMS")
.InputKey(kikeys)
.Input(keyIds.Values.ToArray()), rt => rt.ThrowOrValueToXRead());
}
19
View Source File : Resp3HelperTests.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
static object[] PrepareCmd(string cmd, string subcmd = null, params object[] parms)
{
if (string.IsNullOrWhiteSpace(cmd)) throw new ArgumentNullException("Redis command not is null or empty.");
object[] args = null;
if (parms?.Any() != true)
{
if (string.IsNullOrWhiteSpace(subcmd) == false) args = new object[] { cmd, subcmd };
else args = cmd.Split(' ').Where(a => string.IsNullOrWhiteSpace(a) == false).ToArray();
}
else
{
var issubcmd = string.IsNullOrWhiteSpace(subcmd) == false;
args = new object[parms.Length + 1 + (issubcmd ? 1 : 0)];
var argsIdx = 0;
args[argsIdx++] = cmd;
if (issubcmd) args[argsIdx++] = subcmd;
foreach (var prm in parms) args[argsIdx++] = prm;
}
return args;
}
19
View Source File : LandLord.cs
License : Apache License 2.0
Project Creator : 2881099
License : Apache License 2.0
Project Creator : 2881099
public static List<int> OrderPaiLord(List<int> paiarr)
{
List<int> _tempList = new List<int>(paiarr);
for (int i = 0; i < _tempList.Count; i++)
{
if (_tempList[i] > 100) _tempList[i] %= 100;
}
int[] temparr = _tempList.ToArray<int>();
Array.Sort<int>(temparr);
List<int> _ASCList = temparr.ToList<int>();
_ASCList.Reverse();//默认是升序反转一下就降序了
return _ASCList;
}
19
View Source File : CommandPacket.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
public CommandPacket InputIf(bool condition, params object[] args)
{
if (condition && args != null)
{
foreach (var item in args)
{
if (item is object[] objs) _input.AddRange(objs);
else if (item is string[] strs) _input.AddRange(strs.Select(a => (object)a));
else if (item is int[] ints) _input.AddRange(ints.Select(a => (object)a));
else if (item is long[] longs) _input.AddRange(longs.Select(a => (object)a));
else if (item is KeyValuePair<string, long>[] kvps1) _input.AddRange(kvps1.Select(a => new object[] { a.Key, a.Value }).SelectMany(a => a).ToArray());
else if (item is KeyValuePair<string, string>[] kvps2) _input.AddRange(kvps2.Select(a => new object[] { a.Key, a.Value }).SelectMany(a => a).ToArray());
else if (item is Dictionary<string, long> dict1) _input.AddRange(dict1.Select(a => new object[] { a.Key, a.Value }).SelectMany(a => a).ToArray());
else if (item is Dictionary<string, string> dict2) _input.AddRange(dict2.Select(a => new object[] { a.Key, a.Value }).SelectMany(a => a).ToArray());
else _input.Add(item);
}
}
return this;
}
19
View Source File : IdleBus`1.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
public List<TValue> GetAll() => _dic.Keys.ToArray().Select(a => Get(a)).ToList();
19
View Source File : IdleBus`1.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
public TKey[] GetKeys(Func<TValue, bool> filter = null)
{
if (filter == null) return _dic.Keys.ToArray();
return _dic.Keys.ToArray().Where(key => _dic.TryGetValue(key, out var item) && filter(item.value)).ToArray();
}
19
View Source File : PipelineAdapter.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
public object[] EndPipe()
{
if (_commands.Any() == false) return new object[0];
try
{
switch (UseType)
{
case UseType.Pooling: break;
case UseType.Cluster: return ClusterEndPipe();
case UseType.Sentinel:
case UseType.SingleInside: break;
case UseType.SingleTemp: break;
}
CommandPacket epcmd = "EndPipe";
return TopOwner.LogCall(epcmd, () =>
{
using (var rds = _baseAdapter.GetRedisSocket(null))
{
EndPipe(rds, _commands);
}
return _commands.Select(a => a.Result).ToArray();
});
}
finally
{
Dispose();
}
object[] ClusterEndPipe()
{
throw new NotSupportedException();
}
}
19
View Source File : Connection.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
public void ClientTracking(bool on_off, long? redirect, string[] prefix, bool bcast, bool optin, bool optout, bool noloop) => Call("CLIENT"
.SubCommand("TRACKING")
.InputIf(on_off, "ON")
.InputIf(!on_off, "OFF")
.InputIf(redirect != null, "REDIRECT", redirect)
.InputIf(prefix?.Any() == true, prefix?.Select(a => new[] { "PREFIX", a }).SelectMany(a => a).ToArray())
.InputIf(bcast, "BCAST")
.InputIf(optin, "OPTIN")
.InputIf(optout, "OPTOUT")
.InputIf(noloop, "NOLOOP"), rt => rt.ThrowOrNothing());
19
View Source File : PubSub.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
public void Dispose()
{
_stoped = true;
Cancel(_cancels.Keys.ToArray());
}
19
View Source File : PubSub.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
internal void Cancel(params Guid[] ids)
{
if (ids == null) return;
var readyUnsubInterKeys = new List<string>();
foreach (var id in ids)
{
if (_cancels.TryRemove(id, out var oldkeys))
foreach (var oldkey in oldkeys)
{
if (_registers.TryGetValue(oldkey, out var oldrecvs) &&
oldrecvs.TryRemove(id, out var oldrecv) &&
oldrecvs.Any() == false)
readyUnsubInterKeys.Add(oldkey);
}
}
var unsub = readyUnsubInterKeys.Where(a => !a.StartsWith(_psub_regkey_prefix)).ToArray();
var punsub = readyUnsubInterKeys.Where(a => a.StartsWith(_psub_regkey_prefix)).Select(a => a.Replace(_psub_regkey_prefix, "")).ToArray();
if (unsub.Any()) Call("UNSUBSCRIBE".Input(unsub));
if (punsub.Any()) Call("PUNSUBSCRIBE".Input(punsub));
if (!_cancels.Any())
lock (_lock)
if (!_cancels.Any())
_redisSocket?.ReleaseSocket();
}
19
View Source File : PubSub.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
internal void UnSubscribe(bool punsub, string[] channels)
{
channels = channels?.Distinct().Select(a => punsub ? $"{_psub_regkey_prefix}{a}" : a).ToArray();
if (channels.Any() != true) return;
var ids = channels.Select(a => _registers.TryGetValue(a, out var tryval) ? tryval : null).Where(a => a != null).SelectMany(a => a.Keys).Distinct().ToArray();
Cancel(ids);
}
19
View Source File : PubSub.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
internal IDisposable Subscribe(bool psub, string[] channels, Action<string, string, object> handler)
{
if (_stoped) return new PubSubSubscribeDisposable(this, null);
channels = channels?.Distinct().Where(a => !string.IsNullOrEmpty(a)).ToArray(); //In case of external modification
if (channels?.Any() != true) return new PubSubSubscribeDisposable(this, null);
var id = Guid.NewGuid();
var time = DateTime.Now;
var regkeys = channels.Select(a => psub ? $"{_psub_regkey_prefix}{a}" : a).ToArray();
for (var a = 0; a < regkeys.Length; a++)
{
ConcurrentDictionary<Guid, RegisterInfo> dict = null;
lock (_lock) dict = _registers.GetOrAdd(regkeys[a], k1 => new ConcurrentDictionary<Guid, RegisterInfo>());
dict.TryAdd(id, new RegisterInfo(id, handler, time));
}
lock (_lock)
_cancels.TryAdd(id, regkeys);
var isnew = false;
if (IsSubscribed == false)
{
lock (_lock)
{
if (IsSubscribed == false)
{
_redisSocket = _topOwner.Adapter.GetRedisSocket(null);
IsSubscribed = isnew = true;
}
}
}
if (isnew)
{
new Thread(() =>
{
_redisSocketReceiveTimeoutOld = _redisSocket.ReceiveTimeout;
_redisSocket.ReceiveTimeout = TimeSpan.Zero;
var timer = new Timer(state =>
{
_topOwner.Adapter.Refersh(_redisSocket); //防止 IdleBus 超时回收
try { _redisSocket.Write("PING"); } catch { }
}, null, 10000, 10000);
var readCmd = "PubSubRead".SubCommand(null).FlagReadbytes(false);
while (_stoped == false)
{
RedisResult rt = null;
try
{
rt = _redisSocket.Read(readCmd);
}
catch
{
Thread.CurrentThread.Join(100);
if (_cancels.Any()) continue;
break;
}
var val = rt.Value as object[];
if (val == null) continue; //special case
var val1 = val[0].ConvertTo<string>();
switch (val1)
{
case "pong":
case "punsubscribe":
case "unsubscribe":
continue;
case "pmessage":
OnData(val[1].ConvertTo<string>(), val[2].ConvertTo<string>(), val[3]);
continue;
case "message":
OnData(null, val[1].ConvertTo<string>(), val[2]);
continue;
}
}
timer.Dispose();
lock (_lock)
{
IsSubscribed = false;
_redisSocket.ReceiveTimeout = _redisSocketReceiveTimeoutOld;
_redisSocket.ReleaseSocket();
_redisSocket.Dispose();
_redisSocket = null;
}
}).Start();
}
Call((psub ? "PSUBSCRIBE" : "SUBSCRIBE").Input(channels));
return new PubSubSubscribeDisposable(this, () => Cancel(id));
}
19
View Source File : RedisClient.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
internal T DeserializeRedisValue<T>(byte[] valueRaw, Encoding encoding)
{
if (valueRaw == null) return default(T);
var type = typeof(T);
var typename = type.ToString().TrimEnd(']');
if (typename == "System.Byte[") return (T)Convert.ChangeType(valueRaw, type);
if (typename == "System.String") return (T)Convert.ChangeType(encoding.GetString(valueRaw), type);
if (typename == "System.Boolean[") return (T)Convert.ChangeType(valueRaw.Select(a => a == 49).ToArray(), type);
if (valueRaw.Length == 0) return default(T);
string valueStr = null;
if (type.IsValueType)
{
valueStr = encoding.GetString(valueRaw);
bool isNullable = typename.StartsWith("System.Nullable`1[");
var basename = isNullable ? typename.Substring(18) : typename;
bool isElse = false;
object obj = null;
switch (basename)
{
case "System.Boolean":
if (valueStr == "1") obj = true;
else if (valueStr == "0") obj = false;
break;
case "System.Byte":
if (byte.TryParse(valueStr, out var trybyte)) obj = trybyte;
break;
case "System.Char":
if (valueStr.Length > 0) obj = valueStr[0];
break;
case "System.Decimal":
if (Decimal.TryParse(valueStr, out var trydec)) obj = trydec;
break;
case "System.Double":
if (Double.TryParse(valueStr, out var trydb)) obj = trydb;
break;
case "System.Single":
if (Single.TryParse(valueStr, out var trysg)) obj = trysg;
break;
case "System.Int32":
if (Int32.TryParse(valueStr, out var tryint32)) obj = tryint32;
break;
case "System.Int64":
if (Int64.TryParse(valueStr, out var tryint64)) obj = tryint64;
break;
case "System.SByte":
if (SByte.TryParse(valueStr, out var trysb)) obj = trysb;
break;
case "System.Int16":
if (Int16.TryParse(valueStr, out var tryint16)) obj = tryint16;
break;
case "System.UInt32":
if (UInt32.TryParse(valueStr, out var tryuint32)) obj = tryuint32;
break;
case "System.UInt64":
if (UInt64.TryParse(valueStr, out var tryuint64)) obj = tryuint64;
break;
case "System.UInt16":
if (UInt16.TryParse(valueStr, out var tryuint16)) obj = tryuint16;
break;
case "System.DateTime":
if (DateTime.TryParse(valueStr, out var trydt)) obj = trydt;
break;
case "System.DateTimeOffset":
if (DateTimeOffset.TryParse(valueStr, out var trydtos)) obj = trydtos;
break;
case "System.TimeSpan":
if (Int64.TryParse(valueStr, out tryint64)) obj = new TimeSpan(tryint64);
break;
case "System.Guid":
if (Guid.TryParse(valueStr, out var tryguid)) obj = tryguid;
break;
default:
isElse = true;
break;
}
if (isElse == false)
{
if (obj == null) return default(T);
return (T)obj;
}
}
if (Adapter.TopOwner.DeserializeRaw != null) return (T)Adapter.TopOwner.DeserializeRaw(valueRaw, typeof(T));
if (valueStr == null) valueStr = encoding.GetString(valueRaw);
if (Adapter.TopOwner.Deserialize != null) return (T)Adapter.TopOwner.Deserialize(valueStr, typeof(T));
return valueStr.ConvertTo<T>();
}
19
View Source File : InternalExtensions.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
public static string GetDescription(this Type that)
{
object[] attrs = null;
try
{
attrs = that.GetCustomAttributes(false).ToArray(); //.net core 反射存在版本冲突问题,导致该方法异常
}
catch { }
var dyattr = attrs?.Where(a => {
return ((a as Attribute)?.TypeId as Type)?.Name == "DescriptionAttribute";
}).FirstOrDefault();
if (dyattr != null)
{
var valueProp = dyattr.GetType().GetProperties().Where(a => a.PropertyType == typeof(string)).FirstOrDefault();
var comment = valueProp?.GetValue(dyattr, null)?.ToString();
if (string.IsNullOrEmpty(comment) == false)
return comment;
}
return null;
}
19
View Source File : Program.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
static void Insert(StringBuilder sb, int forTime, int size) {
var songs = Enumerable.Range(0, size).Select(a => new Song {
Create_time = DateTime.Now,
Is_deleted = false,
replacedle = $"Insert_{a}",
Url = $"Url_{a}"
});
//预热
fsql.Insert(songs.First()).ExecuteAffrows();
sugar.Insertable(songs.First()).ExecuteCommand();
using (var db = new SongContext()) {
//db.Configuration.AutoDetectChangesEnabled = false;
db.Songs.AddRange(songs.First());
db.SaveChanges();
}
Stopwatch sw = new Stopwatch();
sw.Restart();
for (var a = 0; a < forTime; a++) {
fsql.Insert(songs).ExecuteAffrows();
}
sw.Stop();
sb.AppendLine($"FreeSql Insert {size}条数据,循环{forTime}次,耗时{sw.ElapsedMilliseconds}ms");
sw.Restart();
for (var a = 0; a < forTime; a++) {
using (var db = new FreeSongContext()) {
db.Songs.AddRange(songs.ToArray());
db.SaveChanges();
}
}
sw.Stop();
sb.AppendLine($"FreeSql.DbContext Insert {size}条数据,循环{forTime}次,耗时{sw.ElapsedMilliseconds}ms");
sw.Restart();
Exception sugarEx = null;
try {
for (var a = 0; a < forTime; a++)
sugar.Insertable(songs.ToArray()).ExecuteCommand();
} catch (Exception ex) {
sugarEx = ex;
}
sw.Stop();
sb.AppendLine($"SqlSugar Insert {size}条数据,循环{forTime}次,耗时{sw.ElapsedMilliseconds}ms" + (sugarEx != null ? $"成绩无效,错误:{sugarEx.Message}" : ""));
sw.Restart();
for (var a = 0; a < forTime; a++) {
using (var db = new SongContext()) {
//db.Configuration.AutoDetectChangesEnabled = false;
db.Songs.AddRange(songs.ToArray());
db.SaveChanges();
}
}
sw.Stop();
sb.AppendLine($"EFCore Insert {size}条数据,循环{forTime}次,耗时{sw.ElapsedMilliseconds}ms\r\n");
}
19
View Source File : DbSetAsync.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
async Task<int> DbContextBetchUpdatePrivAsync(EnreplacedyState[] ups, bool isLiveUpdate) {
if (ups.Any() == false) return 0;
var uplst1 = ups[ups.Length - 1];
var uplst2 = ups.Length > 1 ? ups[ups.Length - 2] : null;
if (_states.TryGetValue(uplst1.Key, out var lstval1) == false) return -999;
var lstval2 = default(EnreplacedyState);
if (uplst2 != null && _states.TryGetValue(uplst2.Key, out lstval2) == false) throw new Exception($"特别错误:更新失败,数据未被跟踪:{_fsql.GetEnreplacedyString(_enreplacedyType, uplst2.Value)}");
var cuig1 = _fsql.CompareEnreplacedyValueReturnColumns(_enreplacedyType, uplst1.Value, lstval1.Value, true);
var cuig2 = uplst2 != null ? _fsql.CompareEnreplacedyValueReturnColumns(_enreplacedyType, uplst2.Value, lstval2.Value, true) : null;
List<EnreplacedyState> data = null;
string[] cuig = null;
if (uplst2 != null && string.Compare(string.Join(",", cuig1), string.Join(",", cuig2)) != 0) {
//最后一个不保存
data = ups.ToList();
data.RemoveAt(ups.Length - 1);
cuig = cuig2;
} else if (isLiveUpdate) {
//立即保存
data = ups.ToList();
cuig = cuig1;
}
if (data?.Count > 0) {
if (cuig.Length == _table.Columns.Count)
return ups.Length == data.Count ? -998 : -997;
var updateSource = data.Select(a => a.Value).ToArray();
var update = this.OrmUpdate(null).SetSource(updateSource).IgnoreColumns(cuig);
var affrows = await update.ExecuteAffrowsAsync();
foreach (var newval in data) {
if (_states.TryGetValue(newval.Key, out var tryold))
_fsql.MapEnreplacedyValue(_enreplacedyType, newval.Value, tryold.Value);
if (newval.OldValue != null)
_fsql.MapEnreplacedyValue(_enreplacedyType, newval.Value, newval.OldValue);
}
return affrows;
}
//等待下次对比再保存
return 0;
}
See More Examples