Here are the examples of the csharp api System.Collections.Generic.IEnumerable.Any(System.Func) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
12647 Examples
19
View Source File : MainWindow.xaml.cs
License : GNU General Public License v3.0
Project Creator : 00000vish
License : GNU General Public License v3.0
Project Creator : 00000vish
private void initVariables()
{
LaunchedViaStartup = Environment.GetCommandLineArgs() != null && Environment.GetCommandLineArgs().Any(arg => arg.Equals("startup", StringComparison.CurrentCultureIgnoreCase));
encrypted = SteamTwoProperties.jsonSetting.encryptedSetting;
currentHandle = this;
}
19
View Source File : XnaToFnaUtil.cs
License : zlib License
Project Creator : 0x0ade
License : zlib License
Project Creator : 0x0ade
public void ApplyCommonChanges(ModuleDefinition mod, string tag = "Relink") {
if (DestroyPublicKeyTokens.Contains(mod.replacedembly.Name.Name)) {
Log($"[{tag}] Destroying public key token for module {mod.replacedembly.Name.Name}");
mod.replacedembly.Name.PublicKeyToken = new byte[0];
}
Log($"[{tag}] Updating dependencies");
for (int i = 0; i < mod.replacedemblyReferences.Count; i++) {
replacedemblyNameReference dep = mod.replacedemblyReferences[i];
// Main mapping mreplaced.
foreach (XnaToFnaMapping mapping in Mappings)
if (mapping.Sources.Contains(dep.Name) &&
// Check if the target module has been found and cached
Modder.DependencyCache.ContainsKey(mapping.Target)) {
// Check if module already depends on the remap
if (mod.replacedemblyReferences.Any(existingDep => existingDep.Name == mapping.Target)) {
// If so, just remove the dependency.
mod.replacedemblyReferences.RemoveAt(i);
i--;
goto NextDep;
}
Log($"[{tag}] Replacing dependency {dep.Name} -> {mapping.Target}");
// Replace the dependency.
mod.replacedemblyReferences[i] = Modder.DependencyCache[mapping.Target].replacedembly.Name;
// Only check until first match found.
goto NextDep;
}
// Didn't remap; Check for RemoveDeps
if (RemoveDeps.Contains(dep.Name)) {
// Remove any unwanted (f.e. mixed) dependencies.
Log($"[{tag}] Removing unwanted dependency {dep.Name}");
mod.replacedemblyReferences.RemoveAt(i);
i--;
goto NextDep;
}
// Didn't remove
// Check for DestroyPublicKeyTokens
if (DestroyPublicKeyTokens.Contains(dep.Name)) {
Log($"[{tag}] Destroying public key token for dependency {dep.Name}");
dep.PublicKeyToken = new byte[0];
}
// Check for ModulesToStub (formerly managed references)
if (ModulesToStub.Any(stub => stub.replacedembly.Name.Name == dep.Name)) {
// Fix stubbed dependencies.
Log($"[{tag}] Fixing stubbed dependency {dep.Name}");
dep.IsWindowsRuntime = false;
dep.HasPublicKey = false;
}
// Check for .NET compact (X360) version
if (dep.Version == DotNetX360Version) {
// Replace public key token.
dep.PublicKeyToken = DotNetFrameworkKeyToken;
// Technically .NET 2(?), but let's just bump the version.
dep.Version = DotNetFramework4Version;
}
NextDep:
continue;
}
if (AddreplacedemblyReference && !mod.replacedemblyReferences.Any(dep => dep.Name == ThisreplacedemblyName)) {
// Add XnaToFna as dependency
Log($"[{tag}] Adding dependency XnaToFna");
mod.replacedemblyReferences.Add(Modder.DependencyCache[ThisreplacedemblyName].replacedembly.Name);
}
if (mod.Runtime < TargetRuntime.Net_4_0) {
// XNA 3.0 / 3.1 and X360 games depend on a .NET Framework pre-4.0
mod.Runtime = TargetRuntime.Net_4_0;
// TODO: What about the System.*.dll dependencies?
}
Log($"[{tag}] Updating module attributes");
mod.Attributes &= ~ModuleAttributes.StrongNameSigned;
if (PreferredPlatform != ILPlatform.Keep) {
// "Clear" to AnyCPU.
mod.Architecture = TargetArchitecture.I386;
mod.Attributes &= ~ModuleAttributes.Required32Bit & ~ModuleAttributes.Preferred32Bit;
switch (PreferredPlatform) {
case ILPlatform.x86:
mod.Architecture = TargetArchitecture.I386;
mod.Attributes |= ModuleAttributes.Required32Bit;
break;
case ILPlatform.x64:
mod.Architecture = TargetArchitecture.AMD64;
break;
case ILPlatform.x86Pref:
mod.Architecture = TargetArchitecture.I386;
mod.Attributes |= ModuleAttributes.Preferred32Bit;
break;
}
}
bool mixed = (mod.Attributes & ModuleAttributes.ILOnly) != ModuleAttributes.ILOnly;
if (ModulesToStub.Count != 0 || mixed) {
Log($"[{tag}] Making replacedembly unsafe");
mod.Attributes |= ModuleAttributes.ILOnly;
for (int i = 0; i < mod.replacedembly.CustomAttributes.Count; i++) {
CustomAttribute attrib = mod.replacedembly.CustomAttributes[i];
if (attrib.AttributeType.FullName == "System.CLSCompliantAttribute") {
mod.replacedembly.CustomAttributes.RemoveAt(i);
i--;
}
}
if (!mod.CustomAttributes.Any(ca => ca.AttributeType.FullName == "System.Security.UnverifiableCodeAttribute"))
mod.AddAttribute(mod.ImportReference(m_UnverifiableCodeAttribute_ctor));
}
// MonoMod needs to relink some types (f.e. XnaToFnaHelper) via FindType, which requires a dependency map.
Log($"[{tag}] Mapping dependencies for MonoMod");
Modder.MapDependencies(mod);
}
19
View Source File : XnaToFnaUtil.Processor.cs
License : zlib License
Project Creator : 0x0ade
License : zlib License
Project Creator : 0x0ade
public void PreProcessType(TypeDefinition type) {
if (HookCompat) {
foreach (MethodDefinition method in type.Methods) {
if (!method.HasPInvokeInfo)
continue;
// Just check if PInvokeHooks contains the entry point, ignoring the module name, except for its end. What can go wrong?...
if (!method.PInvokeInfo.Module.Name.EndsWith("32.dll") && !method.PInvokeInfo.Module.Name.EndsWith("32"))
continue;
string entryPoint = method.PInvokeInfo.EntryPoint ?? method.Name;
if (typeof(PInvokeHooks).GetMethod(entryPoint) != null) {
Log($"[PreProcess] [PInvokeHooks] Remapping call to {entryPoint} ({method.GetFindableID()})");
Modder.RelinkMap[method.GetFindableID(simple: true)] =
new RelinkMapEntry("XnaToFna.PInvokeHooks", entryPoint);
} else {
Log($"[PreProcess] [PInvokeHooks] Found unhooked call to {entryPoint} ({method.GetFindableID()})");
}
}
}
if (FixOldMonoXML) {
Stack<TypeDefinition> baseTypes = new Stack<TypeDefinition>();
try {
for (TypeDefinition baseType = type.BaseType?.Resolve(); baseType != null; baseType = baseType.BaseType?.Resolve())
baseTypes.Push(baseType);
} catch {
// Unresolved replacedembly, f.e. XNA itself
}
foreach (FieldDefinition field in type.Fields) {
string name = field.Name;
if (baseTypes.Any(baseType => baseType.FindField(name) != null || baseType.FindProperty(name) != null)) {
// Field name collision found. Mono 4.4+ handles them well, while Xamarin.Android still fails.
Log($"[PreProcess] Renaming field name collison {name} in {type.FullName}");
field.Name = $"{name}_{type.Name}";
Modder.RelinkMap[$"{type.FullName}::{name}"] = field.FullName;
}
}
}
foreach (TypeDefinition nested in type.NestedTypes)
PreProcessType(nested);
}
19
View Source File : ModelClassGenerator.cs
License : MIT License
Project Creator : 0x1000000
License : MIT License
Project Creator : 0x1000000
public static CompilationUnitSyntax Generate(SqModelMeta meta, string defaultNamespace, string existingFilePath, bool rwClreplacedes, IFileSystem fileSystem, out bool existing)
{
CompilationUnitSyntax result;
ClreplacedDeclarationSyntax? existingClreplaced = null;
existing = false;
if (fileSystem.FileExists(existingFilePath))
{
existing = true;
var tClreplaced = CSharpSyntaxTree.ParseText(fileSystem.ReadAllText(existingFilePath));
existingClreplaced = tClreplaced.GetRoot()
.DescendantNodes()
.OfType<ClreplacedDeclarationSyntax>()
.FirstOrDefault(cd => cd.Identifier.ValueText == meta.Name);
}
var namespaces =
new[] {
nameof(System),
nameof(SqExpress),
$"{nameof(SqExpress)}.{nameof(SqExpress.QueryBuilders)}.{nameof(SqExpress.QueryBuilders.RecordSetter)}"
}
.Concat(meta.Properties.SelectMany(p => p.Column)
.Select(c => c.TableRef.TableTypeNameSpace)
.Where(n => n != defaultNamespace))
.Distinct()
.ToList();
if (rwClreplacedes || ExtractTableRefs(meta).Any(tr => tr.BaseTypeKindTag == BaseTypeKindTag.DerivedTableBase))
{
namespaces.Add($"{nameof(SqExpress)}.{nameof(SqExpress.Syntax)}.{nameof(SqExpress.Syntax.Names)}");
namespaces.Add($"{nameof(System)}.{nameof(System.Collections)}.{nameof(System.Collections.Generic)}");
}
if (existingClreplaced != null)
{
result = existingClreplaced.FindParentOrDefault<CompilationUnitSyntax>() ?? throw new SqExpressCodeGenException($"Could not find compilation unit in \"{existingFilePath}\"");
foreach (var usingDirectiveSyntax in result.Usings)
{
var existingUsing = usingDirectiveSyntax.Name.ToFullString();
var index = namespaces.IndexOf(existingUsing);
if (index >= 0)
{
namespaces.RemoveAt(index);
}
}
if (namespaces.Count > 0)
{
result = result.AddUsings(namespaces
.Select(n => SyntaxFactory.UsingDirective(SyntaxFactory.ParseName(n)))
.ToArray());
}
result = result.ReplaceNode(existingClreplaced, GenerateClreplaced(meta, rwClreplacedes, existingClreplaced));
}
else
{
result = SyntaxFactory.CompilationUnit()
.AddUsings(namespaces.Select(n => SyntaxFactory.UsingDirective(SyntaxFactory.ParseName(n))).ToArray())
.AddMembers(SyntaxFactory.NamespaceDeclaration(SyntaxFactory.ParseName(defaultNamespace))
.AddMembers(GenerateClreplaced(meta, rwClreplacedes, null)));
}
return result.NormalizeWhitespace();
}
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 : IsoHeaderParser.cs
License : MIT License
Project Creator : 13xforever
License : MIT License
Project Creator : 13xforever
public static (List<FileRecord> files, List<string> dirs) GetFilesystemStructure(this CDReader reader)
{
var fsObjects = reader.GetFileSystemEntries(reader.Root.FullName).ToList();
var nextLevel = new List<string>();
var filePaths = new List<string>();
var dirPaths = new List<string>();
while (fsObjects.Any())
{
foreach (var path in fsObjects)
{
if (reader.FileExists(path))
filePaths.Add(path);
else if (reader.DirectoryExists(path))
{
dirPaths.Add(path);
nextLevel.AddRange(reader.GetFileSystemEntries(path));
}
else
Log.Warn($"Unknown filesystem object: {path}");
}
(fsObjects, nextLevel) = (nextLevel, fsObjects);
nextLevel.Clear();
}
var filenames = filePaths.Distinct().Select(n => n.TrimStart('\\')).ToList();
var dirnames = dirPaths.Distinct().Select(n => n.TrimStart('\\')).OrderByDescending(n => n.Length).ToList();
var deepestDirnames = new List<string>();
foreach (var dirname in dirnames)
{
var tmp = dirname + "\\";
if (deepestDirnames.Any(n => n.StartsWith(tmp)))
continue;
deepestDirnames.Add(dirname);
}
dirnames = deepestDirnames.OrderBy(n => n).ToList();
var dirnamesWithFiles = filenames.Select(Path.GetDirectoryName).Distinct().ToList();
var emptydirs = dirnames.Except(dirnamesWithFiles).ToList();
var fileList = new List<FileRecord>();
foreach (var filename in filenames)
{
var clusterRange = reader.PathToClusters(filename);
if (clusterRange.Length != 1)
Log.Warn($"{filename} is split in {clusterRange.Length} ranges");
if (filename.EndsWith("."))
Log.Warn($"Fixing potential mastering error in {filename}");
fileList.Add(new FileRecord(filename.TrimEnd('.'), clusterRange.Min(r => r.Offset), reader.GetFileLength(filename)));
}
fileList = fileList.OrderBy(r => r.StartSector).ToList();
return (files: fileList, dirs: emptydirs);
}
19
View Source File : ProxyGenerator.cs
License : MIT License
Project Creator : 1100100
License : MIT License
Project Creator : 1100100
public static List<Type> GenerateProxy(List<Type> interfaces)
{
if (interfaces.Any(p => !p.IsInterface && !typeof(IService).IsreplacedignableFrom(p)))
throw new ArgumentException("The proxy object must be an interface and inherit IService.", nameof(interfaces));
var replacedemblies = DependencyContext.Default.RuntimeLibraries.SelectMany(i => i.GetDefaultreplacedemblyNames(DependencyContext.Default).Select(z => replacedembly.Load(new replacedemblyName(z.Name)))).Where(i => !i.IsDynamic);
var types = replacedemblies.Select(p => p.GetType()).Except(interfaces);
replacedemblies = types.Aggregate(replacedemblies, (current, type) => current.Append(type.replacedembly));
var trees = interfaces.Select(GenerateProxyTree).ToList();
if (UraganoOptions.Output_DynamicProxy_SourceCode.Value)
{
for (var i = 0; i < trees.Count; i++)
{
File.WriteAllText(Path.Combine(Directory.GetCurrentDirectory(), $"{interfaces[i].Name}.Implement.cs"),
trees[i].ToString());
}
}
using (var stream = CompileClientProxy(trees,
replacedemblies.Select(x => MetadataReference.CreateFromFile(x.Location))
.Concat(new[]
{
MetadataReference.CreateFromFile(typeof(Task).GetTypeInfo().replacedembly.Location)
})))
{
var replacedembly = replacedemblyLoadContext.Default.LoadFromStream(stream);
return replacedembly.GetExportedTypes().ToList();
}
}
19
View Source File : Decrypter.cs
License : MIT License
Project Creator : 13xforever
License : MIT License
Project Creator : 13xforever
private bool IsEncrypted(long sector)
{
var result = !unprotectedSectorRanges.Any(r => r.start <= sector && sector <= r.end);
if (TraceSectors)
Log.Trace($"{sector:x8}: {(result ? "e" : "")}");
return result;
}
19
View Source File : ReflectHelper.cs
License : MIT License
Project Creator : 1100100
License : MIT License
Project Creator : 1100100
public static List<Type> GetDependencyTypes()
{
lock (LockObject)
{
if (Types != null)
return Types;
var ignorereplacedemblyFix = new[]
{
"Microsoft", "System", "Consul", "Polly", "Newtonsoft.Json", "MessagePack", "Google.Protobuf","DotNetty","Exceptionless","CSRedis","SafeObjectPool",
"Remotion.Linq", "SOS.NETCore", "WindowsBase", "mscorlib", "netstandard", "Uragano.Abstractions","Uragano.Core","Uragano.DynamicProxy","Uragano.Logging.Exceptionless","Uragano.Remoting","Uragano.Consul","Uragano.Codec.MessagePack","Uragano.Logging.Log4Net","Uragano.Logging.NLog","Uragano.Caching.Redis","Uragano.Caching.Memory"
};
var replacedemblies = DependencyContext.Default.RuntimeLibraries.SelectMany(i =>
i.GetDefaultreplacedemblyNames(DependencyContext.Default)
.Where(p => !ignorereplacedemblyFix.Any(ignore =>
p.Name.StartsWith(ignore, StringComparison.CurrentCultureIgnoreCase)))
.Select(z => replacedembly.Load(new replacedemblyName(z.Name)))).Where(p => !p.IsDynamic).ToList();
Types = replacedemblies.SelectMany(p => p.GetExportedTypes()).ToList();
return Types;
}
}
19
View Source File : ExpressionActivator.cs
License : Apache License 2.0
Project Creator : 1448376744
License : Apache License 2.0
Project Creator : 1448376744
private Expression CreateExpression(ParameterExpression parameter, string expression)
{
var expressions1 = Factorization(expression);
var expressions2 = new Dictionary<string, Expression>();
foreach (var item in expressions1)
{
var subexpr = item.Value.Trim('(', ')');
var @opterator = ResovleOperator(item.Value);
var opt = GetExpressionType(@opterator);
if (opt == ExpressionType.Not)
{
Expression exp;
var text = subexpr.Split(new string[] { @opterator }, StringSplitOptions.RemoveEmptyEntries)[0].Trim();
if (expressions2.ContainsKey(text))
{
exp = expressions2[text];
}
else if (parameter.Type.GetProperties().Any(a => a.Name == text))
{
var property = parameter.Type.GetProperty(text);
exp = Expression.MakeMemberAccess(parameter, property);
}
else
{
exp = Expression.Constant(Convert.ToBoolean(text));
}
expressions2.Add(item.Key, Expression.MakeUnary(opt, exp, null));
}
else
{
var text1 = subexpr
.Split(new string[] { @opterator }, StringSplitOptions.RemoveEmptyEntries)[0]
.Trim();
var text2 = subexpr
.Split(new string[] { @opterator }, StringSplitOptions.RemoveEmptyEntries)[1]
.Trim();
string temp = null;
Expression exp1, exp2;
//永远将变量放在第一个操作数
if (parameter.Type.GetProperties().Any(a => a.Name == text2))
{
temp = text1;
text1 = text2;
text2 = temp;
}
//是否为上一次的分式
if (expressions2.ContainsKey(text1))
{
exp1 = expressions2[text1];
}
else if (parameter.Type.GetProperties().Any(a => a.Name == text1))
{
//是否为变量
var property = parameter.Type.GetProperty(text1);
exp1 = Expression.MakeMemberAccess(parameter, property);
}
else
{
exp1 = ResovleConstantExpression(text1);
}
//是否为上一次的分式
if (expressions2.ContainsKey(text2))
{
exp2 = expressions2[text2];
}
//如果第一个操作数是变量
else if (parameter.Type.GetProperties().Any(a => a.Name == text1))
{
var constantType = parameter.Type.GetProperty(text1).PropertyType;
exp2 = ResovleConstantExpression(text2, constantType);
}
else
{
exp2 = ResovleConstantExpression(text1, (exp1 as ConstantExpression)?.Type);
}
expressions2.Add(item.Key, Expression.MakeBinary(opt, exp1, exp2));
}
}
return expressions2.Last().Value;
}
19
View Source File : TypeExtensions.cs
License : MIT License
Project Creator : 17MKH
License : MIT License
Project Creator : 17MKH
public static bool IsImplementType(this Type serviceType, Type implementType)
{
//泛型
if (serviceType.IsGenericType)
{
if (serviceType.IsInterface)
{
var interfaces = implementType.GetInterfaces();
if (interfaces.Any(m => m.IsGenericType && m.GetGenericTypeDefinition() == serviceType))
{
return true;
}
}
else
{
if (implementType.BaseType != null && implementType.BaseType.IsGenericType && implementType.BaseType.GetGenericTypeDefinition() == serviceType)
{
return true;
}
}
}
else
{
if (serviceType.IsInterface)
{
var interfaces = implementType.GetInterfaces();
if (interfaces.Any(m => m == serviceType))
return true;
}
else
{
if (implementType.BaseType != null && implementType.BaseType == serviceType)
return true;
}
}
return false;
}
19
View Source File : QueryableSqlBuilder.cs
License : MIT License
Project Creator : 17MKH
License : MIT License
Project Creator : 17MKH
public void ResolveSelectForEnreplacedy(StringBuilder sqlBuilder, int index = 0, List<IColumnDescriptor> excludeColumns = null)
{
var join = _queryBody.Joins[index];
foreach (var col in join.EnreplacedyDescriptor.Columns)
{
if (excludeColumns != null && excludeColumns.Any(m => m == col))
continue;
//单个实体时不需要别名
sqlBuilder.Append(IsSingleEnreplacedy ? $"{_dbAdapter.AppendQuote(col.Name)}" : $"{join.Alias}.{_dbAdapter.AppendQuote(col.Name)}");
sqlBuilder.AppendFormat(" AS {0},", _dbAdapter.AppendQuote(col.PropertyInfo.Name));
}
}
19
View Source File : QueryableSqlBuilder.cs
License : MIT License
Project Creator : 17MKH
License : MIT License
Project Creator : 17MKH
public void ResolveSelectForMember(StringBuilder sqlBuilder, MemberExpression memberExp, LambdaExpression fullLambda, List<IColumnDescriptor> excludeCols, string alias = null)
{
alias ??= memberExp.Member.Name;
string columnName;
if (DbConstants.ENreplacedY_INTERFACE_TYPE.IsImplementType(memberExp.Type))
{
var index = _queryBody.Joins.FindIndex(m => m.EnreplacedyDescriptor.EnreplacedyType == memberExp.Type);
ResolveSelectForEnreplacedy(sqlBuilder, index, excludeCols);
}
else if (memberExp.Expression!.Type.IsString())
{
columnName = _queryBody.GetColumnName(memberExp);
sqlBuilder.AppendFormat("{0} AS {1},", _queryBody.DbAdapter.FunctionMapper(memberExp.Member.Name, columnName), _dbAdapter.AppendQuote(alias));
}
else if (DbConstants.ENreplacedY_INTERFACE_TYPE.IsImplementType(memberExp.Expression.Type))
{
var join = _queryBody.GetJoin(memberExp);
if (excludeCols != null && excludeCols.Any(m => m == join.Item2))
return;
columnName = _queryBody.GetColumnName(join.Item1, join.Item2);
sqlBuilder.AppendFormat("{0} AS {1},", columnName, _dbAdapter.AppendQuote(alias));
}
}
19
View Source File : RedisDatabase.cs
License : MIT License
Project Creator : 17MKH
License : MIT License
Project Creator : 17MKH
private IList<RedisKey> GetKeys(string prefix = null, int pageSize = 10, int pageOffset = 0)
{
var pat = prefix.IsNull() ? null : $"{GetKey(prefix)}*";
var endPoints = _redis.GetEndPoints();
if (endPoints.Length > 1)
{
var skipNum = pageOffset * pageSize;
var leftNum = skipNum + pageSize;
var keys = new List<RedisKey>();
foreach (var endPoint in endPoints)
{
if (leftNum > 0)
{
foreach (var key in _redis.GetServer(endPoint).Keys(_dbIndex, pat, pageSize: leftNum))
{
if (keys.Any(m => m == key))
{
continue;
}
keys.Add(key);
leftNum--;
}
}
}
return keys.Skip(pageSize * pageOffset).Take(pageSize).ToList();
}
else
{
return _redis.GetServer(_redis.GetEndPoints().FirstOrDefault()).Keys(_dbIndex, pat, pageSize: pageSize, pageOffset: pageOffset).ToList();
}
}
19
View Source File : ControllerResolver.cs
License : MIT License
Project Creator : 17MKH
License : MIT License
Project Creator : 17MKH
private void LoadControllers()
{
ControllerFeature controllerFeature = new ControllerFeature();
_partManager.PopulateFeature(controllerFeature);
foreach (TypeInfo item2 in controllerFeature.Controllers.ToList())
{
if (item2.IsAbstract)
{
continue;
}
ControllerDescriptor controllerDescriptor = new ControllerDescriptor
{
Name = item2.Name.Replace("Controller", ""),
Description = _attributeHelper.GetDescription(item2),
Actions = new List<ActionDescriptor>(),
TypeInfo = item2
};
AreaAttribute areaAttribute = (AreaAttribute)Attribute.GetCustomAttribute(item2, typeof(AreaAttribute));
if (areaAttribute != null)
{
controllerDescriptor.Area = areaAttribute.RouteValue;
}
MethodInfo[] methods = item2.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public);
foreach (MethodInfo methodInfo in methods)
{
if (methodInfo.CustomAttributes.Any(m => m.AttributeType == typeof(HttpGetAttribute) || m.AttributeType == typeof(HttpPostAttribute) || m.AttributeType == typeof(HttpPutAttribute) || m.AttributeType == typeof(HttpOptionsAttribute) || m.AttributeType == typeof(HttpHeadAttribute) || m.AttributeType == typeof(HttpPatchAttribute) || m.AttributeType == typeof(HttpDeleteAttribute)))
{
ActionDescriptor item = new ActionDescriptor
{
Name = methodInfo.Name,
MethodInfo = methodInfo
};
controllerDescriptor.Actions.Add(item);
}
}
Controllers.Add(controllerDescriptor);
}
}
19
View Source File : TsCreator.cs
License : MIT License
Project Creator : 279328316
License : MIT License
Project Creator : 279328316
private void FillTsModelList(List<TsModel> list, PTypeModel ptype)
{
ptype = JcApiHelper.GetPTypeModel(ptype.Id); //读取Ptype注释内容
if (list.Any(tsPtype => tsPtype.Id == ptype.Id))
{ //已添加过,不再添加
return;
}
if (ptype.IsIEnumerable)
{ //枚举类型 添加其泛型类型
PTypeModel enumItemPtype = JcApiHelper.GetPTypeModel(ptype.EnumItemId); //读取Ptype注释内容
if (enumItemPtype?.PiList?.Count > 0)
{
FillTsModelList(list, enumItemPtype);
}
return;
}
TsModel tsPType = new TsModel()
{
Id = ptype.Id,
Name = GetTsType(ptype),
Summary = ptype.Summary,
TsModelCode = GetTsModelCode(ptype),
PgQueryModelCode = GetTsQueryModelCode(ptype),
PiList = new List<TsPi>()
};
list.Add(tsPType);
for (int i = 0; i < ptype.PiList?.Count; i++)
{
TsPi tsPi = new TsPi()
{
Name = ptype.PiList[i].Name,
Summary = ptype.PiList[i].Summary,
TsType = GetTsType(ptype.PiList[i].PType)
};
tsPType.PiList.Add(tsPi);
if (ptype.PiList[i].PType.PiList?.Count > 0)
{
FillTsModelList(list, ptype.PiList[i].PType);
}
}
}
19
View Source File : JcApiHelperUIMiddleware.cs
License : MIT License
Project Creator : 279328316
License : MIT License
Project Creator : 279328316
public async Task Invoke(HttpContext httpContext)
{
string httpMethod = httpContext.Request.Method;
string path = httpContext.Request.Path.Value.ToLower();
if (httpMethod == "GET" && Regex.IsMatch(path, $"/apihelper/"))
{
if (Regex.IsMatch(path, $"/apihelper/index.html"))
{ //index.html特殊处理
await RespondWithIndexHtml(httpContext.Response);
return;
}
else
{
string resourceName = path.Replace($"/apihelper/", "")
.Replace("/", ".");
if (!apiResources.Any(a => a.ToLower() == $"{embeddedFileNamespace}.{resourceName}".ToLower()))
{ // 处理刷新界面
await RespondWithIndexHtml(httpContext.Response);
return;
}
}
}
await staticFileMiddleware.Invoke(httpContext);
}
19
View Source File : GodotOnReadySourceGenerator.cs
License : MIT License
Project Creator : 31
License : MIT License
Project Creator : 31
public void Execute(GeneratorExecutionContext context)
{
// If this isn't working, run 'dotnet build-server shutdown' first.
if (Environment
.GetEnvironmentVariable($"Debug{nameof(GodotOnReadySourceGenerator)}") == "true")
{
Debugger.Launch();
}
var receiver = context.SyntaxReceiver as OnReadyReceiver ?? throw new Exception();
INamedTypeSymbol GetSymbolByName(string fullName) =>
context.Compilation.GetTypeByMetadataName(fullName)
?? throw new Exception($"Can't find {fullName}");
var onReadyGetSymbol = GetSymbolByName("GodotOnReady.Attributes.OnReadyGetAttribute");
var onReadySymbol = GetSymbolByName("GodotOnReady.Attributes.OnReadyAttribute");
var generateDataSelectorEnumSymbol =
GetSymbolByName("GodotOnReady.Attributes.GenerateDataSelectorEnumAttribute");
var resourceSymbol = GetSymbolByName("Godot.Resource");
var nodeSymbol = GetSymbolByName("Godot.Node");
List<PartialClreplacedAddition> additions = new();
var clreplacedSymbols = receiver.AllClreplacedes
.Select(clreplacedDecl =>
{
INamedTypeSymbol? clreplacedSymbol = context.Compilation
.GetSemanticModel(clreplacedDecl.SyntaxTree)
.GetDeclaredSymbol(clreplacedDecl);
if (clreplacedSymbol is null)
{
context.ReportDiagnostic(
Diagnostic.Create(
new DiagnosticDescriptor(
"GORSG0001",
"Inspection",
$"Unable to find declared symbol for {clreplacedDecl}. Skipping.",
"GORSG.Parsing",
DiagnosticSeverity.Warning,
true
),
clreplacedDecl.GetLocation()
)
);
}
return clreplacedSymbol;
})
.Distinct(SymbolEqualityComparer.Default)
.OfType<INamedTypeSymbol>();
foreach (var clreplacedSymbol in clreplacedSymbols)
{
foreach (var attribute in clreplacedSymbol.GetAttributes()
.Where(a => Equal(a.AttributeClreplaced, generateDataSelectorEnumSymbol)))
{
var fields = clreplacedSymbol.GetMembers()
.OfType<IFieldSymbol>()
.Where(f => f.IsReadOnly && f.IsStatic)
.ToArray();
additions.Add(new DataSelectorEnumAddition(
fields,
new AttributeSite(clreplacedSymbol, attribute)));
}
var members = Enumerable
.Concat(
clreplacedSymbol.GetMembers().OfType<IPropertySymbol>().Select(MemberSymbol.Create),
clreplacedSymbol.GetMembers().OfType<IFieldSymbol>().Select(MemberSymbol.Create))
.ToArray();
foreach (var member in members)
{
foreach (var attribute in member.Symbol
.GetAttributes()
.Where(a => Equal(a.AttributeClreplaced, onReadyGetSymbol)))
{
var site = new MemberAttributeSite(
member,
new AttributeSite(clreplacedSymbol, attribute));
if (site.AttributeSite.Attribute.NamedArguments.Any(
a => a.Key == "Property" && a.Value.Value is string { Length: > 0 }))
{
additions.Add(new OnReadyGetNodePropertyAddition(site));
}
else if (member.Type.IsOfBaseType(nodeSymbol))
{
additions.Add(new OnReadyGetNodeAddition(site));
}
else if (member.Type.IsOfBaseType(resourceSymbol))
{
additions.Add(new OnReadyGetResourceAddition(site));
}
else
{
string issue =
$"The type '{member.Type}' of '{member.Symbol}' is not supported." +
" Expected a Resource or Node subclreplaced.";
context.ReportDiagnostic(
Diagnostic.Create(
new DiagnosticDescriptor(
"GORSG0002",
"Inspection",
issue,
"GORSG.Parsing",
DiagnosticSeverity.Error,
true
),
member.Symbol.Locations.FirstOrDefault()
)
);
}
}
}
foreach (var methodSymbol in clreplacedSymbol.GetMembers().OfType<IMethodSymbol>())
{
foreach (var attribute in methodSymbol
.GetAttributes()
.Where(a => Equal(a.AttributeClreplaced, onReadySymbol)))
{
additions.Add(new OnReadyAddition(methodSymbol, attribute, clreplacedSymbol));
}
}
}
foreach (var clreplacedAdditionGroup in additions.GroupBy(a => a.Clreplaced))
{
SourceStringBuilder source = CreateInitializedSourceBuilder();
if (clreplacedAdditionGroup.Key is not { } clreplacedSymbol) continue;
source.NamespaceBlockBraceIfExists(clreplacedSymbol.GetSymbolNamespaceName(), () =>
{
source.Line("public partial clreplaced ", clreplacedAdditionGroup.Key.Name);
source.BlockBrace(() =>
{
foreach (var addition in clreplacedAdditionGroup)
{
addition.DeclarationWriter?.Invoke(source);
}
if (clreplacedAdditionGroup.Any(a => a.ConstructorStatementWriter is not null))
{
source.Line();
source.Line("public ", clreplacedAdditionGroup.Key.Name, "()");
source.BlockBrace(() =>
{
foreach (var addition in clreplacedAdditionGroup.OrderBy(a => a.Order))
{
addition.ConstructorStatementWriter?.Invoke(source);
}
source.Line("Constructor();");
});
source.Line("partial void Constructor();");
}
if (clreplacedAdditionGroup.Any(a => a.OnReadyStatementWriter is not null))
{
source.Line();
source.Line("public override void _Ready()");
source.BlockBrace(() =>
{
source.Line("base._Ready();");
// OrderBy is a stable sort.
// Sort by Order, then by discovery order (implicitly).
foreach (var addition in clreplacedAdditionGroup.OrderBy(a => a.Order))
{
addition.OnReadyStatementWriter?.Invoke(source);
}
});
}
});
foreach (var addition in clreplacedAdditionGroup)
{
addition.OutsideClreplacedStatementWriter?.Invoke(source);
}
});
string escapedNamespace =
clreplacedAdditionGroup.Key.GetSymbolNamespaceName()?.Replace(".", "_") ?? "";
context.AddSource(
$"Partial_{escapedNamespace}_{clreplacedAdditionGroup.Key.Name}",
source.ToString());
}
}
19
View Source File : LeapHandsAutoRig.cs
License : MIT License
Project Creator : 39M
License : MIT License
Project Creator : 39M
[ContextMenu("AutoRigByName")]
void AutoRigByName() {
List<string> LeftHandStrings = new List<string> { "left" };
List<string> RightHandStrings = new List<string> { "right" };
//replacedigning these here since this component gets added and used at editor time
HandPoolToPopulate = GameObject.FindObjectOfType<HandPool>();
Reset();
//Find hands and replacedigns RiggedHands
Transform Hand_L = null;
foreach (Transform t in transform) {
if (LeftHandStrings.Any(w => t.name.ToLower().Contains(w))) {
Hand_L = t;
}
}
if (Hand_L != null) {
RiggedHand_L = Hand_L.gameObject.AddComponent<RiggedHand>();
HandTransitionBehavior_L = Hand_L.gameObject.AddComponent<HandEnableDisable>();
RiggedHand_L.Handedness = Chirality.Left;
RiggedHand_L.SetEditorLeapPose = false;
RiggedHand_L.UseMetaCarpals = UseMetaCarpals;
RiggedHand_L.SetupRiggedHand();
RiggedFinger_L_Thumb = (RiggedFinger)RiggedHand_L.fingers[0];
RiggedFinger_L_Index = (RiggedFinger)RiggedHand_L.fingers[1];
RiggedFinger_L_Mid = (RiggedFinger)RiggedHand_L.fingers[2];
RiggedFinger_L_Ring = (RiggedFinger)RiggedHand_L.fingers[3];
RiggedFinger_L_Pinky = (RiggedFinger)RiggedHand_L.fingers[4];
modelFingerPointing_L = RiggedHand_L.modelFingerPointing;
modelPalmFacing_L = RiggedHand_L.modelPalmFacing;
RiggedHand_L.StoreJointsStartPose();
}
Transform Hand_R = null;
foreach (Transform t in transform) {
if (RightHandStrings.Any(w => t.name.ToLower().Contains(w))) {
Hand_R = t;
}
}
if (Hand_R != null) {
RiggedHand_R = Hand_R.gameObject.AddComponent<RiggedHand>();
HandTransitionBehavior_R = Hand_R.gameObject.AddComponent<HandEnableDisable>();
RiggedHand_R.Handedness = Chirality.Right;
RiggedHand_R.SetEditorLeapPose = false;
RiggedHand_R.UseMetaCarpals = UseMetaCarpals;
RiggedHand_R.SetupRiggedHand();
RiggedFinger_R_Thumb = (RiggedFinger)RiggedHand_R.fingers[0];
RiggedFinger_R_Index = (RiggedFinger)RiggedHand_R.fingers[1];
RiggedFinger_R_Mid = (RiggedFinger)RiggedHand_R.fingers[2];
RiggedFinger_R_Ring = (RiggedFinger)RiggedHand_R.fingers[3];
RiggedFinger_R_Pinky = (RiggedFinger)RiggedHand_R.fingers[4];
modelFingerPointing_R = RiggedHand_R.modelFingerPointing;
modelPalmFacing_R = RiggedHand_R.modelPalmFacing;
RiggedHand_R.StoreJointsStartPose();
}
//Find palms and replacedign to RiggedHands
//RiggedHand_L.palm = AnimatorForMapping.GetBoneTransform(HumanBodyBones.LeftHand);
//RiggedHand_R.palm = AnimatorForMapping.GetBoneTransform(HumanBodyBones.RightHand);
if (ModelGroupName == "" || ModelGroupName != null) {
ModelGroupName = transform.name;
}
HandPoolToPopulate.AddNewGroup(ModelGroupName, RiggedHand_L, RiggedHand_R);
}
19
View Source File : RiggedHand.cs
License : MIT License
Project Creator : 39M
License : MIT License
Project Creator : 39M
private void replacedignRiggedFingersByName(){
List<string> palmStrings = new List<string> { "palm"};
List<string> thumbStrings = new List<string> { "thumb", "tmb" };
List<string> indexStrings = new List<string> { "index", "idx"};
List<string> middleStrings = new List<string> { "middle", "mid"};
List<string> ringStrings = new List<string> { "ring"};
List<string> pinkyStrings = new List<string> { "pinky", "pin"};
//find palm by name
//Transform palm = null;
Transform thumb = null;
Transform index = null;
Transform middle = null;
Transform ring = null;
Transform pinky = null;
Transform[] children = transform.GetComponentsInChildren<Transform>();
if (palmStrings.Any(w => transform.name.ToLower().Contains(w))){
base.palm = transform;
}
else{
foreach (Transform t in children) {
if (palmStrings.Any(w => t.name.ToLower().Contains(w)) == true) {
base.palm = t;
}
}
}
if (!palm) {
palm = transform;
}
if (palm) {
foreach (Transform t in children) {
RiggedFinger preExistingRiggedFinger;
preExistingRiggedFinger = t.GetComponent<RiggedFinger>();
string lowercaseName = t.name.ToLower();
if (!preExistingRiggedFinger) {
if (thumbStrings.Any(w => lowercaseName.Contains(w)) && t.parent == palm) {
thumb = t;
RiggedFinger newRiggedFinger = thumb.gameObject.AddComponent<RiggedFinger>();
newRiggedFinger.fingerType = Finger.FingerType.TYPE_THUMB;
}
if (indexStrings.Any(w => lowercaseName.Contains(w)) && t.parent == palm) {
index = t;
RiggedFinger newRiggedFinger = index.gameObject.AddComponent<RiggedFinger>();
newRiggedFinger.fingerType = Finger.FingerType.TYPE_INDEX;
}
if (middleStrings.Any(w => lowercaseName.Contains(w)) && t.parent == palm) {
middle = t;
RiggedFinger newRiggedFinger = middle.gameObject.AddComponent<RiggedFinger>();
newRiggedFinger.fingerType = Finger.FingerType.TYPE_MIDDLE;
}
if (ringStrings.Any(w => lowercaseName.Contains(w)) && t.parent == palm) {
ring = t;
RiggedFinger newRiggedFinger = ring.gameObject.AddComponent<RiggedFinger>();
newRiggedFinger.fingerType = Finger.FingerType.TYPE_RING;
}
if (pinkyStrings.Any(w => lowercaseName.Contains(w)) && t.parent == palm) {
pinky = t;
RiggedFinger newRiggedFinger = pinky.gameObject.AddComponent<RiggedFinger>();
newRiggedFinger.fingerType = Finger.FingerType.TYPE_PINKY;
}
}
}
}
}
19
View Source File : RiggedHand.cs
License : MIT License
Project Creator : 39M
License : MIT License
Project Creator : 39M
private void replacedignRiggedFingersByName(){
List<string> palmStrings = new List<string> { "palm"};
List<string> thumbStrings = new List<string> { "thumb", "tmb" };
List<string> indexStrings = new List<string> { "index", "idx"};
List<string> middleStrings = new List<string> { "middle", "mid"};
List<string> ringStrings = new List<string> { "ring"};
List<string> pinkyStrings = new List<string> { "pinky", "pin"};
//find palm by name
//Transform palm = null;
Transform thumb = null;
Transform index = null;
Transform middle = null;
Transform ring = null;
Transform pinky = null;
Transform[] children = transform.GetComponentsInChildren<Transform>();
if (palmStrings.Any(w => transform.name.ToLower().Contains(w))){
base.palm = transform;
}
else{
foreach (Transform t in children) {
if (palmStrings.Any(w => t.name.ToLower().Contains(w)) == true) {
base.palm = t;
}
}
}
if (!palm) {
palm = transform;
}
if (palm) {
foreach (Transform t in children) {
RiggedFinger preExistingRiggedFinger;
preExistingRiggedFinger = t.GetComponent<RiggedFinger>();
string lowercaseName = t.name.ToLower();
if (!preExistingRiggedFinger) {
if (thumbStrings.Any(w => lowercaseName.Contains(w)) && t.parent == palm) {
thumb = t;
RiggedFinger newRiggedFinger = thumb.gameObject.AddComponent<RiggedFinger>();
newRiggedFinger.fingerType = Finger.FingerType.TYPE_THUMB;
}
if (indexStrings.Any(w => lowercaseName.Contains(w)) && t.parent == palm) {
index = t;
RiggedFinger newRiggedFinger = index.gameObject.AddComponent<RiggedFinger>();
newRiggedFinger.fingerType = Finger.FingerType.TYPE_INDEX;
}
if (middleStrings.Any(w => lowercaseName.Contains(w)) && t.parent == palm) {
middle = t;
RiggedFinger newRiggedFinger = middle.gameObject.AddComponent<RiggedFinger>();
newRiggedFinger.fingerType = Finger.FingerType.TYPE_MIDDLE;
}
if (ringStrings.Any(w => lowercaseName.Contains(w)) && t.parent == palm) {
ring = t;
RiggedFinger newRiggedFinger = ring.gameObject.AddComponent<RiggedFinger>();
newRiggedFinger.fingerType = Finger.FingerType.TYPE_RING;
}
if (pinkyStrings.Any(w => lowercaseName.Contains(w)) && t.parent == palm) {
pinky = t;
RiggedFinger newRiggedFinger = pinky.gameObject.AddComponent<RiggedFinger>();
newRiggedFinger.fingerType = Finger.FingerType.TYPE_PINKY;
}
}
}
}
}
19
View Source File : ProtectedApiCallHelper.cs
License : GNU General Public License v3.0
Project Creator : 3xpl01tc0d3r
License : GNU General Public License v3.0
Project Creator : 3xpl01tc0d3r
public async Task<JObject> CallGetWebApiAndProcessResultASync(string webApiUrl, string accessToken)
{
JObject result = null;
if (!string.IsNullOrEmpty(accessToken))
{
var defaultRequetHeaders = HttpClient.DefaultRequestHeaders;
if (defaultRequetHeaders.Accept == null || !defaultRequetHeaders.Accept.Any(m => m.MediaType == "application/json"))
{
HttpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
}
defaultRequetHeaders.Authorization = new AuthenticationHeaderValue("bearer", accessToken);
HttpResponseMessage response = await HttpClient.GetAsync(webApiUrl);
if (response.IsSuccessStatusCode)
{
var json = await response.Content.ReadreplacedtringAsync();
result = JsonConvert.DeserializeObject(json) as JObject;
Console.ForegroundColor = ConsoleColor.Gray;
}
else
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine($"Failed to call the Web Api: {response.StatusCode}");
JObject content = JObject.Parse(await response.Content.ReadreplacedtringAsync());
Console.WriteLine($"Content: {content}");
result = content;
}
Console.ResetColor();
}
return result;
}
19
View Source File : GCodeParser.cs
License : MIT License
Project Creator : 3RD-Dimension
License : MIT License
Project Creator : 3RD-Dimension
static void Parse(string line, int lineNumber)
{
MatchCollection matches = GCodeSplitter.Matches(line);
List<Word> Words = new List<Word>(matches.Count);
foreach (Match match in matches)
{
Words.Add(new Word() { Command = match.Groups[1].Value[0], Parameter = double.Parse(match.Groups[2].Value, Constants.DecimalParseFormat) });
}
for (int i = 0; i < Words.Count; i++)
{
if (Words[i].Command == 'N')
{
Words.RemoveAt(i--);
continue;
}
if (IgnoreAxes.Contains(Words[i].Command) && Properties.Settings.Default.IgnoreAdditionalAxes)
{
Words.RemoveAt(i--);
continue;
}
if (!ValidWords.Contains(Words[i].Command))
{
Warnings.Add($"ignoring unknown word (letter): \"{Words[i]}\". (line {lineNumber})");
Words.RemoveAt(i--);
continue;
}
if (Words[i].Command != 'F')
continue;
State.Feed = Words[i].Parameter;
if (State.Unit == ParseUnit.Imperial)
State.Feed *= 25.4;
Words.RemoveAt(i--);
continue;
}
for (int i = 0; i < Words.Count; i++)
{
if (Words[i].Command == 'M')
{
int param = (int)Words[i].Parameter;
if (param != Words[i].Parameter || param < 0)
throw new ParseException("M code can only have positive integer parameters", lineNumber);
Commands.Add(new MCode() { Code = param, LineNumber = lineNumber });
Words.RemoveAt(i);
i--;
continue;
}
if (Words[i].Command == 'S')
{
double param = Words[i].Parameter;
if (param < 0)
Warnings.Add($"spindle speed must be positive. (line {lineNumber})");
Commands.Add(new Spindle() { Speed = Math.Abs(param), LineNumber = lineNumber });
Words.RemoveAt(i);
i--;
continue;
}
if (Words[i].Command == 'G' && !MotionCommands.Contains(Words[i].Parameter))
{
#region UnitPlaneDistanceMode
double param = Words[i].Parameter;
if (param == 90)
{
State.DistanceMode = ParseDistanceMode.Absolute;
Words.RemoveAt(i);
i--;
continue;
}
if (param == 91)
{
State.DistanceMode = ParseDistanceMode.Incremental;
Words.RemoveAt(i);
i--;
continue;
}
if (param == 90.1)
{
State.ArcDistanceMode = ParseDistanceMode.Absolute;
Words.RemoveAt(i);
continue;
}
if (param == 91.1)
{
State.ArcDistanceMode = ParseDistanceMode.Incremental;
Words.RemoveAt(i);
i--;
continue;
}
if (param == 21)
{
State.Unit = ParseUnit.Metric;
Words.RemoveAt(i);
i--;
continue;
}
if (param == 20)
{
State.Unit = ParseUnit.Imperial;
Words.RemoveAt(i);
i--;
continue;
}
if (param == 17)
{
State.Plane = ArcPlane.XY;
Words.RemoveAt(i);
i--;
continue;
}
if (param == 18)
{
State.Plane = ArcPlane.ZX;
Words.RemoveAt(i);
i--;
continue;
}
if (param == 19)
{
State.Plane = ArcPlane.YZ;
Words.RemoveAt(i);
i--;
continue;
}
if (param == 4)
{
if (Words.Count >= 2 && Words[i + 1].Command == 'P')
{
if (Words[i + 1].Parameter < 0)
Warnings.Add($"dwell time must be positive. (line {lineNumber})");
Commands.Add(new Dwell() { Seconds = Math.Abs(Words[i + 1].Parameter), LineNumber = lineNumber });
Words.RemoveAt(i + 1);
Words.RemoveAt(i);
i--;
continue;
}
}
Warnings.Add($"ignoring unknown command G{param}. (line {lineNumber})");
Words.RemoveAt(i--);
#endregion
}
}
if (Words.Count == 0)
return;
int MotionMode = State.LastMotionMode;
if (Words.First().Command == 'G')
{
MotionMode = (int)Words.First().Parameter;
State.LastMotionMode = MotionMode;
Words.RemoveAt(0);
}
if (MotionMode < 0)
throw new ParseException("no motion mode active", lineNumber);
double UnitMultiplier = (State.Unit == ParseUnit.Metric) ? 1 : 25.4;
Vector3 EndPos = State.Position;
if (State.DistanceMode == ParseDistanceMode.Incremental && State.PositionValid.Any(isValid => !isValid))
{
throw new ParseException("incremental motion is only allowed after an absolute position has been established (eg. with \"G90 G0 X0 Y0 Z5\")", lineNumber);
}
if ((MotionMode == 2 || MotionMode == 3) && State.PositionValid.Any(isValid => !isValid))
{
throw new ParseException("arcs (G2/G3) are only allowed after an absolute position has been established (eg. with \"G90 G0 X0 Y0 Z5\")", lineNumber);
}
#region FindEndPos
{
int Incremental = (State.DistanceMode == ParseDistanceMode.Incremental) ? 1 : 0;
for (int i = 0; i < Words.Count; i++)
{
if (Words[i].Command != 'X')
continue;
EndPos.X = Words[i].Parameter * UnitMultiplier + Incremental * EndPos.X;
Words.RemoveAt(i);
State.PositionValid[0] = true;
break;
}
for (int i = 0; i < Words.Count; i++)
{
if (Words[i].Command != 'Y')
continue;
EndPos.Y = Words[i].Parameter * UnitMultiplier + Incremental * EndPos.Y;
Words.RemoveAt(i);
State.PositionValid[1] = true;
break;
}
for (int i = 0; i < Words.Count; i++)
{
if (Words[i].Command != 'Z')
continue;
EndPos.Z = Words[i].Parameter * UnitMultiplier + Incremental * EndPos.Z;
Words.RemoveAt(i);
State.PositionValid[2] = true;
break;
}
}
#endregion
if (MotionMode != 0 && State.Feed <= 0)
{
throw new ParseException("feed rate undefined", lineNumber);
}
if (MotionMode == 1 && State.PositionValid.Any(isValid => !isValid))
{
Warnings.Add($"a feed move is used before an absolute position is established, height maps will not be applied to this motion. (line {lineNumber})");
}
if (MotionMode <= 1)
{
if (Words.Count > 0)
Warnings.Add($"motion command must be last in line (ignoring unused words {string.Join(" ", Words)} in block). (line {lineNumber})");
Line motion = new Line();
motion.Start = State.Position;
motion.End = EndPos;
motion.Feed = State.Feed;
motion.Rapid = MotionMode == 0;
motion.LineNumber = lineNumber;
State.PositionValid.CopyTo(motion.PositionValid, 0);
Commands.Add(motion);
State.Position = EndPos;
return;
}
double U, V;
bool IJKused = false;
switch (State.Plane)
{
default:
U = State.Position.X;
V = State.Position.Y;
break;
case ArcPlane.YZ:
U = State.Position.Y;
V = State.Position.Z;
break;
case ArcPlane.ZX:
U = State.Position.Z;
V = State.Position.X;
break;
}
#region FindIJK
{
int ArcIncremental = (State.ArcDistanceMode == ParseDistanceMode.Incremental) ? 1 : 0;
for (int i = 0; i < Words.Count; i++)
{
if (Words[i].Command != 'I')
continue;
switch (State.Plane)
{
case ArcPlane.XY:
U = Words[i].Parameter * UnitMultiplier + ArcIncremental * State.Position.X;
break;
case ArcPlane.YZ:
throw new ParseException("current plane is YZ, I word is invalid", lineNumber);
case ArcPlane.ZX:
V = Words[i].Parameter * UnitMultiplier + ArcIncremental * State.Position.X;
break;
}
IJKused = true;
Words.RemoveAt(i);
break;
}
for (int i = 0; i < Words.Count; i++)
{
if (Words[i].Command != 'J')
continue;
switch (State.Plane)
{
case ArcPlane.XY:
V = Words[i].Parameter * UnitMultiplier + ArcIncremental * State.Position.Y;
break;
case ArcPlane.YZ:
U = Words[i].Parameter * UnitMultiplier + ArcIncremental * State.Position.Y;
break;
case ArcPlane.ZX:
throw new ParseException("current plane is ZX, J word is invalid", lineNumber);
}
IJKused = true;
Words.RemoveAt(i);
break;
}
for (int i = 0; i < Words.Count; i++)
{
if (Words[i].Command != 'K')
continue;
switch (State.Plane)
{
case ArcPlane.XY:
throw new ParseException("current plane is XY, K word is invalid", lineNumber);
case ArcPlane.YZ:
V = Words[i].Parameter * UnitMultiplier + ArcIncremental * State.Position.Z;
break;
case ArcPlane.ZX:
U = Words[i].Parameter * UnitMultiplier + ArcIncremental * State.Position.Z;
break;
}
IJKused = true;
Words.RemoveAt(i);
break;
}
}
#endregion
#region ResolveRadius
for (int i = 0; i < Words.Count; i++)
{
if (Words[i].Command != 'R')
continue;
if (IJKused)
throw new ParseException("both IJK and R notation used", lineNumber);
if (State.Position == EndPos)
throw new ParseException("arcs in R-notation must have non-coincident start and end points", lineNumber);
double Radius = Words[i].Parameter * UnitMultiplier;
if (Radius == 0)
throw new ParseException("radius can't be zero", lineNumber);
double A, B;
switch (State.Plane)
{
default:
A = EndPos.X;
B = EndPos.Y;
break;
case ArcPlane.YZ:
A = EndPos.Y;
B = EndPos.Z;
break;
case ArcPlane.ZX:
A = EndPos.Z;
B = EndPos.X;
break;
}
A -= U; //(AB) = vector from start to end of arc along the axes of the current plane
B -= V;
//see grbl/gcode.c
double h_x2_div_d = 4.0 * (Radius * Radius) - (A * A + B * B);
if (h_x2_div_d < 0)
{
throw new ParseException("arc radius too small to reach both ends", lineNumber);
}
h_x2_div_d = -Math.Sqrt(h_x2_div_d) / Math.Sqrt(A * A + B * B);
if (MotionMode == 3 ^ Radius < 0)
{
h_x2_div_d = -h_x2_div_d;
}
U += 0.5 * (A - (B * h_x2_div_d));
V += 0.5 * (B + (A * h_x2_div_d));
Words.RemoveAt(i);
break;
}
#endregion
if (Words.Count > 0)
Warnings.Add($"motion command must be last in line (ignoring unused words {string.Join(" ", Words)} in block). (line {lineNumber})");
Arc arc = new Arc();
arc.Start = State.Position;
arc.End = EndPos;
arc.Feed = State.Feed;
arc.Direction = (MotionMode == 2) ? ArcDirection.CW : ArcDirection.CCW;
arc.U = U;
arc.V = V;
arc.LineNumber = lineNumber;
arc.Plane = State.Plane;
Commands.Add(arc);
State.Position = EndPos;
return;
}
19
View Source File : ProtectedApiCallHelper.cs
License : GNU General Public License v3.0
Project Creator : 3xpl01tc0d3r
License : GNU General Public License v3.0
Project Creator : 3xpl01tc0d3r
public async Task<string> CallGetHTMLWebApiAndProcessResultASync(string webApiUrl, string accessToken)
{
string result = null;
if (!string.IsNullOrEmpty(accessToken))
{
var defaultRequetHeaders = HttpClient.DefaultRequestHeaders;
if (defaultRequetHeaders.Accept == null || !defaultRequetHeaders.Accept.Any(m => m.MediaType == "application/json"))
{
HttpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
}
defaultRequetHeaders.Authorization = new AuthenticationHeaderValue("bearer", accessToken);
HttpResponseMessage response = await HttpClient.GetAsync(webApiUrl);
if (response.IsSuccessStatusCode)
{
result = await response.Content.ReadreplacedtringAsync();
Console.ForegroundColor = ConsoleColor.Gray;
}
else
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine($"Failed to call the Web Api: {response.StatusCode}");
result = await response.Content.ReadreplacedtringAsync();
Console.WriteLine($"Content: {result}");
}
Console.ResetColor();
}
return result;
}
19
View Source File : ProtectedApiCallHelper.cs
License : GNU General Public License v3.0
Project Creator : 3xpl01tc0d3r
License : GNU General Public License v3.0
Project Creator : 3xpl01tc0d3r
public async Task<JObject> CallPostWebApiAndProcessResultASync(string webApiUrl, string accessToken, string data)
{
JObject result = null;
if (!string.IsNullOrEmpty(accessToken))
{
var defaultRequetHeaders = HttpClient.DefaultRequestHeaders;
if (defaultRequetHeaders.Accept == null || !defaultRequetHeaders.Accept.Any(m => m.MediaType == "application/json"))
{
HttpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
}
defaultRequetHeaders.Authorization = new AuthenticationHeaderValue("bearer", accessToken);
var body = new StringContent(data, Encoding.UTF8, "application/json");
HttpResponseMessage response = await HttpClient.PostAsync(webApiUrl, body);
if (response.IsSuccessStatusCode)
{
string json = await response.Content.ReadreplacedtringAsync();
result = JsonConvert.DeserializeObject(json) as JObject;
Console.ForegroundColor = ConsoleColor.Gray;
}
else
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine($"Failed to call the Web Api: {response.StatusCode}");
JObject content = JObject.Parse(await response.Content.ReadreplacedtringAsync());
Console.WriteLine($"Content: {content}");
result = content;
}
Console.ResetColor();
}
return result;
}
19
View Source File : ProtectedApiCallHelper.cs
License : GNU General Public License v3.0
Project Creator : 3xpl01tc0d3r
License : GNU General Public License v3.0
Project Creator : 3xpl01tc0d3r
public async Task<JObject> CallPatchWebApiAndProcessResultASync(string webApiUrl, string accessToken, string data)
{
JObject result = null;
if (!string.IsNullOrEmpty(accessToken))
{
var defaultRequetHeaders = HttpClient.DefaultRequestHeaders;
if (defaultRequetHeaders.Accept == null || !defaultRequetHeaders.Accept.Any(m => m.MediaType == "application/json"))
{
HttpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
}
defaultRequetHeaders.Authorization = new AuthenticationHeaderValue("bearer", accessToken);
var body = new StringContent(data, Encoding.UTF8, "application/json");
HttpResponseMessage response = await HttpClient.PatchAsync(webApiUrl, body);
if (response.IsSuccessStatusCode)
{
string json = await response.Content.ReadreplacedtringAsync();
result = JsonConvert.DeserializeObject(json) as JObject;
Console.ForegroundColor = ConsoleColor.Gray;
}
else
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine($"Failed to call the Web Api: {response.StatusCode}");
JObject content = JObject.Parse(await response.Content.ReadreplacedtringAsync());
Console.WriteLine($"Content: {content}");
result = content;
}
Console.ResetColor();
}
return result;
}
19
View Source File : Line.cs
License : MIT License
Project Creator : 3RD-Dimension
License : MIT License
Project Creator : 3RD-Dimension
public override IEnumerable<Motion> Split(double length)
{
if (Rapid || PositionValid.Any(isValid => !isValid)) //don't split up rapid or not fully defined motions
{
yield return this;
yield break;
}
int divisions = (int)Math.Ceiling(Length / length);
if (divisions < 1)
divisions = 1;
Vector3 lastEnd = Start;
for (int i = 1; i <= divisions; i++)
{
Vector3 end = Interpolate(((double)i) / divisions);
Line immediate = new Line();
immediate.Start = lastEnd;
immediate.End = end;
immediate.Feed = Feed;
immediate.PositionValid = new bool[] { true, true, true };
yield return immediate;
lastEnd = end;
}
}
19
View Source File : ProtectedApiCallHelper.cs
License : GNU General Public License v3.0
Project Creator : 3xpl01tc0d3r
License : GNU General Public License v3.0
Project Creator : 3xpl01tc0d3r
public async Task<JObject> CallDeleteWebApiAndProcessResultASync(string webApiUrl, string accessToken)
{
JObject result = null;
if (!string.IsNullOrEmpty(accessToken))
{
var defaultRequetHeaders = HttpClient.DefaultRequestHeaders;
if (defaultRequetHeaders.Accept == null || !defaultRequetHeaders.Accept.Any(m => m.MediaType == "application/json"))
{
HttpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
}
defaultRequetHeaders.Authorization = new AuthenticationHeaderValue("bearer", accessToken);
HttpResponseMessage response = await HttpClient.DeleteAsync(webApiUrl);
if (response.IsSuccessStatusCode)
{
var json = await response.Content.ReadreplacedtringAsync();
result = JsonConvert.DeserializeObject(json) as JObject;
Console.ForegroundColor = ConsoleColor.Gray;
}
else
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine($"Failed to call the Web Api: {response.StatusCode}");
JObject content = JObject.Parse(await response.Content.ReadreplacedtringAsync());
Console.WriteLine($"Content: {content}");
result = content;
}
Console.ResetColor();
}
return result;
}
19
View Source File : ProtectedApiCallHelper.cs
License : GNU General Public License v3.0
Project Creator : 3xpl01tc0d3r
License : GNU General Public License v3.0
Project Creator : 3xpl01tc0d3r
public async Task<JObject> CallGetWebApiAndProcessResultASync(string webApiUrl, string accessToken)
{
JObject result = null;
if (!string.IsNullOrEmpty(accessToken))
{
var defaultRequetHeaders = HttpClient.DefaultRequestHeaders;
if (defaultRequetHeaders.Accept == null || !defaultRequetHeaders.Accept.Any(m => m.MediaType == "application/json"))
{
HttpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
}
defaultRequetHeaders.Authorization = new AuthenticationHeaderValue("bearer", accessToken);
HttpResponseMessage response = await HttpClient.GetAsync(webApiUrl);
if (response.IsSuccessStatusCode)
{
var json = await response.Content.ReadreplacedtringAsync();
result = JsonConvert.DeserializeObject(json) as JObject;
//Console.ForegroundColor = ConsoleColor.Gray;
}
else
{
//Console.ForegroundColor = ConsoleColor.Red;
//Console.WriteLine($"Failed to call the Web Api: {response.StatusCode}");
JObject content = JObject.Parse(await response.Content.ReadreplacedtringAsync());
//Console.WriteLine($"Content: {content}");
result = content;
}
//Console.ResetColor();
}
return result;
}
19
View Source File : ProtectedApiCallHelper.cs
License : GNU General Public License v3.0
Project Creator : 3xpl01tc0d3r
License : GNU General Public License v3.0
Project Creator : 3xpl01tc0d3r
public async Task<string> CallGetHTMLWebApiAndProcessResultASync(string webApiUrl, string accessToken)
{
string result = null;
if (!string.IsNullOrEmpty(accessToken))
{
var defaultRequetHeaders = HttpClient.DefaultRequestHeaders;
if (defaultRequetHeaders.Accept == null || !defaultRequetHeaders.Accept.Any(m => m.MediaType == "application/json"))
{
HttpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
}
defaultRequetHeaders.Authorization = new AuthenticationHeaderValue("bearer", accessToken);
HttpResponseMessage response = await HttpClient.GetAsync(webApiUrl);
if (response.IsSuccessStatusCode)
{
result = await response.Content.ReadreplacedtringAsync();
//Console.ForegroundColor = ConsoleColor.Gray;
}
else
{
//Console.ForegroundColor = ConsoleColor.Red;
//Console.WriteLine($"Failed to call the Web Api: {response.StatusCode}");
result = await response.Content.ReadreplacedtringAsync();
//Console.WriteLine($"Content: {result}");
}
//Console.ResetColor();
}
return result;
}
19
View Source File : ProtectedApiCallHelper.cs
License : GNU General Public License v3.0
Project Creator : 3xpl01tc0d3r
License : GNU General Public License v3.0
Project Creator : 3xpl01tc0d3r
public async Task<JObject> CallPostWebApiAndProcessResultASync(string webApiUrl, string accessToken, string data)
{
JObject result = null;
if (!string.IsNullOrEmpty(accessToken))
{
var defaultRequetHeaders = HttpClient.DefaultRequestHeaders;
if (defaultRequetHeaders.Accept == null || !defaultRequetHeaders.Accept.Any(m => m.MediaType == "application/json"))
{
HttpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
}
defaultRequetHeaders.Authorization = new AuthenticationHeaderValue("bearer", accessToken);
var body = new StringContent(data, Encoding.UTF8, "application/json");
HttpResponseMessage response = await HttpClient.PostAsync(webApiUrl, body);
if (response.IsSuccessStatusCode)
{
string json = await response.Content.ReadreplacedtringAsync();
result = JsonConvert.DeserializeObject(json) as JObject;
//Console.ForegroundColor = ConsoleColor.Gray;
}
else
{
//Console.ForegroundColor = ConsoleColor.Red;
//Console.WriteLine($"Failed to call the Web Api: {response.StatusCode}");
JObject content = JObject.Parse(await response.Content.ReadreplacedtringAsync());
//Console.WriteLine($"Content: {content}");
result = content;
}
//Console.ResetColor();
}
return result;
}
19
View Source File : ProtectedApiCallHelper.cs
License : GNU General Public License v3.0
Project Creator : 3xpl01tc0d3r
License : GNU General Public License v3.0
Project Creator : 3xpl01tc0d3r
public async Task<JObject> CallPatchWebApiAndProcessResultASync(string webApiUrl, string accessToken, string data)
{
JObject result = null;
if (!string.IsNullOrEmpty(accessToken))
{
var defaultRequetHeaders = HttpClient.DefaultRequestHeaders;
if (defaultRequetHeaders.Accept == null || !defaultRequetHeaders.Accept.Any(m => m.MediaType == "application/json"))
{
HttpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
}
defaultRequetHeaders.Authorization = new AuthenticationHeaderValue("bearer", accessToken);
var body = new StringContent(data, Encoding.UTF8, "application/json");
HttpResponseMessage response = await HttpClient.PatchAsync(webApiUrl, body);
if (response.IsSuccessStatusCode)
{
string json = await response.Content.ReadreplacedtringAsync();
result = JsonConvert.DeserializeObject(json) as JObject;
//Console.ForegroundColor = ConsoleColor.Gray;
}
else
{
//Console.ForegroundColor = ConsoleColor.Red;
//Console.WriteLine($"Failed to call the Web Api: {response.StatusCode}");
JObject content = JObject.Parse(await response.Content.ReadreplacedtringAsync());
//Console.WriteLine($"Content: {content}");
result = content;
}
//Console.ResetColor();
}
return result;
}
19
View Source File : ProtectedApiCallHelper.cs
License : GNU General Public License v3.0
Project Creator : 3xpl01tc0d3r
License : GNU General Public License v3.0
Project Creator : 3xpl01tc0d3r
public async Task<JObject> CallDeleteWebApiAndProcessResultASync(string webApiUrl, string accessToken)
{
JObject result = null;
if (!string.IsNullOrEmpty(accessToken))
{
var defaultRequetHeaders = HttpClient.DefaultRequestHeaders;
if (defaultRequetHeaders.Accept == null || !defaultRequetHeaders.Accept.Any(m => m.MediaType == "application/json"))
{
HttpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
}
defaultRequetHeaders.Authorization = new AuthenticationHeaderValue("bearer", accessToken);
HttpResponseMessage response = await HttpClient.DeleteAsync(webApiUrl);
if (response.IsSuccessStatusCode)
{
var json = await response.Content.ReadreplacedtringAsync();
result = JsonConvert.DeserializeObject(json) as JObject;
//Console.ForegroundColor = ConsoleColor.Gray;
}
else
{
//Console.ForegroundColor = ConsoleColor.Red;
//Console.WriteLine($"Failed to call the Web Api: {response.StatusCode}");
JObject content = JObject.Parse(await response.Content.ReadreplacedtringAsync());
//Console.WriteLine($"Content: {content}");
result = content;
}
//Console.ResetColor();
}
return result;
}
19
View Source File : ProtectedApiCallHelper.cs
License : GNU General Public License v3.0
Project Creator : 3xpl01tc0d3r
License : GNU General Public License v3.0
Project Creator : 3xpl01tc0d3r
public async Task<JObject> CallPostWebApiAndProcessResultASync(string webApiUrl, string accessToken, string data)
{
JObject result = null;
if (!string.IsNullOrEmpty(accessToken))
{
var defaultRequetHeaders = HttpClient.DefaultRequestHeaders;
if (defaultRequetHeaders.Accept == null || !defaultRequetHeaders.Accept.Any(m => m.MediaType == "application/json"))
{
HttpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
}
defaultRequetHeaders.Authorization = new AuthenticationHeaderValue("bearer", accessToken);
var body = new StringContent(data, Encoding.UTF8, "application/json");
HttpResponseMessage response = await HttpClient.PostAsync(webApiUrl, body);
if (response.IsSuccessStatusCode)
{
string json = await response.Content.ReadreplacedtringAsync();
result = JsonConvert.DeserializeObject(json) as JObject;
Console.ForegroundColor = ConsoleColor.Gray;
}
else
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine($"Failed to call the Web Api: {response.StatusCode}");
JObject content = JObject.Parse(await response.Content.ReadreplacedtringAsync());
Console.WriteLine($"Content: {content}");
result = content;
}
Console.ResetColor();
}
return result;
}
19
View Source File : ProtectedApiCallHelper.cs
License : GNU General Public License v3.0
Project Creator : 3xpl01tc0d3r
License : GNU General Public License v3.0
Project Creator : 3xpl01tc0d3r
public async Task<JObject> CallGetWebApiAndProcessResultASync(string webApiUrl, string accessToken)
{
JObject result = null;
if (!string.IsNullOrEmpty(accessToken))
{
var defaultRequetHeaders = HttpClient.DefaultRequestHeaders;
if (defaultRequetHeaders.Accept == null || !defaultRequetHeaders.Accept.Any(m => m.MediaType == "application/json"))
{
HttpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
}
defaultRequetHeaders.Authorization = new AuthenticationHeaderValue("bearer", accessToken);
HttpResponseMessage response = await HttpClient.GetAsync(webApiUrl);
if (response.IsSuccessStatusCode)
{
var json = await response.Content.ReadreplacedtringAsync();
result = JsonConvert.DeserializeObject(json) as JObject;
//Console.ForegroundColor = ConsoleColor.Gray;
}
else
{
//Console.ForegroundColor = ConsoleColor.Red;
//Console.WriteLine($"Failed to call the Web Api: {response.StatusCode}");
JObject content = JObject.Parse(await response.Content.ReadreplacedtringAsync());
//Console.WriteLine($"Content: {content}");
result = content;
}
//Console.ResetColor();
}
return result;
}
19
View Source File : ProtectedApiCallHelper.cs
License : GNU General Public License v3.0
Project Creator : 3xpl01tc0d3r
License : GNU General Public License v3.0
Project Creator : 3xpl01tc0d3r
public async Task<JObject> CallPostWebApiAndProcessResultASync(string webApiUrl, string accessToken, string data)
{
JObject result = null;
if (!string.IsNullOrEmpty(accessToken))
{
var defaultRequetHeaders = HttpClient.DefaultRequestHeaders;
if (defaultRequetHeaders.Accept == null || !defaultRequetHeaders.Accept.Any(m => m.MediaType == "application/json"))
{
HttpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
}
defaultRequetHeaders.Authorization = new AuthenticationHeaderValue("bearer", accessToken);
var body = new StringContent(data, Encoding.UTF8, "application/json");
HttpResponseMessage response = await HttpClient.PostAsync(webApiUrl, body);
if (response.IsSuccessStatusCode)
{
string json = await response.Content.ReadreplacedtringAsync();
result = JsonConvert.DeserializeObject(json) as JObject;
//Console.ForegroundColor = ConsoleColor.Gray;
}
else
{
//Console.ForegroundColor = ConsoleColor.Red;
//Console.WriteLine($"Failed to call the Web Api: {response.StatusCode}");
JObject content = JObject.Parse(await response.Content.ReadreplacedtringAsync());
//Console.WriteLine($"Content: {content}");
result = content;
}
//Console.ResetColor();
}
return result;
}
19
View Source File : ProtectedApiCallHelper.cs
License : GNU General Public License v3.0
Project Creator : 3xpl01tc0d3r
License : GNU General Public License v3.0
Project Creator : 3xpl01tc0d3r
public async Task<JObject> CallGetWebApiAndProcessResultASync(string webApiUrl, string accessToken)
{
JObject result = null;
if (!string.IsNullOrEmpty(accessToken))
{
var defaultRequetHeaders = HttpClient.DefaultRequestHeaders;
if (defaultRequetHeaders.Accept == null || !defaultRequetHeaders.Accept.Any(m => m.MediaType == "application/json"))
{
HttpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
}
defaultRequetHeaders.Authorization = new AuthenticationHeaderValue("bearer", accessToken);
HttpResponseMessage response = await HttpClient.GetAsync(webApiUrl);
if (response.IsSuccessStatusCode)
{
var json = await response.Content.ReadreplacedtringAsync();
result = JsonConvert.DeserializeObject(json) as JObject;
//Console.ForegroundColor = ConsoleColor.Gray;
}
else
{
//Console.ForegroundColor = ConsoleColor.Red;
//Console.WriteLine($"Failed to call the Web Api: {response.StatusCode}");
JObject content = JObject.Parse(await response.Content.ReadreplacedtringAsync());
//Console.WriteLine($"Content: {content}");
result = content;
}
//Console.ResetColor();
}
return result;
}
19
View Source File : Fuzzer.cs
License : Apache License 2.0
Project Creator : 42skillz
License : Apache License 2.0
Project Creator : 42skillz
private static bool IsATestMethod(MethodBase mb)
{
var attributeTypes = mb.CustomAttributes.Select(c => c.AttributeType);
var hasACustomAttributeOfTypeTest = attributeTypes.Any(y =>
(y.Name == "TestAttribute" || y.Name == "TestCaseAttribute" || y.Name == "Fact"));
if (hasACustomAttributeOfTypeTest)
{
return true;
}
return hasACustomAttributeOfTypeTest;
}
19
View Source File : FuzzerShouldBeDocumented.cs
License : Apache License 2.0
Project Creator : 42skillz
License : Apache License 2.0
Project Creator : 42skillz
[Test]
public void Simplest_usage_with_numbers()
{
// Instantiates the Fuzzer
var fuzzer = new Fuzzer();
var results = new List<int>();
for (var i = 0; i < 50; i++)
{
var integer = fuzzer.GeneratePositiveInteger(maxValue: 3);
results.Add(integer);
}
var findGreaterNumberThanMaxValue = results.Any(x => x > 3);
var findAtLeastOneNumberWithTheMaxValue = results.Any(x => x == 3);
Check.That(findGreaterNumberThanMaxValue).IsFalse();
Check.That(findAtLeastOneNumberWithTheMaxValue).IsTrue();
}
19
View Source File : NumberFuzzerShould.cs
License : Apache License 2.0
Project Creator : 42skillz
License : Apache License 2.0
Project Creator : 42skillz
[TestCase(500)]
public void GeneratePositiveInteger_with_an_inclusive_upper_bound(int attempts)
{
var fuzzer = new Fuzzer();
var maxValue = 3;
var generatedPositiveNumbers = new List<int>();
for (var i = 0; i < attempts; i++)
{
generatedPositiveNumbers.Add(fuzzer.GeneratePositiveInteger(maxValue));
}
Check.That(generatedPositiveNumbers.Any(n => n == 3)).IsTrue();
Check.That(generatedPositiveNumbers.Any(n => n > 3)).IsFalse();
}
19
View Source File : NumberFuzzerShould.cs
License : Apache License 2.0
Project Creator : 42skillz
License : Apache License 2.0
Project Creator : 42skillz
[TestCase(500)]
public void GenerateIntegers_with_an_inclusive_upper_bound(int attempts)
{
var fuzzer = new Fuzzer();
var maxValue = 3;
var generatedPositiveNumbers = new List<int>();
for (var i = 0; i < attempts; i++)
{
generatedPositiveNumbers.Add(fuzzer.GenerateInteger(-2, maxValue));
}
Check.That(generatedPositiveNumbers.Any(n => n == 3)).IsTrue();
Check.That(generatedPositiveNumbers.Any(n => n > 3)).IsFalse();
}
19
View Source File : SuggestionsMade.cs
License : Apache License 2.0
Project Creator : 42skillz
License : Apache License 2.0
Project Creator : 42skillz
public bool MatchExpectations()
{
return ForCategory.SelectMany(s => s.Value).Any(x => x.MatchExpectation());
}
19
View Source File : ReceivePacket.cs
License : MIT License
Project Creator : 499116344
License : MIT License
Project Creator : 499116344
internal void TlvExecutionProcessing(ICollection<Tlv> tlvs)
{
if (_tlvTypes == null)
{
var types = replacedembly.GetExecutingreplacedembly().GetTypes();
_tlvTypes = new Dictionary<int, Type>();
foreach (var type in types)
{
var attributes = type.GetCustomAttributes();
if (!attributes.Any(attr => attr is TlvTagAttribute))
{
continue;
}
var attribute = attributes.First(attr => attr is TlvTagAttribute) as TlvTagAttribute;
_tlvTypes.Add((int) attribute.Tag, type);
}
}
foreach (var tlv in tlvs)
{
if (_tlvTypes.ContainsKey(tlv.Tag))
{
var tlvClreplaced = replacedembly.GetExecutingreplacedembly().CreateInstance(_tlvTypes[tlv.Tag].FullName, true);
var methodinfo = _tlvTypes[tlv.Tag].GetMethod("Parser_Tlv");
methodinfo.Invoke(tlvClreplaced, new object[] { User, Reader });
}
}
}
19
View Source File : DispatchPacketToCommand.cs
License : MIT License
Project Creator : 499116344
License : MIT License
Project Creator : 499116344
public IPacketCommand dispatch_receive_packet(QQCommand command)
{
var types = replacedembly.GetExecutingreplacedembly().GetTypes();
foreach (var type in types)
{
var attributes = type.GetCustomAttributes();
if (!attributes.Any(attr => attr is ReceivePacketCommand))
{
continue;
}
var attribute = attributes.First(attr => attr is ReceivePacketCommand) as ReceivePacketCommand;
if (attribute.Command == command)
{
var receivePacket =
Activator.CreateInstance(type, _data, _service, _transponder, _user) as IPacketCommand;
return receivePacket;
}
}
return new DefaultReceiveCommand(_data, _service, _transponder, _user);
}
19
View Source File : Richtext.cs
License : MIT License
Project Creator : 499116344
License : MIT License
Project Creator : 499116344
public static Richtext Parse(BinaryReader reader)
{
var result = new Richtext();
// TODO: 解析富文本
try
{
var messageType = reader.ReadByte();
var dataLength = reader.BeReadUInt16();
var pos = reader.BaseStream.Position;
while (pos + dataLength < reader.BaseStream.Length)
{
reader.ReadByte();
switch (messageType)
{
case 0x01: // 纯文本消息、@
{
var messageStr = reader.BeReadString();
if (messageStr.StartsWith("@") && pos + dataLength - reader.BaseStream.Position == 16)
{
reader.ReadBytes(10);
result.Snippets.Add(new TextSnippet(messageStr, MessageType.At,
("Target", reader.BeReadLong32())));
}
else
{
result.Snippets.Add(messageStr);
}
break;
}
case 0x02: // Emoji(系统表情)
{
reader.BeReadUInt16(); // 这里的数字貌似总是1:系统表情只有208个。
result.Snippets.Add(new TextSnippet("", MessageType.Emoji, ("Type", reader.ReadByte())));
break;
}
case 0x03: // 图片
{
result.Snippets.Add(new TextSnippet(reader.BeReadString(), MessageType.Picture));
break;
}
case 0x0A: // 音频
{
result.Snippets.Add(new TextSnippet(reader.BeReadString(), MessageType.Audio));
break;
}
case 0x0E: // 未知
{
break;
}
case 0x12: // 群名片
{
break;
}
case 0x14: // XML
{
reader.ReadByte();
result.Snippets.Add(new TextSnippet(
GZipByteArray.DecompressString(reader.ReadBytes((int) (reader.BaseStream.Length - 1))),
MessageType.Xml));
break;
}
case 0x18: // 群文件
{
reader.ReadBytes(5);
var fileName = reader.BeReadString(); // 文件名称... 长度总是一个byte
reader.ReadByte();
reader.ReadBytes(reader.ReadByte()); // 文件大小
result.Snippets.Add(new TextSnippet(fileName, MessageType.OfflineFile));
break;
}
case 0x19: // 红包秘钥段
{
if (reader.ReadByte() != 0xC2)
{
break;
}
reader.ReadBytes(19);
reader.ReadBytes(reader.ReadByte()); // 恭喜发财
reader.ReadByte();
reader.ReadBytes(reader.ReadByte()); // 赶紧点击拆开吧
reader.ReadByte();
reader.ReadBytes(reader.ReadByte()); // QQ红包
reader.ReadBytes(5);
reader.ReadBytes(reader.ReadByte()); // [QQ红包]恭喜发财
reader.ReadBytes(22);
var redId = Encoding.UTF8.GetString(reader.ReadBytes(32)); //redid
reader.ReadBytes(12);
reader.ReadBytes(reader.BeReadUInt16());
reader.ReadBytes(0x10);
var key1 = Encoding.UTF8.GetString(reader.ReadBytes(reader.ReadByte())); //Key1
reader.BeReadUInt16();
var key2 = Encoding.UTF8.GetString(reader.ReadBytes(reader.ReadByte())); //Key2
result.Snippets.Add(new TextSnippet("", MessageType.RedBag, ("RedId", redId),
("Key1", key1), ("Key2", key2)));
break;
}
}
reader.ReadBytes((int) (pos + dataLength - reader.BaseStream.Position));
messageType = reader.ReadByte();
dataLength = reader.BeReadUInt16();
pos = reader.BaseStream.Position;
}
}
catch (Exception ex)
{
}
// 移除所有空白的片段
result.Snippets.RemoveAll(s => s.Type == MessageType.Normal && string.IsNullOrEmpty(s.Content));
// 若长度大于1,那么应该只含有普通文本、At、表情、图片。
// 虽然我看着别人好像视频也能通过转发什么的弄进来,但是反正我们现在不支持接收音视频,所以不管了
return result.Snippets.Count > 1 && result.Snippets.Any(s =>
s.Type != MessageType.Normal && s.Type != MessageType.At &&
s.Type != MessageType.Emoji && s.Type != MessageType.Picture)
? throw new NotSupportedException("富文本中包含多个非聊天代码")
: result;
}
19
View Source File : WebContentFolderHelper.cs
License : MIT License
Project Creator : 52ABP
License : MIT License
Project Creator : 52ABP
private static bool DirectoryContains(string directory, string fileName)
{
return Directory.GetFiles(directory).Any(filePath => string.Equals(Path.GetFileName(filePath), fileName));
}
19
View Source File : TypeExtensions.cs
License : MIT License
Project Creator : 52ABP
License : MIT License
Project Creator : 52ABP
public static bool AttributeExists<T>(this MemberInfo memberInfo, bool inherit = false) where T : Attribute
{
return memberInfo.GetCustomAttributes(typeof (T), inherit).Any(m => m as T != null);
}
19
View Source File : OnOffConstraint.cs
License : MIT License
Project Creator : 5argon
License : MIT License
Project Creator : 5argon
protected override ConstraintResult replacedert()
{
if (FindResult == false)
{
return new ConstraintResult(this, null, isSuccess: false);
}
if (lookingForOn)
{
var allOn = GetOnOffs().All(x => x.IsOn);
return new ConstraintResult(this, FoundBeacon, isSuccess: FindResult && allOn);
}
else
{
var anyOff = GetOnOffs().Any(x => x.IsOn == false);
return new ConstraintResult(this, FoundBeacon, isSuccess: FindResult && anyOff);
}
}
19
View Source File : CompilationProcessor.cs
License : MIT License
Project Creator : 71
License : MIT License
Project Creator : 71
public bool TryInitialize(CSharpCompilation compilation, CancellationToken cancellationToken)
{
if (IsInitialized && IsInitializationSuccessful)
return true;
List<CompilationEditor> editors = Editors;
var addDiagnostic = AddDiagnostic;
CSharpCompilation clone = compilation.Clone();
IsInitialized = true;
// Log all previously encountered exceptions
initializationExceptions.Capacity = initializationExceptions.Count;
var exceptions = initializationExceptions.MoveToImmutable();
for (int i = 0; i < exceptions.Length; i++)
{
var (exception, data) = exceptions[i];
var location = data.ApplicationSyntaxReference.ToLocation();
addDiagnostic(Diagnostic.Create(InitializationError, location, data.AttributeClreplaced, exception.Message.Filter(), exception.StackTrace.Filter()));
}
if (exceptions.Length > 0)
return false;
// Initialize all editors
int editorsCount = editors.Count;
for (int i = 0; i < editorsCount; i++)
{
CompilationEditor editor = editors[i];
try
{
// Register
if (!editor.TryRegister(this, addDiagnostic, clone, cancellationToken, out var children, out var exception))
{
addDiagnostic(Diagnostic.Create(EditorError, Location.None, editor.ToString(), exception.ToString()));
return false;
}
// Make sure no error was diagnosed by the editor
if (GetDiagnostics().Any(x => x.Severity == DiagnosticSeverity.Error))
{
return false;
}
// Optionally register some children
if (children == null || children.Length == 0)
continue;
editors.Capacity += children.Length;
for (int j = 0; j < children.Length; j++)
{
CompilationEditor child = children[j];
if (child == null)
{
addDiagnostic(Diagnostic.Create(
id: "MissingChild", category: Common.DiagnosticsCategory,
message: $"A child returned by the '{editor}' editor is null.",
severity: DiagnosticSeverity.Warning, defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true, warningLevel: 1, isSuppressed: false));
continue;
}
editors.Insert(i + j + 1, child);
editorsCount++;
}
// Since we insert them right after this one, the for loop will take care of initializing them easily
// => No recursion, baby
}
catch (Exception e)
{
while (e is TargetInvocationException tie)
e = tie.InnerException;
addDiagnostic(Diagnostic.Create(EditorError, Location.None, editor.ToString(), e.Message.Filter()));
return false;
}
}
// We got this far: the initialization is a success.
IsInitializationSuccessful = true;
return true;
}
19
View Source File : Form1.cs
License : MIT License
Project Creator : a1xd
License : MIT License
Project Creator : a1xd
static void MakeStartupShortcut(bool gui)
{
var startupFolder = Environment.GetFolderPath(Environment.SpecialFolder.Startup);
if (string.IsNullOrEmpty(startupFolder))
{
throw new Exception("Startup folder does not exist");
}
//Windows Script Host Shell Object
Type t = Type.GetTypeFromCLSID(new Guid("72C24DD5-D70A-438B-8A42-98424B88AFB8"));
dynamic shell = Activator.CreateInstance(t);
try
{
// Delete any other RA related startup shortcuts
var candidates = new[] { "rawaccel", "raw accel", "writer" };
foreach (string path in Directory.EnumerateFiles(startupFolder, "*.lnk")
.Where(f => candidates.Any(f.Substring(startupFolder.Length).ToLower().Contains)))
{
var link = shell.CreateShortcut(path);
try
{
string targetPath = link.TargetPath;
if (!(targetPath is null) &&
(targetPath.EndsWith("rawaccel.exe") ||
targetPath.EndsWith("writer.exe") &&
new FileInfo(targetPath).Directory.GetFiles("rawaccel.exe").Any()))
{
File.Delete(path);
}
}
finally
{
Marshal.FinalReleaseComObject(link);
}
}
var name = gui ? "rawaccel" : "writer";
var lnk = shell.CreateShortcut($@"{startupFolder}\{name}.lnk");
try
{
if (!gui) lnk.Arguments = Constants.DefaultSettingsFileName;
lnk.TargetPath = $@"{Application.StartupPath}\{name}.exe";
lnk.Save();
}
finally
{
Marshal.FinalReleaseComObject(lnk);
}
}
finally
{
Marshal.FinalReleaseComObject(shell);
}
}
See More Examples