content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
using UnityEngine; using UnityEditor; namespace com.spacepuppyeditor.AI.Sensors { internal static class SensorRenderUtil { #region Fields private static Material _arcMaterial; public static Material ArcMaterial { get { if (_arcMaterial == null) { var shader = Shader.Find("SPEditor/VisualSensorArcShader"); if (shader == null) { shader = MaterialHelper.DefaultMaterial.shader; } _arcMaterial = new Material(shader); _arcMaterial.hideFlags = HideFlags.HideAndDontSave; _arcMaterial.shader.hideFlags = HideFlags.HideAndDontSave; } return _arcMaterial; } } private static Material _lineMaterial; public static Material LineMaterial { get { if (_lineMaterial == null) { var shader = Shader.Find("SPEditor/VisualSensorLineShader"); if (shader == null) { shader = MaterialHelper.DefaultLineMaterial.shader; } _lineMaterial = new Material(shader); _lineMaterial.hideFlags = HideFlags.HideAndDontSave; _lineMaterial.shader.hideFlags = HideFlags.HideAndDontSave; } return _lineMaterial; } } private static Material _aspectMaterial; public static Material AspectMaterial { get { if (_aspectMaterial == null) { var shader = Shader.Find("SPEditor/VisualAspectShader"); if (shader == null) { shader = MaterialHelper.DefaultMaterial.shader; } _aspectMaterial = new Material(shader); _aspectMaterial.hideFlags = HideFlags.HideAndDontSave; _aspectMaterial.shader.hideFlags = HideFlags.HideAndDontSave; } return _aspectMaterial; } } #endregion } }
30.61039
81
0.484514
[ "Unlicense" ]
lordofduct/spacepuppy-unity-framework
SpacepuppyAIEditor/AI/Sensors/SensorRenderUtil.cs
2,359
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; namespace WebAppVeterinary { public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); RouteConfig.RegisterRoutes(RouteTable.Routes); } } }
22.526316
61
0.663551
[ "MIT" ]
fernandezjr/veterinary-clinic
SolutionVeterinary/WebAppVeterinary/Global.asax.cs
430
C#
using AgileAES.Models; using System; using System.Net; using System.Security; using System.Security.Cryptography; using System.Threading.Tasks; namespace AgileAES.Extensions { public static class EncryptedSecureStringExtensions { /// <summary> /// Decrypts an encrypted SecureString thats been ciphered in base64 /// </summary> /// <param name="encryptedSecureStr">the encrypted SecureString thats been ciphered in base64</param> /// <returns>a decrypted non-ciphered read-only SecureString</returns> public static async Task<SecureString> ToDecryptedSecureString(this EncryptedSecureString encryptedSecureStr) { var ciphered = new NetworkCredential("", encryptedSecureStr.String).Password; var encrypted = Convert.FromBase64String(ciphered); using (var aes = Aes.Create()) { aes.Key = encryptedSecureStr.Key; aes.IV = encryptedSecureStr.IV; return await Adapter.Decrypt(encrypted, aes.Key, aes.IV); } } } }
36.466667
117
0.659963
[ "MIT" ]
vitawebsitedesign/AgileAES
AgileAES/AgileAES/Extensions/EncryptedSecureStringExtensions.cs
1,096
C#
using Microsoft.AspNetCore.Mvc; using Newtonsoft.Json.Linq; using System; using MachinaTrader.Globals.Helpers; using MachinaTrader.Models; using MachinaTrader.Globals; using MachinaTrader.Globals.Models; using Microsoft.AspNetCore.Authorization; namespace MachinaTrader.Controllers { [Authorize, Route("api/config/")] public class ApiConfig : Controller { [HttpGet] [Route("mainConfig")] public ActionResult<MainConfig> GetMainConfig() { return Global.Configuration; } [HttpPost] [Route("mainConfig")] public void PostMainConfig([FromBody]JObject data) { try { Global.Configuration = MergeObjects.MergeCsDictionaryAndSave(Global.Configuration, Global.DataPath + "/MainConfig.json", data).ToObject<MainConfig>(); } catch (Exception ex) { Global.Logger.Error(@"Can not save config file: " + ex); } } [HttpGet] [Route("runtime")] public ActionResult GetRuntime() { return new JsonResult(Global.RuntimeSettings); } } }
26.863636
166
0.608291
[ "MIT" ]
elha/MachinaTrader
MachinaTrader/Controllers/ApiConfig.cs
1,182
C#
using NodaTime; namespace Test.RCS1201 { public class MyEntity { public long Col1 { get; set; } public MyEnum Col2 { get; set; } public YearMonth Col3 { get; set; } } }
15.923077
43
0.574879
[ "Unlicense" ]
pgrm/code-analyzers-tests
Test/RCS1201/MyEntity.cs
207
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("16114")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("16114")] [assembly: AssemblyCopyright("Copyright © 2018")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("7c7adfbc-0c3d-4a7f-b375-d27b9eb1dab3")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.243243
84
0.745283
[ "MIT" ]
CommName/MauMau
GameEngine/16114/Properties/AssemblyInfo.cs
1,381
C#
using MasterDevs.ChromeDevTools; using Newtonsoft.Json; using System.Collections.Generic; namespace MasterDevs.ChromeDevTools.Protocol.Chrome.Page { /// <summary> /// Information about the Frame on the page. /// </summary> [SupportedBy("Chrome")] public class Frame { /// <summary> /// Gets or sets Frame unique identifier. /// </summary> public string Id { get; set; } /// <summary> /// Gets or sets Parent frame identifier. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] public string ParentId { get; set; } /// <summary> /// Gets or sets Identifier of the loader associated with this frame. /// </summary> public string LoaderId { get; set; } /// <summary> /// Gets or sets Frame's name as specified in the tag. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] public string Name { get; set; } /// <summary> /// Gets or sets Frame document's URL. /// </summary> public string Url { get; set; } /// <summary> /// Gets or sets Frame document's security origin. /// </summary> public string SecurityOrigin { get; set; } /// <summary> /// Gets or sets Frame document's mimeType as determined by the browser. /// </summary> public string MimeType { get; set; } /// <summary> /// Gets or sets If the frame failed to load, this contains the URL that could not be loaded. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] public string UnreachableUrl { get; set; } } }
30.48
95
0.673885
[ "MIT" ]
Digitalbil/ChromeDevTools
source/ChromeDevTools/Protocol/Chrome/Page/Frame.cs
1,524
C#
using System; using System.Collections.Generic; namespace Ela.Compilation { internal sealed class ConstructorData { public string TypeName { get; internal set; } public int TypeModuleId { get; internal set; } public int Code { get; internal set; } internal int TypeCode { get; set; } public bool Private { get; internal set; } public string Name { get; internal set; } internal List<String> Parameters { get; set; } //These are populated only by linker internal int ModuleId; internal int ConsAddress; } }
23.444444
55
0.605055
[ "MIT" ]
vorov2/ela
Ela/Ela/Compilation/ConstructorData.cs
635
C#
// Copyright (c) Leonardo Brugnara // Full copyright and license information in LICENSE file using Zenit.Ast; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; namespace Zenit.Syntax { public class Parser : IParser { #region Private fields /// <summary> /// Stream of tokens /// </summary> private List<Token> tokens; /// <summary> /// Pointer to keep track of the current position /// </summary> private int pointer; private List<ParserException> parsingErrors; #endregion #region Constructor public Node Parse(List<Token> tokens) { this.pointer = 0; this.tokens = tokens; this.parsingErrors = new List<ParserException>(); return this.Program(); } #endregion public ReadOnlyCollection<ParserException> ParsingErrors => new ReadOnlyCollection<ParserException>(this.parsingErrors); #region Parser state /// <summary> /// Now it just contains a copy of the pointer. It is overkill but /// in the future if the parser starts to keep track of states, this /// class will be helpful to keep track of them /// </summary> protected class ParserCheckpoint { public int Pointer { get; } public ParserCheckpoint(int pointer) { this.Pointer = pointer; } } /// <summary> /// Get a copy o the current parser's state /// </summary> /// <returns></returns> protected ParserCheckpoint SaveCheckpoint() { return new ParserCheckpoint(this.pointer); } /// <summary> /// Restore a previous parser's state /// </summary> /// <param name="checkpoint"></param> protected void RestoreCheckpoint(ParserCheckpoint checkpoint) { this.pointer = checkpoint.Pointer; } #endregion #region Parsing helpers private bool HasInput() { return this.pointer < this.tokens.Count; } /// <summary> /// Return true if the following tokens starting from the current position match in type with the provided array of types /// </summary> /// <param name="types">Target stream of types to match</param> /// <returns></returns> private bool Match(params TokenType[] types) { return this.MatchFrom(0, types); } /// <summary> /// Return true if the following tokens starting from the current position and applying an offset, match in type with the provided array of types /// </summary> /// <param name="offset">Offset to reach the target token</param> /// <param name="types">Types to check against the target token</param> /// <returns></returns> private bool MatchFrom(int offset, params TokenType[] types) { if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset), "Offset cannot be negative"); var l = types.Length; if (l + this.pointer + offset > this.tokens.Count || this.pointer + offset < 0) return false; for (int i = 0; i < types.Length; i++) { if (types[i] == TokenType.Unknown) continue; if (this.tokens[this.pointer + i + offset].Type != types[i]) return false; } return true; } /// <summary> /// Return true if the following token starting from the current position, has its type in the types array /// </summary> /// <param name="types">List of expected types to match with the next token</param> /// <returns></returns> private bool MatchAny(params TokenType[] types) { var t = this.Peek(); return t != null && types.Contains(t.Type); } /// <summary> /// Return true if the following token starting from the current position and applying an offset, has its type in the types array /// </summary> /// <param name="types">List of expected types to match with the next token</param> /// <returns></returns> private bool MatchAnyFrom(int offset, params TokenType[] types) { if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset), "Offset cannot be negative"); var t = this.PeekFrom(offset); return t != null && types.Contains(t.Type); } /// <summary> /// Return the number of tokens starting from the current position and applying an offset, that repeatedly match the /// types in order /// </summary> /// <param name="types">List of expected types to match with the next token</param> /// <returns></returns> private int CountRepeatedMatchesFrom(int offset, params TokenType[] types) { if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset), "Offset cannot be negative"); int q = 0; var l = types.Length; if (l + this.pointer + offset > this.tokens.Count) return 0; int i = 0; bool valid = true; while (valid && i + offset + this.pointer < this.tokens.Count) { for (int j = 0; j < types.Length; j++, i++) { if (types[j] == TokenType.Unknown) { q++; continue; } if (this.pointer + i + offset >= this.tokens.Count || this.tokens[this.pointer + i + offset].Type != types[j]) { valid = false; break; } q++; } } return q >= types.Length ? q : 0; } /// <summary> /// Return the next token if available /// </summary> /// <returns></returns> private Token Peek() { return this.pointer < this.tokens.Count ? this.tokens[this.pointer] : null; } /// <summary> /// Return the next token based on the current position with a positive offset /// </summary> /// <param name="offset"></param> /// <returns></returns> private Token PeekFrom(int offset) { //if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset), "Offset cannot be negative"); int i = this.pointer + offset; return i >= 0 && i < this.tokens.Count ? this.tokens[i] : null; } /// <summary> /// Consume the next token /// </summary> /// <returns></returns> private Token Consume() { if (!this.HasInput()) return null; return this.tokens[this.pointer++]; } private string GetSourceContext() { // TODO: Retrieve context from Lexer return ""; } private string GetCurrentLineAndCol() { Token t = this.tokens.ElementAtOrDefault(this.pointer - 1); return t != null ? $"[Line {t.Line}:{t.Col}]" : "[Line 0:0]"; } /// <summary> /// Consume the next token making sure its type matches the provided type. If the next token does not match with the type /// throw an exception. If message is not null use it as the exception's message /// </summary> /// <param name="type">Expected type of the next token</param> /// <param name="message">Error message if the token's type does not match the provided type</param> /// <returns></returns> private Token Consume(TokenType type, string message = null) { if (!this.HasInput()) { // ; is optional at the end of the input if (type == TokenType.Semicolon) { var lt = this.tokens.LastOrDefault(); return new Token() { Line = lt?.Line ?? 0, Col = lt?.Col+1 ?? 0, Type = TokenType.Semicolon, Value = ";" }; } throw new ParserException(message ?? $"{this.GetCurrentLineAndCol()} Expects {type} but received the end of the input: {this.GetSourceContext()}"); } if (!this.Match(type)) { throw new ParserException(message ?? $"{this.GetCurrentLineAndCol()} Expects {type} but received {this.Peek().Type}: {this.GetSourceContext()}"); } return this.tokens[this.pointer++]; } /// <summary> /// Move the pointer back one position /// </summary> /// <param name="t"></param> private void Restore(Token t) { this.pointer--; } #endregion #region Grammar // Rule: // program -> declaration* private DeclarationNode Program() { List<Node> declarations = new List<Node>(); while (this.HasInput()) { try { if (this.Match(TokenType.Semicolon)) { this.Consume(); continue; } declarations.Add(this.Declaration()); } catch (ParserException pe) { this.parsingErrors.Add(pe); while (this.HasInput() && !this.Match(TokenType.Semicolon)) this.Consume(); } } return new DeclarationNode(declarations); } // Rule: // declaration -> func_declaration // | variable_declaration // | constant_declaration // | statement // private Node Declaration() { if (this.IsVarDeclaration()) { return this.VarDeclaration(); } else if (this.Match(TokenType.Constant)) { return this.ConstDeclaration(); } else if (this.Match(TokenType.Function)) { return this.FuncDeclaration(); } else if (this.Match(TokenType.Class)) { return this.ClassDeclaration(); } return this.Statement(); } // Rule: // variable_declaration -> 'mut'? ( implicit_var_declaration | typed_var_declaration ) ';' private VariableNode VarDeclaration() { VariableNode variable = null; if (this.Match(TokenType.Variable) || this.Match(TokenType.Mutable, TokenType.Variable)) { variable = this.ImplicitVarDeclaration(); } else { variable = this.TypedVarDeclaration(); } this.Consume(TokenType.Semicolon); return variable; } // Rule: // implicit_var_declaration -> VAR ( IDENTIFIER '=' expression | var_destructuring )';' private VariableNode ImplicitVarDeclaration() { // Get the symbol information Token mutability = this.Match(TokenType.Mutable) ? this.Consume() : null; Token type = this.Consume(TokenType.Variable); SymbolInformation variableType = new SymbolInformation(type, mutability, null); // If there is a left parent present, it is a destructuring declaration if (this.IsDestructuring()) return this.VarDestructuring(variableType); // If not it is a common var declaration Token identifier = this.Consume(TokenType.Identifier); this.Consume(TokenType.Assignment, "Implicitly typed variables must be initialized"); Node expression = this.Expression(); return new VariableDefinitionNode(variableType, new List<SymbolDefinition>() { new SymbolDefinition(identifier, expression) }); } // Rule: // typed_var_declaration -> IDENTIFIER ( '[' ']' )* ( typed_var_definition | var_destructuring ) ';' private VariableNode TypedVarDeclaration() { // Get the symbol information Token mutability = this.Match(TokenType.Mutable) ? this.Consume() : null; Token type = this.Consume(TokenType.Identifier); SymbolInformation variableType = new SymbolInformation(type, mutability, null); // If it contains a left bracket, it is an array variable if (this.Match(TokenType.LeftBracket)) { List<Token> dimensions = new List<Token>(); while (this.Match(TokenType.LeftBracket)) { dimensions.Add(this.Consume(TokenType.LeftBracket)); dimensions.Add(this.Consume(TokenType.RightBracket)); } variableType = new SymbolInformation(type, mutability, null, dimensions); } var state = this.SaveCheckpoint(); try { // If there is a left parent present, it is a destructuring declaration if (this.IsDestructuring()) return this.VarDestructuring(variableType); } catch (Exception) { this.RestoreCheckpoint(state); } // If not, it is a simple typed var definition return new VariableDefinitionNode(variableType, this.TypedVarDefinition()); } // Rule: // typed_var_definition -> IDENTIFIER ( '=' expression )? ( ',' typed_var_definition )* private List<SymbolDefinition> TypedVarDefinition() { var vars = new List<SymbolDefinition>(); do { // There could be multiple declarations and definitions, so consume the // identifier and then check if it is a definition or just a declaration var id = this.Consume(TokenType.Identifier); if (this.Match(TokenType.Assignment) && this.Consume(TokenType.Assignment) != null) vars.Add(new SymbolDefinition(id, this.Expression())); else vars.Add(new SymbolDefinition(id, null)); } while (this.Match(TokenType.Comma) && this.Consume(TokenType.Comma) != null); return vars; } // Rule: // var_destructuring -> '(' ( ',' | IDENTIFIER )+ ')' '=' expression private VariableDestructuringNode VarDestructuring(SymbolInformation varType) { List<Token> tokens = new List<Token>(); // Consume the left hand side: (x,y,z) or (,y,) or (x,,) etc. bool hasParenthesis = false; if (this.Match(TokenType.LeftParen) && this.Consume(TokenType.LeftParen) != null) hasParenthesis = true; do { if (this.Match(TokenType.Comma)) { tokens.Add(null); } else if (this.Match(TokenType.Identifier)) { tokens.Add(this.Consume(TokenType.Identifier)); } } while (this.Match(TokenType.Comma) && this.Consume(TokenType.Comma) != null); if (hasParenthesis) this.Consume(TokenType.RightParen); // Destructuring just work with assignment, it is a must this.Consume(TokenType.Assignment); // Get the expression that will need to return a Tuple value, let the runtime check that return new VariableDestructuringNode(varType, tokens, this.Expression()); } // Rule: // constant_declaration -> 'const' IDENTIFIER? IDENTIFIER '=' expression ( ',' IDENTIFIER '=' expression )* ) ';' private ConstantNode ConstDeclaration() { // Consume the keyword this.Consume(TokenType.Constant); // Get the constant type if present Token type = this.Match(TokenType.Identifier, TokenType.Identifier) ? this.Consume(TokenType.Identifier) : null; // Consume multiple constants declarations and definitions List<SymbolDefinition> constdefs = new List<SymbolDefinition>(); do { Token identifier = this.Consume(TokenType.Identifier); this.Consume(TokenType.Assignment, "A constant value needs to be defined when declared."); Node expression = this.Expression(); constdefs.Add(new SymbolDefinition(identifier, expression)); } while (this.Match(TokenType.Comma) && this.Consume(TokenType.Comma) != null); this.Consume(TokenType.Semicolon); return new ConstantNode(type, constdefs); } // Rule: // func_declaration -> 'fn' IDENTIFIER '(' func_params? ')' ( '{' declaration* '}' | '=>' expression ) private FunctionNode FuncDeclaration() { this.Consume(TokenType.Function); Token name = this.Consume(TokenType.Identifier); List<ParameterNode> parameters = null; this.Consume(TokenType.LeftParen); parameters = this.FuncParameters(); this.Consume(TokenType.RightParen); if (this.Peek().Type == TokenType.RightArrow) { // RightArrow followed by brace doesn't make sense here, expression is the only accepted node this.Consume(TokenType.RightArrow); var f = new FunctionNode(name, parameters ?? new List<ParameterNode>(), new List<Node>() { this.Expression() }, false, true); if (this.Match(TokenType.Semicolon)) this.Consume(TokenType.Semicolon); return f; } List<Node> decls = new List<Node>(); this.Consume(TokenType.LeftBrace); while (!this.Match(TokenType.RightBrace)) { decls.Add(this.Declaration()); } this.Consume(TokenType.RightBrace); return new FunctionNode(name, parameters, decls, false, false); } // Rule: // func_params -> func_param_declaration ( ',' func_param_declaration )* private List<ParameterNode> FuncParameters() { var parameters = new List<ParameterNode>(); while (this.MatchAny(TokenType.Mutable, TokenType.Identifier)) { parameters.Add(this.FuncParameter()); if (this.Match(TokenType.Comma)) this.Consume(); } return parameters; } // Rule: // func_param_declaration -> 'mut'? IDENTIFIER? IDENTIFIER //private private ParameterNode FuncParameter() { Token mutability = this.Match(TokenType.Mutable) ? this.Consume() : null; // The type is present if we find IDENTIFIER IDENTIFIER Token type = this.PeekFrom(1).Type != TokenType.Identifier ? null : this.Consume(); Token name = this.Consume(TokenType.Identifier); return new ParameterNode(name, new SymbolInformation(type, mutability, null)); } // Rule: // class_declaration -> 'class' IDENTIFIER '{' class_body? '}' // // class_body -> class_property // | class_constant // | class_method // // access_modifier -> ( 'public' | 'protected' | 'private' ) private ClassNode ClassDeclaration() { var classToken = this.Consume(TokenType.Class); var className = this.Consume(TokenType.Identifier); this.Consume(TokenType.LeftBrace); var properties = new List<ClassPropertyNode>(); var constants = new List<ClassConstantNode>(); var methods = new List<ClassMethodNode>(); while (!this.Match(TokenType.RightBrace)) { if (this.IsClassPropertyDeclaration()) { properties.Add(this.ClassProperty()); } else if (this.IsClassConstantDeclaration()) { constants.Add(this.ClassConstant()); } else if (this.IsClassMethodDeclaration()) { methods.Add(this.ClassMethod()); } else throw new ParserException($"Unexpected '{this.Peek().Value}' in class declaration"); } this.Consume(TokenType.RightBrace); return new ClassNode(className, properties, constants, methods); } // Rule: (TODO: getter and setter for class_property, because of that the class_field indirection) // class_property -> class_field // // class_field -> access_modifier? 'mut' IDENTIFIER ( '[' ']' )* IDENTIFIER ( '=' expression )? ';' private ClassPropertyNode ClassProperty() { // Get symbol information Token accessModifier = this.Match(TokenType.AccessModifier) ? this.Consume() : null; Token mutability = this.Match(TokenType.Mutable) ? this.Consume() : null; Token type = this.Consume(TokenType.Identifier); SymbolInformation variableType = new SymbolInformation(type, mutability, accessModifier); // If it contains a left bracket, it is an array variable if (this.Match(TokenType.LeftBracket)) { List<Token> dimensions = new List<Token>(); while (this.Match(TokenType.LeftBracket)) { dimensions.Add(this.Consume(TokenType.LeftBracket)); dimensions.Add(this.Consume(TokenType.RightBracket)); } variableType = new SymbolInformation(type, mutability, accessModifier, dimensions); } var name = this.Consume(TokenType.Identifier); Node definition = null; if (this.Match(TokenType.Assignment) && this.Consume(TokenType.Assignment) != null) definition = this.Expression(); this.Consume(TokenType.Semicolon); // If not, it is a simple typed var definition return new ClassPropertyNode(name, variableType, definition); } // Rule: // class_constant -> access_modifier? 'const' IDENTIFIER IDENTIFIER '=' expression ';' private ClassConstantNode ClassConstant() { // Check access modifier Token accessModifier = this.Match(TokenType.AccessModifier) ? this.Consume() : null; // Consume the keyword this.Consume(TokenType.Constant); // Get the constant type if present Token type = this.Consume(TokenType.Identifier); var modifiers = new SymbolInformation(type, null, accessModifier); Token identifier = this.Consume(TokenType.Identifier); this.Consume(TokenType.Assignment, "A constant value needs to be defined when declared."); Node expression = this.Expression(); this.Consume(TokenType.Semicolon); return new ClassConstantNode(identifier, modifiers, expression); } // Rule: // class_method -> access_modifier? func_declaration private ClassMethodNode ClassMethod() { // Check access modifier Token accessModifier = this.Match(TokenType.AccessModifier) ? this.Consume() : null; Token type = this.Consume(TokenType.Function); var modifiers = new SymbolInformation(type, null, accessModifier); Token name = this.Consume(TokenType.Identifier); this.Consume(TokenType.LeftParen); List<ParameterNode> parameters = this.FuncParameters(); this.Consume(TokenType.RightParen); if (this.Peek().Type == TokenType.RightArrow) { // RightArrow followed by brace doesn't make sense here, expression is the only accepted node this.Consume(TokenType.RightArrow); var f = new ClassMethodNode(name, modifiers, parameters, new List<Node>() { this.Expression() }, true); if (this.Match(TokenType.Semicolon)) this.Consume(TokenType.Semicolon); return f; } List<Node> decls = new List<Node>(); this.Consume(TokenType.LeftBrace); while (!this.Match(TokenType.RightBrace)) { decls.Add(this.Declaration()); } this.Consume(TokenType.RightBrace); return new ClassMethodNode(name, modifiers, parameters, decls, false); } // Rule: // statement -> expression_statement // | if_statement // | while_statement // | for_statement // | break_statement // | continue_statement // | return_statement // | block private Node Statement() { if (this.Match(TokenType.If)) return this.IfStatement(); if (this.Match(TokenType.LeftBrace)) return this.Block(); if (this.Match(TokenType.While)) return this.WhileStatement(); if (this.Match(TokenType.For)) return this.ForStatement(); if (this.Match(TokenType.Break)) return this.BreakStatement(); if (this.Match(TokenType.Continue)) return this.ContinueStatement(); if (this.Match(TokenType.Return)) return this.ReturnStatement(); return this.ExpressionStatement(); } // Rule: // return_statement -> 'return' ( expression )? ';' private ReturnNode ReturnStatement() { Token kw = this.Consume(TokenType.Return); Node expr = null; if (!this.Match(TokenType.Semicolon)) expr = this.Expression(); this.Consume(TokenType.Semicolon); return new ReturnNode(kw, expr); } // Rule: // continue_statement -> "continue" ";" private ContinueNode ContinueStatement() { var cont = new ContinueNode(this.Consume(TokenType.Continue)); this.Consume(TokenType.Semicolon); return cont; } // Rule: // break_statement -> "break" INTEGER? ";" private BreakNode BreakStatement() { Node nbreaks = null; Token kw = this.Consume(TokenType.Break); if (this.Match(TokenType.Integer)) nbreaks = new PrimitiveNode(this.Consume(TokenType.Integer)); this.Consume(TokenType.Semicolon); return new BreakNode(kw, nbreaks); } // Rule: // parenthesized_expr -> "(" expression ")" ( statement | ";" ) private (Node, Node) ParenthesizedStatement() { Node expression = this.ParenthesizedExpression(); Node stmt = this.Match(TokenType.Semicolon) ? new NoOpNode(this.Consume(TokenType.Semicolon)) : this.Statement(); return (expression, stmt); } private Node ParenthesizedExpression() { this.Consume(TokenType.LeftParen); Node expression = this.Expression(); this.Consume(TokenType.RightParen); return expression; } // Rule: // braced_expr -> expression block private (Node, Node) BracedStatement() { Node expression = this.Expression(); Node block = this.Block(); return (expression, block); } // Rule: // while_statement -> "while" ( parenthesized_expr | braced_expr ) private Node WhileStatement() { Token kw = this.Consume(TokenType.While); Node condition = null; Node body = null; (condition, body) = this.Match(TokenType.LeftParen) ? this.ParenthesizedStatement() : this.BracedStatement(); return new WhileNode(kw, condition, body); } #region for_statement // Rule: // for_statement -> "for" "(" for_initializer? ";" expression? ";" for_iterator? ")" statement // | "for" for_initializer? ";" expression? ";" for_iterator? block private ForNode ForStatement() { if (this.Match(TokenType.For, TokenType.LeftParen)) return this.ParenthesizedForStatemet(); Token kw = this.Consume(TokenType.For); Node forInitializer = null; Node expression = null; Node forIterator = null; Node body = null; // Initializer if (this.Match(TokenType.Semicolon)) { forInitializer = new NoOpNode(this.Consume()); } else { forInitializer = this.ForInitializer(); this.Consume(TokenType.Semicolon); } // Expression if (this.Match(TokenType.Semicolon)) { expression = new NoOpNode(this.Consume()); } else { expression = this.Expression(); this.Consume(TokenType.Semicolon); } // Iterator if (this.Match(TokenType.LeftBrace)) { forIterator = new NoOpNode(this.Peek()); // Get a reference of the line/col } else { forIterator = this.ForIterator(); } // Body body = this.Block(); return new ForNode(kw, forInitializer, expression, forIterator, body); } // Rule: (continuation) // for_statement -> "for" "(" for_initializer? ";" expression? ";" for_iterator? ")" statement private ForNode ParenthesizedForStatemet() { Token kw = this.Consume(TokenType.For); this.Consume(TokenType.LeftParen); Node forInitializer = null; Node expression = null; Node forIterator = null; Node body = null; // Initializer if (this.Match(TokenType.Semicolon)) { forInitializer = new NoOpNode(this.Consume()); } else { forInitializer = this.ForInitializer(); this.Consume(TokenType.Semicolon); } // Expression if (this.Match(TokenType.Semicolon)) { expression = new NoOpNode(this.Consume()); } else { expression = this.Expression(); this.Consume(TokenType.Semicolon); } // Iterator if (this.Match(TokenType.RightParen)) { forIterator = new NoOpNode(this.Consume()); } else { forIterator = this.ForIterator(); this.Consume(TokenType.RightParen); } // Body body = this.Match(TokenType.Semicolon) ? new NoOpNode(this.Consume(TokenType.Semicolon)) : this.Statement(); return new ForNode(kw, forInitializer, expression, forIterator, body); } // Rule: // for_initializer -> for_declaration // | expression_list private Node ForInitializer() { if (this.IsVarDeclaration()) { return this.ForDeclaration(); } return this.ExpressionList(); } // Rule: // for_declaration -> ( implicit_var_declaration | typed_var_declaration ) private DeclarationNode ForDeclaration() { Node variable = null; if (this.Match(TokenType.Variable)) { variable = this.ImplicitVarDeclaration(); } else { variable = this.TypedVarDeclaration(); } return new DeclarationNode(new List<Node>() { variable }); } // Rule: // for_iterator -> expression ( "," expression )* private DeclarationNode ForIterator() { List<Node> exprs = new List<Node> { this.Expression() }; while (this.Match(TokenType.Comma)) { this.Consume(); exprs.Add(this.Expression()); } // TODO: Check if DeclarationNode is correct return new DeclarationNode(exprs); } #endregion // Rule: // if_statement -> "if" (parenthesized_expr | braced_expr ) ( "else" (statement | ";" ) )? // parenthesized_expr -> "(" expression ")" ( statement | ";" ) // braced_expr -> expression block private IfNode IfStatement() { Token kw = this.Consume(TokenType.If); Node condition = null; Node thenbranch = null; Node elsebranch = null; (condition, thenbranch) = this.Match(TokenType.LeftParen) ? this.ParenthesizedStatement() : this.BracedStatement(); // Parse the else branch if present if (this.Match(TokenType.Else)) { this.Consume(TokenType.Else); elsebranch = this.Match(TokenType.Semicolon) ? new NoOpNode(this.Consume(TokenType.Semicolon)) : this.Statement(); } return new IfNode(kw, condition, thenbranch, elsebranch); } // Rule: // block -> "{" declaration* "}" private BlockNode Block() { List<Node> statements = new List<Node>(); this.Consume(TokenType.LeftBrace); while (!this.Match(TokenType.RightBrace)) { statements.Add(this.Declaration()); } this.Consume(TokenType.RightBrace); return new BlockNode(statements); } // Rule: // expression_statement -> expression ";" private Node ExpressionStatement() { Node expr = this.Expression(); this.Consume(TokenType.Semicolon); return expr; } // Rule: // expression_list -> expression ( ',' expression )* private ExpressionListNode ExpressionList() { List<Node> exprs = new List<Node> { this.Expression() }; while (this.Match(TokenType.Comma)) { this.Consume(); exprs.Add(this.Expression()); } return new ExpressionListNode(exprs); } // Rule: // expression -> expression_assignment private Node Expression() { return this.ExpressionAssignment(); } // Rule: // object_expression -> '{' object_property ( ',' object_property )* ','? '}' private ObjectNode ObjectExpression() { var properties = new List<ObjectPropertyNode>(); if (this.Match(TokenType.At)) this.Consume(); this.Consume(TokenType.LeftBrace); while (this.Match(TokenType.Identifier) || this.Match(TokenType.Mutable, TokenType.Identifier)) { // Create a dummy token for the var token var curTok = this.Peek(); var varToken = new Token { Col = curTok.Col-1, Line = curTok.Line, Type = TokenType.Variable, Value = "var" }; var info = new SymbolInformation(varToken, this.Match(TokenType.Mutable) ? this.Consume(TokenType.Mutable) : null, null); var name = this.Consume(TokenType.Identifier); this.Consume(TokenType.Colon); var value = this.Expression(); var property = new ObjectPropertyNode { Name = name, Information = info, Value = value }; properties.Add(property); // Consume trailing comma if (this.Match(TokenType.Comma)) this.Consume(TokenType.Comma); } this.Consume(TokenType.RightBrace); return new ObjectNode(properties); } // Rule: // lambda_expression -> lambda_params '=>' ( block | expression ) private FunctionNode LambdaExpression() { List<ParameterNode> lambdaParams = this.LambdaParams(); var arrow = this.Consume(TokenType.RightArrow); var isBlock = this.Match(TokenType.LeftBrace); Node expr = isBlock ? this.Block() : this.Expression(); return new FunctionNode(arrow, lambdaParams, new List<Node>() { expr }, true, !isBlock); } // Rule: // lambda_params -> '(' func_params ')' | func_params private List<ParameterNode> LambdaParams() { var parameters = new List<ParameterNode>(); // Lambda params could be wrapped between parenthesis bool parenthesis = false; if (Match(TokenType.LeftParen)) { parenthesis = true; this.Consume(); } // Consume the identifiers separated by commas while (this.MatchAny(TokenType.Mutable, TokenType.Identifier)) { parameters.Add(this.FuncParameter()); if (this.Match(TokenType.Comma)) this.Consume(); } if (parenthesis) this.Consume(TokenType.RightParen); return parameters; } // Rule: // destructuring -> '(' IDENTIFIER ( '.' IDENTIFIER )* ( ',' destructuring )* ')' private TupleNode Destructuring() { List<TupleMember> exprs = new List<TupleMember>(); bool hasParenthesis = false; if (this.Match(TokenType.LeftParen) && this.Consume(TokenType.LeftParen) != null) hasParenthesis = true; do { Node accessor = null; // Try to find member accessors or callable members // member.property.property2 if (this.Match(TokenType.Identifier)) { do { accessor = new AccessorNode(this.Consume(TokenType.Identifier), accessor); } while (this.Match(TokenType.Dot) && this.Consume(TokenType.Dot) != null); } if (accessor == null) accessor = new NoOpNode(null); exprs.Add(new TupleMember(accessor)); } while (this.Match(TokenType.Comma) && this.Consume(TokenType.Comma) != null); if (hasParenthesis) this.Consume(TokenType.RightParen); return new TupleNode(exprs); } // Rule: // tuple_expression -> '(' tuple_member ',' ( tuple_members )? ')' // tuple_members -> tuple_member ( ',' tuple_member )* // tuple_member -> ( member_name ':' )? expression private TupleNode TupleExpression() { List<TupleMember> args = new List<TupleMember>(); bool isValidTuple = false; this.Consume(TokenType.LeftParen); while (!this.Match(TokenType.RightParen)) { string name = null; if (this.Match(TokenType.Identifier, TokenType.Colon)) { name = this.Consume(TokenType.Identifier).Value; this.Consume(TokenType.Colon); } var expression = this.Expression(); args.Add(new TupleMember(name, expression)); while (this.Match(TokenType.Comma)) { isValidTuple = true; this.Consume(); } } this.Consume(TokenType.RightParen); return isValidTuple ? new TupleNode(args) : null; } // Rule: // expression_assignment -> lambda_expression // | destructuring ( '=' | '+=' | '-=' | '/=' | '*=' ) expression_assignment // | conditional_expression ( ( '=' | '+=' | '-=' | '/=' | '*=' ) expression_assignment )? private Node ExpressionAssignment() { // Try to parse a lambda expression if (this.IsLambdaExpression()) return this.LambdaExpression(); ParserCheckpoint checkpoint = this.SaveCheckpoint(); if (this.IsDestructuring()) { // First try if it is a left-hand side expression try { TupleNode leftval = this.Destructuring(); // If we now match an assignment of any type, create an assignment node if (this.MatchAny(TokenType.Assignment, TokenType.IncrementAndAssign, TokenType.DecrementAndAssign, TokenType.DivideAndAssign, TokenType.MultAndAssign)) { Token assignmentop = this.Consume(); Node expression = this.TupleExpression(); return new DestructuringAssignmentNode(leftval, assignmentop, expression as TupleNode); } } catch { } // If we reach this point, we restore the checkpoint this.RestoreCheckpoint(checkpoint); } var lvalue = this.ConditionalExpression(); if (this.MatchAny(TokenType.Assignment, TokenType.IncrementAndAssign, TokenType.DecrementAndAssign, TokenType.DivideAndAssign, TokenType.MultAndAssign)) { Token assignmentop = this.Consume(); Node expression = this.Expression(); if (lvalue is CallableNode) throw new ParserException($"{this.GetCurrentLineAndCol()} Left-hand side of an assignment must be a variable."); return new VariableAssignmentNode(lvalue as AccessorNode, assignmentop, expression); } return lvalue; } // Rule: // conditional_expression -> null_coalescing_expression ( '?' expression ':' expression )? private Node ConditionalExpression() { Node nullCoalescingExpr = this.NullCoalescingExpression(); if (this.Match(TokenType.Question)) { Token q = this.Consume(); Node trueExpr = this.Expression(); this.Consume(TokenType.Colon); Node falseExpr = this.Expression(); return new IfNode(q, nullCoalescingExpr, trueExpr, falseExpr); } return nullCoalescingExpr; } // Rule: // null_coalescing_expression -> or_expression ( '??' null_coalescing_expression )? private Node NullCoalescingExpression() { Node orExpr = this.OrExpression(); if (this.Match(TokenType.QuestionQuestion)) { Token q = this.Consume(); Node rightExpr = this.NullCoalescingExpression(); return new NullCoalescingNode(q, orExpr, rightExpr); } return orExpr; } // Rule: // or_expression -> and_expression ( "||" and_expression )* private Node OrExpression() { Node orexpr = this.AndExpression(); while (this.Match(TokenType.Or)) { Token or = this.Consume(); Node right = this.AndExpression(); orexpr = new BinaryNode(or, orexpr, right); } return orexpr; } // Rule: // and_expression -> equality_expression ( "&&" equality_expression )* private Node AndExpression() { Node andexpr = this.EqualityExpression(); while (this.Match(TokenType.And)) { Token and = this.Consume(); Node right = this.EqualityExpression(); andexpr = new BinaryNode(and, andexpr, right); } return andexpr; } // Rule: // equality_expression -> comparison_expression ( ( "!=" | "==" ) comparison_expression )* private Node EqualityExpression() { Node compexpr = this.ComparisonExpression(); while (this.Match(TokenType.Equal) || this.Match(TokenType.NotEqual)) { Token equality = this.Consume(); Node right = this.ComparisonExpression(); compexpr = new BinaryNode(equality, compexpr, right); } return compexpr; } // Rule: // comparison_expression -> addition_expression(( ">" | ">=" | "<" | "<=" ) addition_expression )* private Node ComparisonExpression() { Node additionexpr = this.AdditionExpression(); while (this.Match(TokenType.GreatThan) || this.Match(TokenType.GreatThanEqual) || this.Match(TokenType.LessThan) || this.Match(TokenType.LessThanEqual)) { Token comp = this.Consume(); Node right = this.AdditionExpression(); additionexpr = new BinaryNode(comp, additionexpr, right); } return additionexpr; } // Rule: // addition_expression -> multiplication_expression(( "-" | "+" ) multiplication_expression )* private Node AdditionExpression() { Node multexpr = this.MultiplicationExpression(); while (this.Match(TokenType.Minus) || this.Match(TokenType.Addition)) { Token addition = this.Consume(); Node right = this.MultiplicationExpression(); multexpr = new BinaryNode(addition, multexpr, right); } return multexpr; } // Rule: // multiplication_expression -> unary_expression(( "/" | "*" ) unary_expression )* private Node MultiplicationExpression() { Node unaryexpr = this.UnaryExpression(); while (this.Match(TokenType.Multiplication) || this.Match(TokenType.Division)) { Token mult = this.Consume(); Node right = this.UnaryExpression(); unaryexpr = new BinaryNode(mult, unaryexpr, right); } return unaryexpr; } // Rule: // unary_expression -> ( '!' | '-' ) unary_expression // | ( '++' | '--' ) symbol_expression symbol_operator* // | symbol_expression symbol_operator* ( '++' | '--' )? private Node UnaryExpression() { // ( '!' | '-' ) unary_expression if (this.Match(TokenType.Not) || this.Match(TokenType.Minus)) return new UnaryNode(this.Consume(), this.UnaryExpression()); // ( '++' | '--' ) symbol_expression symbol_operator* if (this.Match(TokenType.Increment) || this.Match(TokenType.Decrement)) { // ( '++' | '--' ) ... var prefix = this.Consume(); // ... symbol_expression ... var sexpr = this.SymbolExpression(); // ... symbol_operator* while (this.MatchAny(TokenType.Dot, TokenType.LeftBracket, TokenType.LeftParen)) sexpr = this.SymbolOperator(sexpr); return new UnaryPrefixNode(prefix, sexpr); } // symbol_expression symbol_operator* ('++' | '--') ? var symbolExpression = this.SymbolExpression(); // ... symbol_operator* ... while (this.MatchAny(TokenType.Dot, TokenType.LeftBracket, TokenType.LeftParen)) symbolExpression = this.SymbolOperator(symbolExpression); // ... ('++' | '--')? if (this.Match(TokenType.Increment) || this.Match(TokenType.Decrement)) return new UnaryPostfixNode(this.Consume(), symbolExpression); return symbolExpression; } // Rule: // symbol_expression -> 'new' IDENTIFIER ( '.' IDENTIFIER )* call_operator // | IDENTIFIER // | object_expression // | array_expression // | tuple_expression // | primary private Node SymbolExpression() { if (this.Match(TokenType.New)) { var newt = this.Consume(); var symbol = new AccessorNode(this.Consume(TokenType.Identifier), null); while (this.Match(TokenType.Dot)) { this.Consume(TokenType.Dot); symbol = new AccessorNode(this.Consume(TokenType.Identifier), symbol); } ExpressionListNode callOperator = this.Match(TokenType.LeftParen) ? this.CallOperator() : new ExpressionListNode(new List<Node>()); return new CallableNode(symbol, callOperator, newt); } if (this.Match(TokenType.Identifier)) return new AccessorNode(this.Consume(TokenType.Identifier), null); if (this.IsObjectExpression()) return this.ObjectExpression(); /*if (this.Match(TokenType.LeftBracket)) return this.ArrayExpression();*/ if (this.Match(TokenType.LeftParen)) return this.Try(this.TupleExpression, this.ParenthesizedExpression); return this.Primary(); } // Rule: // symbol_operator -> ( dot_operator | indexer_operator | call_operator ) // // dot_operator -> '.' IDENTIFIER private Node SymbolOperator(Node parent) { Node child = null; // dot_operator if (this.Match(TokenType.Dot)) { this.Consume(TokenType.Dot); child = new AccessorNode(this.Consume(TokenType.Identifier), parent); } // indexer_operator else if (this.Match(TokenType.LeftBracket)) { child = new IndexerNode(parent, this.IndexerOperator()); } // call_operator else if (this.Match(TokenType.LeftParen)) { ExpressionListNode callOperator = this.CallOperator(); child = new CallableNode(parent, callOperator); } return child; } // Rule: (it is easier to check the expression_list manually here) // indexer -> '[' expression_list ']' private ExpressionListNode IndexerOperator() { List<Node> args = new List<Node>(); this.Consume(TokenType.LeftBracket); do { args.Add(this.Expression()); while (this.Match(TokenType.Comma)) { this.Consume(); args.Add(this.Expression()); } } while ((!this.Match(TokenType.RightBracket))); this.Consume(TokenType.RightBracket); return new ExpressionListNode(args); } // Rule: (it is easier to check the expression_list manually here) // call_operator -> '(' expression_list? ')' private ExpressionListNode CallOperator() { List<Node> args = new List<Node>(); this.Consume(TokenType.LeftParen); if (!this.Match(TokenType.RightParen)) { args.Add(this.Expression()); while (this.Match(TokenType.Comma)) { this.Consume(); args.Add(this.Expression()); } } this.Consume(TokenType.RightParen); return new ExpressionListNode(args); } // Rule: // primary -> "true" | "false" | INTEGER | FLOAT | DOUBLE | DECIMAL | STRING | IDENTIFIER private Node Primary() { bool isPrimary = this.Match(TokenType.Boolean) || this.Match(TokenType.Char) || this.Match(TokenType.Integer) || this.Match(TokenType.Float) || this.Match(TokenType.Double) || this.Match(TokenType.Decimal) || this.Match(TokenType.String); if (!isPrimary) throw new ParserException($"{this.GetCurrentLineAndCol()} Expects primary but received {(this.HasInput() ? this.Peek().Type.ToString() : "end of input")}"); return new PrimitiveNode(this.Consume()); } #endregion private Node Try(params Func<Node>[] actions) { Node result = null; var checkpoint = this.SaveCheckpoint(); foreach (var action in actions) { try { result = action.Invoke(); } catch (Exception e) { } if (result != null) break; this.RestoreCheckpoint(checkpoint); } return result; } #region Parser lookahead helpers private bool IsClassPropertyDeclaration() { int offset = 0; if (this.Match(TokenType.AccessModifier)) offset++; if (this.MatchFrom(offset ,TokenType.Mutable)) offset++; if (this.MatchFrom(offset, TokenType.Identifier)) { // identifier identifier ( '=' expression )? if (this.MatchFrom(offset+1, TokenType.Identifier)) return true; // identifier ( '[' ']' )+ identifier ( '=' expression )? int dimensions = this.CountRepeatedMatchesFrom(offset + 1, TokenType.LeftBracket, TokenType.RightBracket); return dimensions > 0 && this.MatchFrom(dimensions + offset + 1, TokenType.Identifier); } return false; } private bool IsClassConstantDeclaration() { int offset = 0; if (this.Match(TokenType.AccessModifier)) offset++; return this.MatchFrom(offset, TokenType.Constant); } private bool IsClassMethodDeclaration() { int offset = 0; if (this.Match(TokenType.AccessModifier)) offset++; return this.MatchFrom(offset, TokenType.Function); } private bool IsVarDeclaration() { var offset = this.Match(TokenType.Mutable) ? 1 : 0; // 'var' identifier ( '=' expression )? if (this.MatchFrom(offset, TokenType.Variable)) return true; if (this.MatchFrom(offset, TokenType.Identifier, TokenType.LeftParen, TokenType.Identifier)) { // identifier (identifier, identifier, ..., identifier) '=' int decls = this.CountRepeatedMatchesFrom(offset + 2, TokenType.Identifier, TokenType.Comma); if (this.MatchFrom(offset + decls + 1, TokenType.Identifier, TokenType.RightParen, TokenType.Assignment)) return true; /*// identifier ( '[' ']' )+ (identifier, identifier, ..., identifier) int dimensions = CountRepeatedMatchesFrom(1, TokenType.LeftBracket, TokenType.RightBracket); return dimensions > 0 && MatchFrom(dimensions + 1, TokenType.Identifier);*/ } if (this.MatchFrom(offset, TokenType.Identifier)) { // identifier identifier ( '=' expression )? if (this.MatchFrom(offset + 1, TokenType.Identifier) && (this.MatchAnyFrom(offset + 2, TokenType.Assignment, TokenType.Semicolon) || this.MatchAnyFrom(offset + 2, TokenType.Comma, TokenType.Identifier))) return true; // identifier ( '[' ']' )+ identifier ( '=' expression )? int dimensions = this.CountRepeatedMatchesFrom(offset + 1, TokenType.LeftBracket, TokenType.RightBracket); return dimensions > 0 && this.MatchFrom(offset + dimensions + 1, TokenType.Identifier); } return false; } /// <summary> /// It is destructuring if it is wrapped by parenthesis and is a lvalue /// </summary> /// <returns></returns> private bool IsDestructuring() { // Check for a left-hand side expression containing a Comma if (!this.Match(TokenType.LeftParen)) { for (int i=0; i < this.tokens.Count; i++) { var t = this.PeekFrom(i); if (t == null || t.Type == TokenType.Assignment || t.Type == TokenType.Semicolon) break; if (t.Type == TokenType.Comma) return true; } } // Check for parenthesized list of identifiers return (this.Match(TokenType.LeftParen, TokenType.Identifier) && this.MatchAnyFrom(2, TokenType.Dot, TokenType.Comma, TokenType.RightParen)) || this.Match(TokenType.LeftParen, TokenType.Comma); } private bool IsAssignment() { return this.Match(TokenType.Identifier) && this.MatchAnyFrom(1, TokenType.Dot, TokenType.LeftParen, TokenType.Assignment, TokenType.IncrementAndAssign, TokenType.DecrementAndAssign, TokenType.DivideAndAssign, TokenType.MultAndAssign); } private bool IsObjectExpression() { if (this.Match(TokenType.At, TokenType.LeftBrace)) return true; return this.Match(TokenType.LeftBrace) && (this.MatchFrom(1, TokenType.RightBrace) || this.MatchFrom(1, TokenType.Mutable, TokenType.Identifier, TokenType.Colon) || this.MatchFrom(1, TokenType.Identifier, TokenType.Colon)); } private bool IsLambdaExpression() { if (this.Match(TokenType.RightArrow)) return true; bool needsParent = this.Match(TokenType.LeftParen); int offset = needsParent ? 1 : 0; while (this.MatchAnyFrom(offset, TokenType.Mutable, TokenType.Identifier, TokenType.Comma)) offset++; if (needsParent && this.MatchFrom(offset, TokenType.RightParen)) offset++; return this.MatchFrom(offset, TokenType.RightArrow); // => bool arrow = this.Match(TokenType.RightArrow); // a => bool paramArrow = (!this.Match(TokenType.LeftParen) && this.Match(TokenType.Unknown, TokenType.RightArrow)); // a,b => bool paramListArrow = this.MatchFrom(this.CountRepeatedMatchesFrom(0, TokenType.Unknown, TokenType.Comma), TokenType.RightArrow); // () => bool parentArrow = this.Match(TokenType.LeftParen, TokenType.RightParen, TokenType.RightArrow); // (a) => bool parentParamArrow = (!this.MatchFrom(1, TokenType.LeftParen) && this.Match(TokenType.LeftParen, TokenType.Unknown, TokenType.RightParen, TokenType.RightArrow)); // (a,b) => bool parentParamListArrow = (this.Match(TokenType.LeftParen) && this.MatchFrom(1 + this.CountRepeatedMatchesFrom(1, TokenType.Unknown, TokenType.Comma), TokenType.RightParen, TokenType.RightArrow)); return arrow || paramArrow || paramListArrow || parentArrow || parentParamArrow || parentParamListArrow; } private AccessorNode TryGetAccessor(Node primary) { Node tmp = primary; while (tmp != null) { if (tmp is AccessorNode) return tmp as AccessorNode; if (tmp is CallableNode) { tmp = (tmp as CallableNode).Target; continue; } } return null; } private PrimitiveNode TryGetPrimitive(Node primary) { Node tmp = primary; while (tmp != null) { if (tmp is PrimitiveNode) return tmp as PrimitiveNode; if (tmp is AccessorNode) { tmp = (tmp as AccessorNode).Parent; continue; } else if (tmp is CallableNode) { tmp = (tmp as CallableNode).Target; continue; } } return null; } #endregion } }
36.245087
210
0.527558
[ "MIT" ]
lbrugnara/flsharp
FrontEnd/Syntax/Parser.cs
62,706
C#
using System; namespace Open_Lab_02._04 { class Farm { public int GetLegsCount(int chickens, int cows, int pigs) { return (chickens * 2 + cows * 4 + pigs * 4); } } }
16.538462
65
0.530233
[ "MIT" ]
martinorion/Open-Lab-02.04
Open-Lab-02.04/Farm.cs
215
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; namespace CLRProfiler.Behaviors { public static class DialogCloser { public static readonly DependencyProperty DialogResultProperty = DependencyProperty.RegisterAttached( "DialogResult", typeof(bool?), typeof(DialogCloser), new PropertyMetadata(DialogResultChanged)); private static void DialogResultChanged( DependencyObject d, DependencyPropertyChangedEventArgs e) { var window = d as Window; if (window != null) window.DialogResult = e.NewValue as bool?; } public static void SetDialogResult(Window target, bool? value) { target.SetValue(DialogResultProperty, value); } } }
23.424242
66
0.754204
[ "MIT" ]
kingraham/debugging-clrmd
CLRProfiler/Behaviors/DialogResult.cs
775
C#
using System.Text; using MyStik.TimeTable.Data; using System; using System.Collections.Generic; using System.Linq; namespace MyStik.TimeTable.Web.Models { /// <summary> /// /// </summary> public class ActivityCurrentModel { /// <summary> /// /// </summary> public List<ActivityDate> CurrentDates { get; set; } /// <summary> /// /// </summary> public List<ActivityDate> CanceledDates { get; set; } } /// <summary> /// /// </summary> public class ActivityPlanModel { /// <summary> /// /// </summary> public ActivityPlanModel() { MyActivities = new List<ActivitySummary>(); MySubscriptions = new List<ActivitySubscriptionModel>(); } /// <summary> /// /// </summary> public List<ActivitySummary> MyActivities { get; } /// <summary> /// /// </summary> public List<ActivitySubscriptionModel> MySubscriptions { get; } public ActivityOrganiser Organiser { get; set; } public Semester Semester { get; set; } /// <summary> /// /// </summary> public bool HasLottery { get; set; } /// <summary> /// /// </summary> public bool IsDuringLottery { get; set; } } /// <summary> /// /// </summary> public class ActivitySubscriptionModel { /// <summary> /// /// </summary> public IActivitySummary Activity { get; set; } /// <summary> /// /// </summary> public OccurrenceStateModel State { get; set; } } /// <summary> /// /// </summary> public interface IActivitySummary { /// <summary> /// /// </summary> Activity Activity { get; } /// <summary> /// /// </summary> ActivitySummary Summary { get; } /// <summary> /// /// </summary> string Name { get; } /// <summary> /// /// </summary> string TimeFrame { get; } /// <summary> /// /// </summary> string Action { get; } /// <summary> /// /// </summary> string Controller { get; } /// <summary> /// /// </summary> string Id { get; } /// <summary> /// /// </summary> string IconName { get; } /// <summary> /// /// </summary> string BannerColor { get; } /// <summary> /// /// </summary> ICollection<OccurrenceSubscription> Subscriptions { get; } /// <summary> /// /// </summary> /// <param name="start"></param> /// <param name="end"></param> /// <returns></returns> ICollection<ActivityDate> GetDates(DateTime start, DateTime end); /// <summary> /// /// </summary> string NextDateTime { get; } } /// <summary> /// /// </summary> public class ActivitySummary : IActivitySummary { /// <summary> /// /// </summary> public ActivitySummary() { } /// <summary> /// /// </summary> /// <param name="act"></param> public ActivitySummary(Activity act) { Activity = act; } /// <summary> /// /// </summary> public ActivitySummary Summary => new ActivitySummary(Activity); /// <summary> /// /// </summary> public Activity Activity { get; set; } /// <summary> /// /// </summary> public string Name { get { if (string.IsNullOrEmpty(Activity.Name)) { if (string.IsNullOrEmpty(Activity.ShortName)) { return "N.N."; } return Activity.ShortName; } return Activity.Name; } } /// <summary> /// /// </summary> public string TimeFrame => ""; /// <summary> /// /// </summary> public string Action { get { if (Activity is OfficeHour) return "OfficeHour"; return "Index"; } } /// <summary> /// /// </summary> public string Controller { get { if (Activity is Course) return "Course"; if (Activity is Newsletter) return "Newsletter"; if (Activity is OfficeHour) return "Lecturer"; if (Activity is Event) return "Event"; if (Activity is Reservation) return "Reservation"; return string.Empty; } } /// <summary> /// /// </summary> public string Id { get { if (Activity != null) { /* if (Activity is OfficeHour hour) { var oh = hour; var date = oh.Dates.FirstOrDefault(); var host = date?.Hosts.FirstOrDefault(); if (host != null) { return hour.Semester.Id.ToString(); } } */ return Activity.Id.ToString(); } return string.Empty; } } /// <summary> /// /// </summary> public string IconName { get { if (Activity is Course) return "fa-lightbulb-o"; if (Activity is Newsletter) return "fa-envelope"; if (Activity is OfficeHour) return "fa-stethoscope"; if (Activity is Event) return "fa-tag"; if (Activity is Reservation) return "fa-check-square-o"; return string.Empty; } } /// <summary> /// /// </summary> public string BannerColor { get { if (Activity is Course) return "bg-fillter-lecturer"; if (Activity is Newsletter) return "bg-fillter-events"; if (Activity is OfficeHour) return "bg-fillter-lecturer"; if (Activity is Event) return "bg-fillter-events"; if (Activity is Reservation) return "bg-fillter-rooms"; return string.Empty; } } /// <summary> /// /// </summary> public ICollection<OccurrenceSubscription> Subscriptions { get { if (Activity.Occurrence != null) { return Activity.Occurrence.Subscriptions; } else { return new List<OccurrenceSubscription>(); } } } /// <summary> /// /// </summary> /// <param name="start"></param> /// <param name="end"></param> /// <returns></returns> public ICollection<ActivityDate> GetDates(DateTime start, DateTime end) { return Activity.Dates.Where(d => d.Begin >= start && d.End <= end).ToList(); } /// <summary> /// /// </summary> public CourseDateStateModel CurrentDate { get; set; } /// <summary> /// /// </summary> public CourseDateStateModel NextDate { get; set; } /// <summary> /// /// </summary> public string Details { get { var activity = Activity as Course; if (activity != null) { var course = activity; var sb = new StringBuilder(); foreach (var semesterGroup in course.SemesterGroups) { sb.AppendFormat("{0}", semesterGroup.FullName); if (semesterGroup != course.SemesterGroups.Last()) sb.Append(", "); } return sb.ToString(); } return ""; } } /// <summary> /// /// </summary> public string NextDateTime { get { var sb = new StringBuilder(); var nextDate = Activity.Dates.Where(d => d.Begin >= DateTime.Now) .OrderBy(d => d.Begin) .FirstOrDefault(); if (nextDate != null) { sb.AppendFormat("{0} [{1} - {2}] ", nextDate.Begin.ToShortDateString(), nextDate.Begin.ToShortTimeString(), nextDate.End.ToShortTimeString()); return sb.ToString(); } else { return "Keine Termine"; } } } } /// <summary> /// /// </summary> public class ActivityDateSummary : IActivitySummary { /// <summary> /// /// </summary> public ActivityDateSummary() { } /// <summary> /// /// </summary> /// <param name="date"></param> /// <param name="dateType"></param> public ActivityDateSummary(ActivityDate date, ActivityDateType dateType) { Date = date; DateType = dateType; } /// <summary> /// /// </summary> /// <param name="date"></param> /// <param name="dateType"></param> public ActivityDateSummary(ActivityDate date, OccurrenceSubscription sub) { Date = date; DateType = ActivityDateType.Subscription; Subscription = sub; } /// <summary> /// /// </summary> public Activity Activity => Date.Activity; /// <summary> /// /// </summary> public ActivitySummary Summary => new ActivitySummary(Activity); /// <summary> /// /// </summary> public ActivityDateType DateType { get; set; } /// <summary> /// /// </summary> public ActivityDate Date { get; set; } /// <summary> /// /// </summary> public ActivitySlot Slot { get; set; } public OccurrenceSubscription Subscription { get; set; } /// <summary> /// /// </summary> public string Name { get { var sb = new StringBuilder(); if (Date.Activity != null) { if (Date.Activity is Reservation) { sb.AppendFormat("{0} ({1})", Date.Description, Date.Activity.Organiser.ShortName); } else { sb.Append(Date.Activity.Name); if (!string.IsNullOrEmpty(Date.Title)) { sb.AppendFormat(" ({0})", Date.Title); } } } else { sb.Append("N.N."); } return sb.ToString(); } } /// <summary> /// /// </summary> public string ShortName { get { var sb = new StringBuilder(); if (Date.Activity != null) { if (Date.Activity is Reservation) { sb.AppendFormat("{0} ({1})", Date.Activity.Name, Date.Activity.Organiser.ShortName); } else { sb.Append(string.IsNullOrEmpty(Date.Activity.ShortName) ? "N.N." : Date.Activity.ShortName); } } else { sb.Append("N.N."); } if (!string.IsNullOrEmpty(Date.ShortName)) { sb.AppendFormat(" ({0})", Date.ShortName); } return sb.ToString(); } } /// <summary> /// /// </summary> public string TimeFrame => $"{Date.Begin} - {Date.End}"; /// <summary> /// /// </summary> public string Action => new ActivitySummary(Date.Activity).Action; /// <summary> /// /// </summary> public string Controller => new ActivitySummary(Date.Activity).Controller; /// <summary> /// /// </summary> public string Id => new ActivitySummary(Date.Activity).Id; /// <summary> /// /// </summary> public string IconName => new ActivitySummary(Date.Activity).IconName; /// <summary> /// /// </summary> public string BannerColor => new ActivitySummary(Date.Activity).BannerColor; /// <summary> /// /// </summary> public ICollection<OccurrenceSubscription> Subscriptions { get { if (Date.Slots.Count > 0) { var subscriptions = new List<OccurrenceSubscription>(); foreach (var slot in Date.Slots) { subscriptions.AddRange(slot.Occurrence.Subscriptions); } return subscriptions; } if (!Date.Occurrence.Subscriptions.Any()) { return Date.Activity.Occurrence.Subscriptions; } return Date.Occurrence.Subscriptions; } } /// <summary> /// /// </summary> /// <param name="start"></param> /// <param name="end"></param> /// <returns></returns> public ICollection<ActivityDate> GetDates(DateTime start, DateTime end) { var dates = new List<ActivityDate>(); if (Date.Begin >= start && Date.End <= end) dates.Add(Date); return dates; } /// <summary> /// /// </summary> public string TextColor => "#000"; /// <summary> /// /// </summary> public string BackgroundColor { get { // Keine Occurrence => war mal ein Fehler, jetzt gibt es Raumreservierungen if (Date.Occurrence == null) { if (Date.Activity is Reservation) return "#CCC"; return "#F00"; } // wenn der Termin ausfällt, immer roter Hintergrund if (Date.Occurrence.IsCanceled) return "#FFB5C5"; if (Subscription == null) { switch (DateType) { case ActivityDateType.Offer: // Eigene Angebote: weiss return "#FFF"; case ActivityDateType.SearchResult: // Suchergebnisse: grau return "#CCC"; case ActivityDateType.Subscription: // Eintragungen: grün = findet statt return "#ffffb3"; default: return "#FFF"; } } else { if (Subscription.OnWaitingList) { return "#c89f23"; } else { return "#37918b"; } } } } /// <summary> /// /// </summary> public string NextDateTime { get { var sb = new StringBuilder(); sb.AppendFormat("{0} [{1} - {2}] ", Date.Begin.ToShortDateString(), Date.Begin.ToShortTimeString(), Date.End.ToShortTimeString()); return sb.ToString(); } } } /// <summary> /// /// </summary> public enum ActivityDateType { /// <summary> /// /// </summary> Offer, /// <summary> /// /// </summary> Subscription, /// <summary> /// /// </summary> SearchResult } /// <summary> /// /// </summary> public class ActivitySlotSummary : IActivitySummary { /// <summary> /// /// </summary> public ActivitySlot Slot { get; set; } /// <summary> /// /// </summary> public string Name { get { var sb = new StringBuilder(); sb.Append(Slot.ActivityDate.Activity.Name); if (!string.IsNullOrEmpty(Slot.ActivityDate.Title)) { sb.AppendFormat(" ({0})", Slot.ActivityDate.Title); } return sb.ToString(); } } /// <summary> /// /// </summary> public Activity Activity => Slot.ActivityDate.Activity; /// <summary> /// /// </summary> public ActivitySummary Summary => new ActivitySummary(Activity); /// <summary> /// /// </summary> public string TimeFrame => $"{Slot.ActivityDate.Begin.Date}: {Slot.Begin} - {Slot.End}"; /// <summary> /// /// </summary> public string Action => new ActivitySummary(Slot.ActivityDate.Activity).Action; /// <summary> /// /// </summary> public string Controller => new ActivitySummary(Slot.ActivityDate.Activity).Controller; /// <summary> /// /// </summary> public string Id => new ActivitySummary(Slot.ActivityDate.Activity).Id; /// <summary> /// /// </summary> public string IconName => new ActivitySummary(Slot.ActivityDate.Activity).IconName; /// <summary> /// /// </summary> public string BannerColor => new ActivitySummary(Slot.ActivityDate.Activity).BannerColor; /// <summary> /// /// </summary> public ICollection<OccurrenceSubscription> Subscriptions => Slot.Occurrence.Subscriptions; /// <summary> /// /// </summary> /// <param name="start"></param> /// <param name="end"></param> /// <returns></returns> public ICollection<ActivityDate> GetDates(DateTime start, DateTime end) { var dates = new List<ActivityDate>(); if (Slot.ActivityDate.Begin >= start && Slot.ActivityDate.End <= end) dates.Add(Slot.ActivityDate); return dates; } /// <summary> /// /// </summary> public string NextDateTime { get { var sb = new StringBuilder(); sb.AppendFormat("{0} [{1} - {2}] ", Slot.Begin.ToShortDateString(), Slot.Begin.ToShortTimeString(), Slot.End.ToShortTimeString()); return sb.ToString(); } } } public class ActivitySemesterViewModel { public Semester Semester { get; set; } public ICollection<Course> Courses { get; set; } } }
25.688264
116
0.406463
[ "MIT" ]
AccelerateX-org/NINE
Sources/TimeTable/MyStik.TimeTable.Web/Models/ActivityModels.cs
21,017
C#
using System; using System.Collections.Generic; using System.Text; namespace InventoryManagementSoftware.Model.Requests { public class ImportExportDetailSearchObject { public int? ImportExportId { get; set; } } }
19.583333
52
0.740426
[ "MIT" ]
farisl/InventoryManagementSoftware
InventoryManagementSoftware/InventoryManagementSoftware.Model/Requests/ImportExportDetailSearchObject.cs
237
C#
using System; using System.Collections.Generic; using System.Linq; namespace Telerik_OOP_03_Principles__StudentsAndWorkers { class StartUp { static void Main(string[] args) { // We initialize a list of 10 students and sort them by grade in ascending order. var listStudents = new List<Student> { new Student("Pesho", "Peshev", 6.00), new Student("Gosho", "Goshev", 5.83), new Student("Ivan", "Ivanov", 5.96), new Student("Peter", "Petrov", 4.83), new Student("Maria", "Marinova", 5.98), new Student("Anastasia", "Ivanova", 6.00), new Student("Magdalena", "Nikolova", 3.83), new Student("Nikolai", "Georgiev", 4.83), new Student("Alexander", "Dimitrov", 5.23), new Student("Ognyan", "Vasilev", 4.83)}; Console.WriteLine("Students:"); foreach(Student student in listStudents.OrderBy(x => x.Grade)) { Console.WriteLine(student.Print()); } Console.WriteLine("\nWorkers:"); //Initialize a list of 10 workers and sort them by money per hour in descending order. var listWorkers = new List<Worker> { new Worker("Peshko", "Peshev", 100, 20), new Worker("Goshko", "Goshev", 50, 50), new Worker("Ivancho", "Ivanov", 30, 40), new Worker("Peter", "Petrov", 500, 40 ), new Worker("Mimi", "Marinova", 70, 40), new Worker("Ana", "Ivanova", 300, 25), new Worker("Magi", "Nikolova", 1000, 40), new Worker("Niki", "Georgiev", 60, 10), new Worker("Alex", "Dimitrov", 90, 10), new Worker("Ogi", "Vasilev", 60, 10)}; foreach(Worker worker in listWorkers.OrderByDescending(x => x.CalculateMoneyPerHour())) { Console.WriteLine(worker.Print()); } //Merge the lists and sort them by first name and last name. var mergedLists = new List<Human>(); mergedLists.AddRange(listStudents); mergedLists.AddRange(listWorkers); Console.WriteLine("\nSorted merged list by first and then second names:"); foreach(Human human in mergedLists.OrderBy(x => x.FirstName).ThenBy(x => x.LastName)) { Console.WriteLine(human.Print()); } } } }
51.622222
144
0.582006
[ "MIT" ]
SophiaKiryakova/TelerikAcademyAlpha
Module I/C#-OOP/Homework/03. OOP-Principles-Part-1/StudentsAndWorkers/Telerik_OOP_03_Principles_ StudentsAndWorkers/StartUp.cs
2,325
C#
using System.Collections.Generic; using TinyECS.Interfaces; using TinyECSUnityIntegration.Impls; using UnityEngine; public class RotatingCubesSystem: IUpdateSystem { protected IWorldContext mWorldContext; public RotatingCubesSystem(IWorldContext worldContext) { mWorldContext = worldContext; } public void Update(float deltaTime) { // get all entities with TRotatingCubeComponent component List<uint> entities = mWorldContext.GetEntitiesWithAll(typeof(TRotatingCubeComponent)); IEntity currEntity = null; for (int i = 0; i < entities.Count; ++i) { currEntity = mWorldContext.GetEntityById(entities[i]); // now we have two ways: strongly coupled code or use TinyECS approach // first version: /* * uncomment to test this version * TViewComponent viewComponent = currEntity.GetComponent<TViewComponent>(); TRotatingCubeComponent rotatingCubeComponent = currEntity.GetComponent<TRotatingCubeComponent>(); viewComponent.mView.transform.Rotate(Vector3.up, rotatingCubeComponent.mSpeed); */ // second version (TinyECS approach) /* */ TRotatingCubeComponent rotatingCubeComponent = currEntity.GetComponent<TRotatingCubeComponent>(); TRotationComponent rotationComponent = currEntity.GetComponent<TRotationComponent>(); currEntity.AddComponent(new TRotationComponent { mRotation = rotationComponent.mRotation * Quaternion.Euler(0.0f, rotatingCubeComponent.mSpeed, 0.0f) }); } } }
34.040816
165
0.673861
[ "Apache-2.0" ]
bnoazx005/TinyECS
Samples/Tutorial02_TinyECSIntegrationWithUnity3D/Assets/Scripts/Systems/RotatingCubesSystem.cs
1,670
C#
using AutoMapper; using JokesOnYou.Web.Api.DTOs; using JokesOnYou.Web.Api.Models; namespace JokesOnYou.Web.Api.Profiles { public class TagProfile : Profile { public TagProfile() { CreateMap<Tag, TagReplyDto>(); CreateMap<TagCreateDto, Tag>(); } } }
19.4375
43
0.614148
[ "Unlicense" ]
Palisar/JokesOnYou
Server/JokesOnYou.Web.Api/Profiles/TagProfile.cs
313
C#
namespace treeDiM.StackBuilder.Desktop { partial class DockContentDocumentExplorer { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(DockContentDocumentExplorer)); this.ContextMenuDock = new System.Windows.Forms.ContextMenuStrip(this.components); this.FloatingToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.DockableToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.TabbedDocumentToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.AutoHideToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.HideToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this._documentTreeView = new treeDiM.StackBuilder.Desktop.AnalysisTreeView(); this.ContextMenuDock.SuspendLayout(); this.SuspendLayout(); // // ContextMenuDock // this.ContextMenuDock.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.FloatingToolStripMenuItem, this.DockableToolStripMenuItem, this.TabbedDocumentToolStripMenuItem, this.AutoHideToolStripMenuItem, this.HideToolStripMenuItem}); this.ContextMenuDock.Name = "ContextMenuStrip1"; this.ContextMenuDock.Size = new System.Drawing.Size(174, 114); this.ContextMenuDock.Text = "Window Position"; // // FloatingToolStripMenuItem // this.FloatingToolStripMenuItem.CheckOnClick = true; this.FloatingToolStripMenuItem.Name = "FloatingToolStripMenuItem"; this.FloatingToolStripMenuItem.Size = new System.Drawing.Size(173, 22); this.FloatingToolStripMenuItem.Text = "Floating"; this.FloatingToolStripMenuItem.Click += new System.EventHandler(this.FloatingToolStripMenuItem_Click); // // DockableToolStripMenuItem // this.DockableToolStripMenuItem.Checked = true; this.DockableToolStripMenuItem.CheckOnClick = true; this.DockableToolStripMenuItem.CheckState = System.Windows.Forms.CheckState.Checked; this.DockableToolStripMenuItem.Name = "DockableToolStripMenuItem"; this.DockableToolStripMenuItem.Size = new System.Drawing.Size(173, 22); this.DockableToolStripMenuItem.Text = "Dockable"; this.DockableToolStripMenuItem.Click += new System.EventHandler(this.DockableToolStripMenuItem_Click); // // TabbedDocumentToolStripMenuItem // this.TabbedDocumentToolStripMenuItem.CheckOnClick = true; this.TabbedDocumentToolStripMenuItem.Name = "TabbedDocumentToolStripMenuItem"; this.TabbedDocumentToolStripMenuItem.Size = new System.Drawing.Size(173, 22); this.TabbedDocumentToolStripMenuItem.Text = "Tabbed Document"; this.TabbedDocumentToolStripMenuItem.Click += new System.EventHandler(this.TabbedDocumentToolStripMenuItem_Click); // // AutoHideToolStripMenuItem // this.AutoHideToolStripMenuItem.CheckOnClick = true; this.AutoHideToolStripMenuItem.Name = "AutoHideToolStripMenuItem"; this.AutoHideToolStripMenuItem.Size = new System.Drawing.Size(173, 22); this.AutoHideToolStripMenuItem.Text = "Auto Hide"; this.AutoHideToolStripMenuItem.Click += new System.EventHandler(this.AutoHideToolStripMenuItem_Click); // // HideToolStripMenuItem // this.HideToolStripMenuItem.CheckOnClick = true; this.HideToolStripMenuItem.Name = "HideToolStripMenuItem"; this.HideToolStripMenuItem.Size = new System.Drawing.Size(173, 22); this.HideToolStripMenuItem.Text = "Hide"; // // _documentTreeView // this._documentTreeView.Dock = System.Windows.Forms.DockStyle.Fill; this._documentTreeView.ImageIndex = 0; this._documentTreeView.Location = new System.Drawing.Point(0, 0); this._documentTreeView.Name = "_documentTreeView"; this._documentTreeView.SelectedImageIndex = 0; this._documentTreeView.Size = new System.Drawing.Size(284, 549); this._documentTreeView.TabIndex = 1; // // DockContentDocumentExplorer // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(284, 549); this.CloseButton = false; this.CloseButtonVisible = false; this.ControlBox = false; this.Controls.Add(this._documentTreeView); this.DockAreas = ((WeifenLuo.WinFormsUI.Docking.DockAreas)(((((WeifenLuo.WinFormsUI.Docking.DockAreas.Float | WeifenLuo.WinFormsUI.Docking.DockAreas.DockLeft) | WeifenLuo.WinFormsUI.Docking.DockAreas.DockRight) | WeifenLuo.WinFormsUI.Docking.DockAreas.DockTop) | WeifenLuo.WinFormsUI.Docking.DockAreas.DockBottom))); this.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "DockContentDocumentExplorer"; this.ShowHint = WeifenLuo.WinFormsUI.Docking.DockState.DockLeft; this.ShowInTaskbar = false; this.TabPageContextMenuStrip = this.ContextMenuDock; this.Text = "Document explorer"; this.ContextMenuDock.ResumeLayout(false); this.ResumeLayout(false); } #endregion internal System.Windows.Forms.ContextMenuStrip ContextMenuDock; internal System.Windows.Forms.ToolStripMenuItem FloatingToolStripMenuItem; internal System.Windows.Forms.ToolStripMenuItem DockableToolStripMenuItem; internal System.Windows.Forms.ToolStripMenuItem TabbedDocumentToolStripMenuItem; internal System.Windows.Forms.ToolStripMenuItem AutoHideToolStripMenuItem; internal System.Windows.Forms.ToolStripMenuItem HideToolStripMenuItem; internal AnalysisTreeView _documentTreeView; } }
54.521127
171
0.643632
[ "Unlicense", "MIT" ]
siranen/PalletBuilder
TreeDim.StackBuilder.Desktop/DockContentDocumentExplorer.Designer.cs
7,744
C#
using Quasar.Client.Networking; using Quasar.Common; using Quasar.Common.Enums; using Quasar.Common.Extensions; using Quasar.Common.Helpers; using Quasar.Common.IO; using Quasar.Common.Messages; using Quasar.Common.Models; using Quasar.Common.Networking; using System; using System.Collections.Concurrent; using System.IO; using System.Linq; using System.Security; using System.Threading; namespace Quasar.Client.Messages { public class FileManagerHandler : NotificationMessageProcessor, IDisposable { private readonly ConcurrentDictionary<int, FileSplit> _activeTransfers = new ConcurrentDictionary<int, FileSplit>(); private readonly Semaphore _limitThreads = new Semaphore(2, 2); // maximum simultaneous file downloads private readonly QuasarClient _client; private CancellationTokenSource _tokenSource; private CancellationToken _token; public FileManagerHandler(QuasarClient client) { _client = client; _client.ClientState += OnClientStateChange; _tokenSource = new CancellationTokenSource(); _token = _tokenSource.Token; } private void OnClientStateChange(Networking.Client s, bool connected) { switch (connected) { case true: _tokenSource?.Dispose(); _tokenSource = new CancellationTokenSource(); _token = _tokenSource.Token; break; case false: // cancel all running transfers on disconnect _tokenSource.Cancel(); break; } } public override bool CanExecute(IMessage message) => message is GetDrives || message is GetDirectory || message is FileTransferRequest || message is FileTransferCancel || message is FileTransferChunk || message is DoPathDelete || message is DoPathRename; public override bool CanExecuteFrom(ISender sender) => true; public override void Execute(ISender sender, IMessage message) { switch (message) { case GetDrives msg: Execute(sender, msg); break; case GetDirectory msg: Execute(sender, msg); break; case FileTransferRequest msg: Execute(sender, msg); break; case FileTransferCancel msg: Execute(sender, msg); break; case FileTransferChunk msg: Execute(sender, msg); break; case DoPathDelete msg: Execute(sender, msg); break; case DoPathRename msg: Execute(sender, msg); break; } } private void Execute(ISender client, GetDrives command) { DriveInfo[] driveInfos; try { driveInfos = DriveInfo.GetDrives().Where(d => d.IsReady).ToArray(); } catch (IOException) { client.Send(new SetStatusFileManager { Message = "GetDrives I/O error", SetLastDirectorySeen = false }); return; } catch (UnauthorizedAccessException) { client.Send(new SetStatusFileManager { Message = "GetDrives No permission", SetLastDirectorySeen = false }); return; } if (driveInfos.Length == 0) { client.Send(new SetStatusFileManager { Message = "GetDrives No drives", SetLastDirectorySeen = false }); return; } Drive[] drives = new Drive[driveInfos.Length]; for (int i = 0; i < drives.Length; i++) { try { var displayName = !string.IsNullOrEmpty(driveInfos[i].VolumeLabel) ? string.Format("{0} ({1}) [{2}, {3}]", driveInfos[i].RootDirectory.FullName, driveInfos[i].VolumeLabel, driveInfos[i].DriveType.ToFriendlyString(), driveInfos[i].DriveFormat) : string.Format("{0} [{1}, {2}]", driveInfos[i].RootDirectory.FullName, driveInfos[i].DriveType.ToFriendlyString(), driveInfos[i].DriveFormat); drives[i] = new Drive { DisplayName = displayName, RootDirectory = driveInfos[i].RootDirectory.FullName }; } catch (Exception) { } } client.Send(new GetDrivesResponse { Drives = drives }); } private void Execute(ISender client, GetDirectory message) { bool isError = false; string statusMessage = null; Action<string> onError = (msg) => { isError = true; statusMessage = msg; }; try { DirectoryInfo dicInfo = new DirectoryInfo(message.RemotePath); FileInfo[] files = dicInfo.GetFiles(); DirectoryInfo[] directories = dicInfo.GetDirectories(); FileSystemEntry[] items = new FileSystemEntry[files.Length + directories.Length]; int offset = 0; for (int i = 0; i < directories.Length; i++, offset++) { items[i] = new FileSystemEntry { EntryType = FileType.Directory, Name = directories[i].Name, Size = 0, LastAccessTimeUtc = directories[i].LastAccessTimeUtc }; } for (int i = 0; i < files.Length; i++) { items[i + offset] = new FileSystemEntry { EntryType = FileType.File, Name = files[i].Name, Size = files[i].Length, ContentType = Path.GetExtension(files[i].Name).ToContentType(), LastAccessTimeUtc = files[i].LastAccessTimeUtc }; } client.Send(new GetDirectoryResponse { RemotePath = message.RemotePath, Items = items }); } catch (UnauthorizedAccessException) { onError("GetDirectory No permission"); } catch (SecurityException) { onError("GetDirectory No permission"); } catch (PathTooLongException) { onError("GetDirectory Path too long"); } catch (DirectoryNotFoundException) { onError("GetDirectory Directory not found"); } catch (FileNotFoundException) { onError("GetDirectory File not found"); } catch (IOException) { onError("GetDirectory I/O error"); } catch (Exception) { onError("GetDirectory Failed"); } finally { if (isError && !string.IsNullOrEmpty(statusMessage)) client.Send(new SetStatusFileManager { Message = statusMessage, SetLastDirectorySeen = true }); } } private void Execute(ISender client, FileTransferRequest message) { new Thread(() => { _limitThreads.WaitOne(); try { using (var srcFile = new FileSplit(message.RemotePath, FileAccess.Read)) { _activeTransfers[message.Id] = srcFile; OnReport("File upload started"); foreach (var chunk in srcFile) { if (_token.IsCancellationRequested || !_activeTransfers.ContainsKey(message.Id)) break; // blocking sending might not be required, needs further testing _client.SendBlocking(new FileTransferChunk { Id = message.Id, FilePath = message.RemotePath, FileSize = srcFile.FileSize, Chunk = chunk }); } client.Send(new FileTransferComplete { Id = message.Id, FilePath = message.RemotePath }); } } catch (Exception) { client.Send(new FileTransferCancel { Id = message.Id, Reason = "Error reading file" }); } finally { RemoveFileTransfer(message.Id); _limitThreads.Release(); } }).Start(); } private void Execute(ISender client, FileTransferCancel message) { if (_activeTransfers.ContainsKey(message.Id)) { RemoveFileTransfer(message.Id); client.Send(new FileTransferCancel { Id = message.Id, Reason = "Canceled" }); } } private void Execute(ISender client, FileTransferChunk message) { try { if (message.Chunk.Offset == 0) { string filePath = message.FilePath; if (string.IsNullOrEmpty(filePath)) { // generate new temporary file path if empty filePath = FileHelper.GetTempFilePath(".exe"); } if (File.Exists(filePath)) { // delete existing file NativeMethods.DeleteFile(filePath); } _activeTransfers[message.Id] = new FileSplit(filePath, FileAccess.Write); OnReport("File download started"); } if (!_activeTransfers.ContainsKey(message.Id)) return; var destFile = _activeTransfers[message.Id]; destFile.WriteChunk(message.Chunk); if (destFile.FileSize == message.FileSize) { client.Send(new FileTransferComplete { Id = message.Id, FilePath = destFile.FilePath }); RemoveFileTransfer(message.Id); } } catch (Exception) { RemoveFileTransfer(message.Id); client.Send(new FileTransferCancel { Id = message.Id, Reason = "Error writing file" }); } } private void Execute(ISender client, DoPathDelete message) { bool isError = false; string statusMessage = null; Action<string> onError = (msg) => { isError = true; statusMessage = msg; }; try { switch (message.PathType) { case FileType.Directory: Directory.Delete(message.Path, true); client.Send(new SetStatusFileManager { Message = "Deleted directory", SetLastDirectorySeen = false }); break; case FileType.File: File.Delete(message.Path); client.Send(new SetStatusFileManager { Message = "Deleted file", SetLastDirectorySeen = false }); break; } Execute(client, new GetDirectory { RemotePath = Path.GetDirectoryName(message.Path) }); } catch (UnauthorizedAccessException) { onError("DeletePath No permission"); } catch (PathTooLongException) { onError("DeletePath Path too long"); } catch (DirectoryNotFoundException) { onError("DeletePath Path not found"); } catch (IOException) { onError("DeletePath I/O error"); } catch (Exception) { onError("DeletePath Failed"); } finally { if (isError && !string.IsNullOrEmpty(statusMessage)) client.Send(new SetStatusFileManager { Message = statusMessage, SetLastDirectorySeen = false }); } } private void Execute(ISender client, DoPathRename message) { bool isError = false; string statusMessage = null; Action<string> onError = (msg) => { isError = true; statusMessage = msg; }; try { switch (message.PathType) { case FileType.Directory: Directory.Move(message.Path, message.NewPath); client.Send(new SetStatusFileManager { Message = "Renamed directory", SetLastDirectorySeen = false }); break; case FileType.File: File.Move(message.Path, message.NewPath); client.Send(new SetStatusFileManager { Message = "Renamed file", SetLastDirectorySeen = false }); break; } Execute(client, new GetDirectory { RemotePath = Path.GetDirectoryName(message.NewPath) }); } catch (UnauthorizedAccessException) { onError("RenamePath No permission"); } catch (PathTooLongException) { onError("RenamePath Path too long"); } catch (DirectoryNotFoundException) { onError("RenamePath Path not found"); } catch (IOException) { onError("RenamePath I/O error"); } catch (Exception) { onError("RenamePath Failed"); } finally { if (isError && !string.IsNullOrEmpty(statusMessage)) client.Send(new SetStatusFileManager { Message = statusMessage, SetLastDirectorySeen = false }); } } private void RemoveFileTransfer(int id) { if (_activeTransfers.ContainsKey(id)) { _activeTransfers[id]?.Dispose(); _activeTransfers.TryRemove(id, out _); } } /// <summary> /// Disposes all managed and unmanaged resources associated with this message processor. /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposing) { _client.ClientState -= OnClientStateChange; _tokenSource.Cancel(); _tokenSource.Dispose(); foreach (var transfer in _activeTransfers) { transfer.Value?.Dispose(); } _activeTransfers.Clear(); } } } }
34.720648
124
0.447003
[ "Apache-2.0", "MIT" ]
2-young-2-simple/QuasarRAT
Quasar.Client/Messages/FileManagerHandler.cs
17,154
C#
// // Copyright (c) 2019-2021 Angouri. // AngouriMath is licensed under MIT. // Details: https://github.com/asc-community/AngouriMath/blob/master/LICENSE.md. // Website: https://am.angouri.org. // using static System.Console; using AngouriMath.Extensions; using static AngouriMath.MathS; using AngouriMath; using static AngouriMath.Entity.Number; // Hello world in AM WriteLine("Alright, let's start from a hello world"); WriteLine("2 + 3 is " + "2 + 3".EvalNumerical().Stringize()); WriteLine(); // Simplify WriteLine("x + 3 + 4 + x + 2x + 23 + a".Simplify().Stringize()); WriteLine(); // Build expressions var x = Var("x"); var expr = Sin(x) + Sqrt(x) + Integral(Sin(Sin(x)), x); WriteLine(expr.Stringize()); WriteLine(); // Derive WriteLine(expr.Differentiate(x).Simplify().Stringize()); WriteLine(); // Solve a simple equation WriteLine("x2 = 3".Solve("x").Stringize()); WriteLine(); // Solve a complicated statement WriteLine("(x - 2)(x - 3) = 0 and (x - 1)(x - 2) = 0".Solve("x").InnerSimplified.Stringize()); WriteLine("sin(a x)2 + c sin(2 a x) = c".Solve("x")); WriteLine("(x - 6)(x + 9) >= 0".Solve("x").Latexise()); WriteLine(); // Work with sets WriteLine("{ 1, 2 }".Latexise()); WriteLine("[3; +oo)".Latexise()); WriteLine("RR".Latexise()); WriteLine("{ x : x8 + a x < 0 }".Latexise()); WriteLine(@"A \/ B".Latexise()); WriteLine(@"A /\ B".Latexise()); WriteLine(@"A \ B".Latexise()); WriteLine(@"{ 1, 2, 3 } \/ { 3, 5 }".Simplify()); WriteLine(@"[a; b) \/ { b }".Simplify()); WriteLine(); // Differentiate, integrate, find limits WriteLine("x2 + a x".Differentiate("x").InnerSimplified); WriteLine("x2 + a x".Integrate("x").InnerSimplified.Latexise()); WriteLine("(a x2 + b x) / (e x - h x2 - 3)".Limit("x", "+oo").InnerSimplified); WriteLine(); // Boolean WriteLine("true and false implies true".Simplify()); WriteLine(string.Join(" ", new[] { "a", "b", "c", "F" })); WriteLine(MathS.Boolean.BuildTruthTable("a and b implies c", "a", "b", "c")); WriteLine(); // LaTeX WriteLine("x ^ y + sqrt(x) + integral(sqrt(x) / a, x, 1) + derivative(sqrt(x) / a, x, 1) + limit(sqrt(x) / a, x, +oo)".Latexise());
30.898551
131
0.633208
[ "MIT" ]
asc-community/AngouriMath
Sources/Samples/SampleNet5/Program.cs
2,134
C#
using System; using System.Collections.Generic; using System.Text; using Xunit; namespace CnDream.Core.Test { public class UnpackerTests { [Fact] public void SmallPayload() { var unpacker = new DataUnpacker(new IdentityTransformer()); var input = new byte[] { 1, 2, 3, 2, 1, 0, 0, 0, 2, 0, 0, 0, 4, 0, 0, 0, 1, 2, 3, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; var output = new byte[16]; var unpacked = unpacker.UnpackData( new ArraySegment<byte>(output), out var bytesWritten, out var bytesRead, out var pairId, out var serialId, out var payloadSize, new ArraySegment<byte>(input)); Assert.True(unpacked); Assert.Equal(payloadSize, bytesWritten); Assert.Equal(input.Length, bytesRead); Assert.Equal(1, pairId); Assert.Equal(2, serialId); Assert.Equal(4, payloadSize); } [Fact] public void SmallPayloadSliced() { var unpacker = new DataUnpacker(new IdentityTransformer()); var input = new byte[] { 1, 2, 3, 2, 1, 0, 0, 0, 2, 0, 0, 0, 4, 0, 0, 0, 1, 2, 3, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; var output = new byte[16]; var unpacked = false; int bytesWritten, bytesRead, pairId, serialId, payloadSize; for ( int i = 0; i < 4; i++ ) { unpacked = unpacker.UnpackData( new ArraySegment<byte>(output), out bytesWritten, out bytesRead, out pairId, out serialId, out payloadSize, new ArraySegment<byte>(input, i * 4, 4)); Assert.False(unpacked); } unpacked = unpacker.UnpackData( new ArraySegment<byte>(output), out bytesWritten, out bytesRead, out pairId, out serialId, out payloadSize, new ArraySegment<byte>(input, 4 * 4, 16)); Assert.True(unpacked); Assert.Equal(payloadSize, bytesWritten); Assert.Equal(16, bytesRead); Assert.Equal(1, pairId); Assert.Equal(2, serialId); Assert.Equal(4, payloadSize); } } }
29.11236
104
0.464685
[ "MIT" ]
PartysLead/CN_Dream
src/Core.Test/UnpackerTests.cs
2,593
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the fsx-2018-03-01.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml.Serialization; using Amazon.FSx.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.FSx.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for BackupFailureDetails Object /// </summary> public class BackupFailureDetailsUnmarshaller : IUnmarshaller<BackupFailureDetails, XmlUnmarshallerContext>, IUnmarshaller<BackupFailureDetails, JsonUnmarshallerContext> { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> BackupFailureDetails IUnmarshaller<BackupFailureDetails, XmlUnmarshallerContext>.Unmarshall(XmlUnmarshallerContext context) { throw new NotImplementedException(); } /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public BackupFailureDetails Unmarshall(JsonUnmarshallerContext context) { context.Read(); if (context.CurrentTokenType == JsonToken.Null) return null; BackupFailureDetails unmarshalledObject = new BackupFailureDetails(); int targetDepth = context.CurrentDepth; while (context.ReadAtDepth(targetDepth)) { if (context.TestExpression("Message", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.Message = unmarshaller.Unmarshall(context); continue; } } return unmarshalledObject; } private static BackupFailureDetailsUnmarshaller _instance = new BackupFailureDetailsUnmarshaller(); /// <summary> /// Gets the singleton. /// </summary> public static BackupFailureDetailsUnmarshaller Instance { get { return _instance; } } } }
33.98913
173
0.645987
[ "Apache-2.0" ]
ChristopherButtars/aws-sdk-net
sdk/src/Services/FSx/Generated/Model/Internal/MarshallTransformations/BackupFailureDetailsUnmarshaller.cs
3,127
C#
/* Copyright (c) Citrix Systems Inc. * All rights reserved. * * Redistribution and use in source and binary forms, * with or without modification, are permitted provided * that the following conditions are met: * * * Redistributions of source code must retain the above * copyright notice, this list of conditions and the * following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the * following disclaimer in the documentation and/or other * materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ using System.Collections.Generic; using XenAPI; namespace XenAdmin.Actions { public class UpdateIntegratedGpuPassthroughAction : PureAsyncAction { private bool enable; public UpdateIntegratedGpuPassthroughAction(Host host, bool enableOnNextReboot, bool suppressHistory) : base(host.Connection, string.Format(Messages.ACTION_UPDATE_INTEGRATED_GPU_PASSTHROUGH_TITLE, host.Name), null, suppressHistory) { Host = host; enable = enableOnNextReboot; } protected override void Run() { this.Description = Messages.UPDATING_PROPERTIES; RelatedTask = enable ? Host.async_enable_display(Session, Host.opaque_ref) : Host.async_disable_display(Session, Host.opaque_ref); PollToCompletion(0, 50); var pGpu = Host.SystemDisplayDevice; if (pGpu != null) { RelatedTask = enable ? PGPU.async_enable_dom0_access(Session, pGpu.opaque_ref) : PGPU.async_disable_dom0_access(Session, pGpu.opaque_ref); PollToCompletion(50, 100); } PercentComplete = 100; Description = Messages.UPDATED_PROPERTIES; } } }
38.549296
141
0.677749
[ "BSD-2-Clause" ]
cheng-z/xenadmin
XenModel/Actions/Host/UpdateIntegratedGpuPassthroughAction.cs
2,739
C#
#region License, Terms and Conditions // // Jayrock - JSON and JSON-RPC for Microsoft .NET Framework and Mono // Written by Atif Aziz (atif.aziz@skybow.com) // Copyright (c) 2005 Atif Aziz. All rights reserved. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License as published by the Free // Software Foundation; either version 2.1 of the License, or (at your option) // any later version. // // This library is distributed in the hope that it will be useful, but WITHOUT // ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS // FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more // details. // // You should have received a copy of the GNU Lesser General Public License // along with this library; if not, write to the Free Software Foundation, Inc., // 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // #endregion using System; using System.Globalization; namespace Niue.Alipay.Jayrock.Json.Json.Conversion.Converters { #region Imports #endregion public abstract class NumberImporterBase : ImporterBase { protected NumberImporterBase(Type type) : base(type) {} protected override object ImportFromString(ImportContext context, JsonReader reader) { return ImportFromNumber(context, reader); } protected override object ImportFromNumber(ImportContext context, JsonReader reader) { if (context == null) throw new ArgumentNullException("context"); if (reader == null) throw new ArgumentNullException("reader"); string text = reader.Text; try { return ReadReturning(reader, ConvertFromString(text)); } catch (FormatException e) { throw NumberError(e, text); } catch (OverflowException e) { throw NumberError(e, text); } } protected override object ImportFromBoolean(ImportContext context, JsonReader reader) { return Convert.ChangeType(BooleanObject.Box(reader.ReadBoolean()), OutputType); } protected abstract object ConvertFromString(string s); private Exception NumberError(Exception e, string text) { return new JsonException(string.Format("Error importing JSON Number {0} as {1}.", text, OutputType.FullName), e); } } public sealed class ByteImporter : NumberImporterBase { public ByteImporter() : base(typeof(byte)) {} protected override object ConvertFromString(string s) { return Convert.ToByte(s, CultureInfo.InvariantCulture); } } public sealed class Int16Importer : NumberImporterBase { public Int16Importer() : base(typeof(short)) {} protected override object ConvertFromString(string s) { return Convert.ToInt16(s, CultureInfo.InvariantCulture); } } public sealed class Int32Importer : NumberImporterBase { public Int32Importer() : base(typeof(int)) {} protected override object ConvertFromString(string s) { return Convert.ToInt32(s, CultureInfo.InvariantCulture); } } public sealed class Int64Importer : NumberImporterBase { public Int64Importer() : base(typeof(long)) {} protected override object ConvertFromString(string s) { return Convert.ToInt64(s, CultureInfo.InvariantCulture); } } public sealed class SingleImporter : NumberImporterBase { public SingleImporter() : base(typeof(float)) {} protected override object ConvertFromString(string s) { return Convert.ToSingle(s, CultureInfo.InvariantCulture); } } public sealed class DoubleImporter : NumberImporterBase { public DoubleImporter() : base(typeof(double)) {} protected override object ConvertFromString(string s) { return Convert.ToDouble(s, CultureInfo.InvariantCulture); } } public sealed class DecimalImporter : NumberImporterBase { public DecimalImporter() : base(typeof(decimal)) {} protected override object ConvertFromString(string s) { return Convert.ToDecimal(s, CultureInfo.InvariantCulture); } } }
29.707006
125
0.628002
[ "MIT" ]
P79N6A/abp-ant-design-pro-vue
Niue.Alipay/Jayrock/Json/Json/Conversion/Converters/NumberImporter.cs
4,664
C#
// Automatically generated by xdrgen // DO NOT EDIT or your changes may be overwritten namespace stellar_dotnetcore_sdk.xdr { // === xdr source ============================================================ // struct Curve25519Secret // { // opaque key[32]; // }; // =========================================================================== public class Curve25519Secret { public byte[] Key { get; set; } public static void Encode(XdrDataOutputStream stream, Curve25519Secret encodedCurve25519Secret) { var keysize = encodedCurve25519Secret.Key.Length; stream.Write(encodedCurve25519Secret.Key, 0, keysize); } public static Curve25519Secret Decode(XdrDataInputStream stream) { var decodedCurve25519Secret = new Curve25519Secret(); var keysize = 32; decodedCurve25519Secret.Key = new byte[keysize]; stream.Read(decodedCurve25519Secret.Key, 0, keysize); return decodedCurve25519Secret; } } }
32.090909
103
0.558074
[ "Apache-2.0" ]
ammogcoder/dotnet-stellar-sdk
stellar-dotnetcore-sdk/xdr/generated/Curve25519Secret.cs
1,059
C#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Testing; using Test.Utilities; using Xunit; using VerifyCS = Test.Utilities.CSharpSecurityCodeFixVerifier< Microsoft.NetCore.Analyzers.Security.UseDefaultDllImportSearchPathsAttribute, Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>; namespace Microsoft.NetCore.Analyzers.Security.UnitTests { // All the test cases use user32.dll as an example, // however it is a commonly used system dll and will be influenced by Known Dlls mechanism, // which will ignore all the configuration about the search algorithm. // Fow now, this rule didn't take Known Dlls into consideration. // If it is needed in the future, we can recover this rule. public class UseDefaultDllImportSearchPathsAttributeTests { // It will try to retrieve the MessageBox from user32.dll, which will be searched in a default order. [Fact] public async Task Test_DllImportAttribute_Diagnostic() { await VerifyCS.VerifyAnalyzerAsync(@" using System; using System.Runtime.InteropServices; class TestClass { [DllImport(""user32.dll"")] public static extern int MessageBox(IntPtr hWnd, String text, String caption, uint type); public void TestMethod() { MessageBox(new IntPtr(0), ""Hello World!"", ""Hello Dialog"", 0); } }", GetCSharpResultAt(8, 30, UseDefaultDllImportSearchPathsAttribute.UseDefaultDllImportSearchPathsAttributeRule, "MessageBox")); } [Fact] public async Task Test_DllInUpperCase_Diagnostic() { await VerifyCS.VerifyAnalyzerAsync(@" using System; using System.Runtime.InteropServices; class TestClass { [DllImport(""user32.DLL"")] public static extern int MessageBox(IntPtr hWnd, String text, String caption, uint type); public void TestMethod() { MessageBox(new IntPtr(0), ""Hello World!"", ""Hello Dialog"", 0); } }", GetCSharpResultAt(8, 30, UseDefaultDllImportSearchPathsAttribute.UseDefaultDllImportSearchPathsAttributeRule, "MessageBox")); } [Fact] public async Task Test_WithoutDllExtension_Diagnostic() { await VerifyCS.VerifyAnalyzerAsync(@" using System; using System.Runtime.InteropServices; class TestClass { [DllImport(""user32"")] public static extern int MessageBox(IntPtr hWnd, String text, String caption, uint type); public void TestMethod() { MessageBox(new IntPtr(0), ""Hello World!"", ""Hello Dialog"", 0); } }", GetCSharpResultAt(8, 30, UseDefaultDllImportSearchPathsAttribute.UseDefaultDllImportSearchPathsAttributeRule, "MessageBox")); } [Fact] public async Task Test_DllImportSearchPathAssemblyDirectory_Diagnostic() { await VerifyCS.VerifyAnalyzerAsync(@" using System; using System.Runtime.InteropServices; class TestClass { [DllImport(""user32.dll"")] [DefaultDllImportSearchPaths(DllImportSearchPath.AssemblyDirectory)] public static extern int MessageBox(IntPtr hWnd, String text, String caption, uint type); public void TestMethod() { MessageBox(new IntPtr(0), ""Hello World!"", ""Hello Dialog"", 0); } }", GetCSharpResultAt(9, 30, UseDefaultDllImportSearchPathsAttribute.DoNotUseUnsafeDllImportSearchPathRule, "AssemblyDirectory")); } [Fact] public async Task Test_UnsafeDllImportSearchPathBits_BitwiseCombination_OneValueIsBad_Diagnostic() { await VerifyCS.VerifyAnalyzerAsync(@" using System; using System.Runtime.InteropServices; class TestClass { [DllImport(""user32.dll"")] [DefaultDllImportSearchPaths(DllImportSearchPath.AssemblyDirectory | DllImportSearchPath.UserDirectories)] public static extern int MessageBox(IntPtr hWnd, String text, String caption, uint type); public void TestMethod() { MessageBox(new IntPtr(0), ""Hello World!"", ""Hello Dialog"", 0); } }", GetCSharpResultAt(9, 30, UseDefaultDllImportSearchPathsAttribute.DoNotUseUnsafeDllImportSearchPathRule, "AssemblyDirectory")); } [Fact] public async Task Test_UnsafeDllImportSearchPathBits_BitwiseCombination_BothIsBad_Diagnostic() { await VerifyCS.VerifyAnalyzerAsync(@" using System; using System.Runtime.InteropServices; class TestClass { [DllImport(""user32.dll"")] [DefaultDllImportSearchPaths(DllImportSearchPath.AssemblyDirectory | DllImportSearchPath.ApplicationDirectory)] public static extern int MessageBox(IntPtr hWnd, String text, String caption, uint type); public void TestMethod() { MessageBox(new IntPtr(0), ""Hello World!"", ""Hello Dialog"", 0); } }", GetCSharpResultAt(9, 30, UseDefaultDllImportSearchPathsAttribute.DoNotUseUnsafeDllImportSearchPathRule, "AssemblyDirectory, ApplicationDirectory")); } [Fact] public async Task Test_DllImportSearchPathLegacyBehavior_Diagnostic() { await VerifyCS.VerifyAnalyzerAsync(@" using System; using System.Runtime.InteropServices; class TestClass { [DllImport(""user32.dll"")] [DefaultDllImportSearchPaths(DllImportSearchPath.LegacyBehavior)] public static extern int MessageBox(IntPtr hWnd, String text, String caption, uint type); public void TestMethod() { MessageBox(new IntPtr(0), ""Hello World!"", ""Hello Dialog"", 0); } }", GetCSharpResultAt(9, 30, UseDefaultDllImportSearchPathsAttribute.DoNotUseUnsafeDllImportSearchPathRule, "LegacyBehavior")); } [Fact] public async Task Test_DllImportSearchPathUseDllDirectoryForDependencies_Diagnostic() { await VerifyCS.VerifyAnalyzerAsync(@" using System; using System.Runtime.InteropServices; class TestClass { [DllImport(""user32.dll"")] [DefaultDllImportSearchPaths(DllImportSearchPath.UseDllDirectoryForDependencies)] public static extern int MessageBox(IntPtr hWnd, String text, String caption, uint type); public void TestMethod() { MessageBox(new IntPtr(0), ""Hello World!"", ""Hello Dialog"", 0); } }", GetCSharpResultAt(9, 30, UseDefaultDllImportSearchPathsAttribute.DoNotUseUnsafeDllImportSearchPathRule, "UseDllDirectoryForDependencies")); } [Fact] public async Task Test_DllImportSearchPathAssemblyDirectory_Assembly_Diagnostic() { await VerifyCS.VerifyAnalyzerAsync(@" using System; using System.Runtime.InteropServices; [assembly:DefaultDllImportSearchPaths(DllImportSearchPath.AssemblyDirectory)] class TestClass { [DllImport(""user32.dll"")] public static extern int MessageBox(IntPtr hWnd, String text, String caption, uint type); public void TestMethod() { MessageBox(new IntPtr(0), ""Hello World!"", ""Hello Dialog"", 0); } }", GetCSharpResultAt(10, 30, UseDefaultDllImportSearchPathsAttribute.DoNotUseUnsafeDllImportSearchPathRule, "AssemblyDirectory")); } [Fact] public async Task Test_AssemblyDirectory_ApplicationDirectory_Diagnostic() { await VerifyCS.VerifyAnalyzerAsync(@" using System; using System.Runtime.InteropServices; [assembly:DefaultDllImportSearchPaths(DllImportSearchPath.AssemblyDirectory)] class TestClass { [DllImport(""user32.dll"")] [DefaultDllImportSearchPaths(DllImportSearchPath.ApplicationDirectory)] public static extern int MessageBox(IntPtr hWnd, String text, String caption, uint type); public void TestMethod() { MessageBox(new IntPtr(0), ""Hello World!"", ""Hello Dialog"", 0); } }", GetCSharpResultAt(11, 30, UseDefaultDllImportSearchPathsAttribute.DoNotUseUnsafeDllImportSearchPathRule, "ApplicationDirectory")); } [Fact] public async Task Test_ApplicationDirectory_AssemblyDirectory_Diagnostic() { await VerifyCS.VerifyAnalyzerAsync(@" using System; using System.Runtime.InteropServices; [assembly:DefaultDllImportSearchPaths(DllImportSearchPath.ApplicationDirectory)] class TestClass { [DllImport(""user32.dll"")] [DefaultDllImportSearchPaths(DllImportSearchPath.AssemblyDirectory)] public static extern int MessageBox(IntPtr hWnd, String text, String caption, uint type); public void TestMethod() { MessageBox(new IntPtr(0), ""Hello World!"", ""Hello Dialog"", 0); } }", GetCSharpResultAt(11, 30, UseDefaultDllImportSearchPathsAttribute.DoNotUseUnsafeDllImportSearchPathRule, "AssemblyDirectory")); } [Theory] [InlineData("")] [InlineData("dotnet_code_quality.CA5393.unsafe_DllImportSearchPath_bits = 2 | 256 | 512")] [InlineData("dotnet_code_quality.CA5393.unsafe_DllImportSearchPath_bits = 770")] public async Task EditorConfigConfiguration_UnsafeDllImportSearchPathBits_DefaultValue_Diagnostic(string editorConfigText) { await new VerifyCS.Test { TestState = { Sources = { @" using System; using System.Runtime.InteropServices; class TestClass { [DllImport(""user32.dll"")] [DefaultDllImportSearchPaths(DllImportSearchPath.AssemblyDirectory | DllImportSearchPath.ApplicationDirectory)] public static extern int MessageBox(IntPtr hWnd, String text, String caption, uint type); public void TestMethod() { MessageBox(new IntPtr(0), ""Hello World!"", ""Hello Dialog"", 0); } }" }, ExpectedDiagnostics = { GetCSharpResultAt(9, 30, UseDefaultDllImportSearchPathsAttribute.DoNotUseUnsafeDllImportSearchPathRule, "AssemblyDirectory, ApplicationDirectory"), }, AnalyzerConfigFiles = { ("/.editorconfig", $@"root = true [*] {editorConfigText} ") } }, }.RunAsync(); } [Theory] [InlineData("dotnet_code_quality.CA5393.unsafe_DllImportSearchPath_bits = 2048")] public async Task EditorConfigConfiguration_UnsafeDllImportSearchPathBits_NonDefaultValue_Diagnostic(string editorConfigText) { await new VerifyCS.Test { TestState = { Sources = { @" using System; using System.Runtime.InteropServices; class TestClass { [DllImport(""user32.dll"")] [DefaultDllImportSearchPaths(DllImportSearchPath.System32)] public static extern int MessageBox(IntPtr hWnd, String text, String caption, uint type); public void TestMethod() { MessageBox(new IntPtr(0), ""Hello World!"", ""Hello Dialog"", 0); } }" }, ExpectedDiagnostics = { GetCSharpResultAt(9, 30, UseDefaultDllImportSearchPathsAttribute.DoNotUseUnsafeDllImportSearchPathRule, "System32"), }, AnalyzerConfigFiles = { ("/.editorconfig", $@"root = true [*] {editorConfigText} ") } }, }.RunAsync(); } [Theory] [InlineData("dotnet_code_quality.CA5393.unsafe_DllImportSearchPath_bits = 1026")] public async Task EditorConfigConfiguration_UnsafeDllImportSearchPathBits_BitwiseCombination_Diagnostic(string editorConfigText) { await new VerifyCS.Test { TestState = { Sources = { @" using System; using System.Runtime.InteropServices; class TestClass { [DllImport(""user32.dll"")] [DefaultDllImportSearchPaths(DllImportSearchPath.UserDirectories)] public static extern int MessageBox(IntPtr hWnd, String text, String caption, uint type); public void TestMethod() { MessageBox(new IntPtr(0), ""Hello World!"", ""Hello Dialog"", 0); } }" }, ExpectedDiagnostics = { GetCSharpResultAt(9, 30, UseDefaultDllImportSearchPathsAttribute.DoNotUseUnsafeDllImportSearchPathRule, "UserDirectories"), }, AnalyzerConfigFiles = { ("/.editorconfig", $@"root = true [*] {editorConfigText} ") } }, }.RunAsync(); } [Fact] public async Task Test_NoAttribute_NoDiagnostic() { await VerifyCS.VerifyAnalyzerAsync(@" using System; using System.Runtime.InteropServices; class TestClass { public static extern int MessageBox(IntPtr hWnd, String text, String caption, uint type); public void TestMethod() { MessageBox(new IntPtr(0), ""Hello World!"", ""Hello Dialog"", 0); } }"); } // user32.dll will be searched in UserDirectories, which is specified by DllImportSearchPath and is good. [Fact] public async Task Test_DllImportAndDefaultDllImportSearchPathsAttributes_NoDiagnostic() { await VerifyCS.VerifyAnalyzerAsync(@" using System; using System.Runtime.InteropServices; class TestClass { [DllImport(""user32.dll"")] [DefaultDllImportSearchPaths(DllImportSearchPath.UserDirectories)] public static extern int MessageBox(IntPtr hWnd, String text, String caption, uint type); public void TestMethod() { MessageBox(new IntPtr(0), ""Hello World!"", ""Hello Dialog"", 0); } }"); } [Theory] [InlineData("dotnet_code_quality.CA5392.unsafe_DllImportSearchPath_bits = 2 | 1024")] [InlineData("dotnet_code_quality.CA5392.unsafe_DllImportSearchPath_bits = DllImportSearchPath.AssemblyDirectory | DllImportSearchPath.UserDirectories")] public async Task EditorConfigConfiguration_UnsafeDllImportSearchPathBits_BitwiseCombination_NoDiagnostic(string editorConfigText) { await new VerifyCS.Test { TestState = { Sources = { @" using System; using System.Runtime.InteropServices; class TestClass { [DllImport(""user32.dll"")] [DefaultDllImportSearchPaths(DllImportSearchPath.UserDirectories)] public static extern int MessageBox(IntPtr hWnd, String text, String caption, uint type); public void TestMethod() { MessageBox(new IntPtr(0), ""Hello World!"", ""Hello Dialog"", 0); } }" }, AnalyzerConfigFiles = { ("/.editorconfig", $@"root = true [*] {editorConfigText} ") } }, }.RunAsync(); } [Theory] [InlineData("dotnet_code_quality.CA5393.unsafe_DllImportSearchPath_bits = 2048")] public async Task EditorConfigConfiguration_UnsafeDllImportSearchPathBits_NonDefaultValue_NoDiagnostic(string editorConfigText) { await new VerifyCS.Test { TestState = { Sources = { @" using System; using System.Runtime.InteropServices; class TestClass { [DllImport(""user32.dll"")] [DefaultDllImportSearchPaths(DllImportSearchPath.AssemblyDirectory | DllImportSearchPath.ApplicationDirectory)] public static extern int MessageBox(IntPtr hWnd, String text, String caption, uint type); public void TestMethod() { MessageBox(new IntPtr(0), ""Hello World!"", ""Hello Dialog"", 0); } }" }, AnalyzerConfigFiles = { ("/.editorconfig", $@"root = true [*] {editorConfigText} ") } }, }.RunAsync(); } // In this case, [DefaultDllImportSearchPaths] is applied to the assembly. // So, this attribute specifies the paths that are used by default to search for any DLL that provides a function for a platform invoke, in any code in the assembly. [Fact] public async Task Test_DllImportAndAssemblyDefaultDllImportSearchPathsAttributes_NoDiagnostic() { await VerifyCS.VerifyAnalyzerAsync(@" using System; using System.Runtime.InteropServices; [assembly:DefaultDllImportSearchPaths(DllImportSearchPath.UserDirectories)] class TestClass { [DllImport(""user32.dll"")] public static extern int MessageBox(IntPtr hWnd, String text, String caption, uint type); public void TestMethod() { MessageBox(new IntPtr(0), ""Hello World!"", ""Hello Dialog"", 0); } }"); } // It will have a compiler warning and recommend to use [DllImport] also. [Fact] public async Task Test_DefaultDllImportSearchPaths_NoDiagnostic() { await VerifyCS.VerifyAnalyzerAsync(@" using System; using System.Runtime.InteropServices; class TestClass { [DefaultDllImportSearchPaths(DllImportSearchPath.UserDirectories)] public static extern int MessageBox(IntPtr hWnd, String text, String caption, uint type); public void TestMethod() { } }"); } // It will have a compiler warning and recommend to use [DllImport] also. [Fact] public async Task Test_AssemblyDefaultDllImportSearchPaths_NoDiagnostic() { await VerifyCS.VerifyAnalyzerAsync(@" using System; using System.Runtime.InteropServices; [assembly:DefaultDllImportSearchPaths(DllImportSearchPath.UserDirectories)] class TestClass { public static extern int MessageBox(IntPtr hWnd, String text, String caption, uint type); public void TestMethod() { } }"); } // [DllImport] is set with an absolute path, which will let the [DefaultDllImportSearchPaths] be ignored. [WindowsOnlyFact] public async Task Test_DllImportAttributeWithAbsolutePath_DefaultDllImportSearchPaths_NoDiagnostic() { await VerifyCS.VerifyAnalyzerAsync(@" using System; using System.Runtime.InteropServices; class TestClass { [DllImport(""C:\\Windows\\System32\\user32.dll"")] [DefaultDllImportSearchPaths(DllImportSearchPath.UserDirectories)] public static extern int MessageBox(IntPtr hWnd, String text, String caption, uint type); public void TestMethod() { MessageBox(new IntPtr(0), ""Hello World!"", ""Hello Dialog"", 0); } }"); } // [DllImport] is set with an absolute path. [WindowsOnlyFact] public async Task Test_DllImportAttributeWithAbsolutePath_NoDiagnostic() { await VerifyCS.VerifyAnalyzerAsync(@" using System; using System.Runtime.InteropServices; class TestClass { [DllImport(""C:\\Windows\\System32\\user32.dll"")] public static extern int MessageBox(IntPtr hWnd, String text, String caption, uint type); public void TestMethod() { MessageBox(new IntPtr(0), ""Hello World!"", ""Hello Dialog"", 0); } }"); } [WindowsOnlyFact] public async Task Test_UsingNonexistentAbsolutePath_NoDiagnostic() { await VerifyCS.VerifyAnalyzerAsync(@" using System; using System.Runtime.InteropServices; class TestClass { [DllImport(""C:\\Nonexistent\\user32.dll"")] [DefaultDllImportSearchPaths(DllImportSearchPath.UserDirectories)] public static extern int MessageBox(IntPtr hWnd, String text, String caption, uint type); public void TestMethod() { MessageBox(new IntPtr(0), ""Hello World!"", ""Hello Dialog"", 0); } }"); } private static DiagnosticResult GetCSharpResultAt(int line, int column, DiagnosticDescriptor rule, params string[] arguments) #pragma warning disable RS0030 // Do not used banned APIs => VerifyCS.Diagnostic(rule) .WithLocation(line, column) #pragma warning restore RS0030 // Do not used banned APIs .WithArguments(arguments); } }
32.865041
173
0.666931
[ "Apache-2.0" ]
AndrewZu1337/roslyn-analyzers
src/NetAnalyzers/UnitTests/Microsoft.NetCore.Analyzers/Security/UseDefaultDllImportSearchPathsAttributeTests.cs
20,214
C#
using System; using System.Collections.Generic; using Abp.Authorization.Users; using Abp.Extensions; namespace template.Authorization.Users { public class User : AbpUser<User> { public const string DefaultPassword = "123qwe"; public static string CreateRandomPassword() { return Guid.NewGuid().ToString("N").Truncate(16); } public static User CreateTenantAdminUser(int tenantId, string emailAddress) { var user = new User { TenantId = tenantId, UserName = AdminUserName, Name = AdminUserName, Surname = AdminUserName, EmailAddress = emailAddress, Roles = new List<UserRole>() }; user.SetNormalizedNames(); return user; } } }
24.771429
83
0.561707
[ "MIT" ]
mirusky/identity-abp
src/template.Core/Authorization/Users/User.cs
869
C#
using System; using System.Threading.Tasks; using CloudKit; using ObjCRuntime; namespace Foundation { #if MONOMAC || IOS public partial class NSItemProvider { #if !NET && MONOMAC [Obsolete ("Use RegisterCloudKitShare (CloudKitRegistrationPreparationAction) instead.")] public virtual void RegisterCloudKitShare (Action<CloudKitRegistrationPreparationHandler> preparationHandler) { CloudKitRegistrationPreparationAction action = handler => preparationHandler (handler); RegisterCloudKitShare (action); } #endif #if MONOMAC public virtual Task<CloudKitRegistrationPreparationHandler> RegisterCloudKitShareAsync () { var tcs = new TaskCompletionSource<CloudKitRegistrationPreparationHandler> (); CloudKitRegistrationPreparationAction action = (handler) => { tcs.SetResult (handler); }; RegisterCloudKitShare (action); return tcs.Task; } #endif #if NET [SupportedOSPlatform ("tvos11.0")] [SupportedOSPlatform ("macos10.13")] [SupportedOSPlatform ("ios11.0")] #else [Watch (4,0)] [TV (11,0)] [Mac (10,13)] [iOS (11,0)] #endif public NSProgress LoadObject<T> (Action<T, NSError> completionHandler) where T: NSObject, INSItemProviderReading { return LoadObject (new Class (typeof (T)), (rv, err) => { var obj = rv as T; if (obj == null && rv != null) obj = Runtime.ConstructNSObject<T> (rv.Handle); completionHandler (obj, err); }); } #if NET [SupportedOSPlatform ("tvos11.0")] [SupportedOSPlatform ("macos10.13")] [SupportedOSPlatform ("ios11.0")] #else [Watch (4,0)] [TV (11,0)] [Mac (10,13)] [iOS (11,0)] #endif public Task<T> LoadObjectAsync<T> () where T: NSObject, INSItemProviderReading { var rv = LoadObjectAsync (new Class (typeof (T))); return rv.ContinueWith ((v) => { var obj = v.Result as T; if (obj == null && v.Result != null) obj = Runtime.ConstructNSObject<T> (v.Result.Handle); return obj; }); } #if NET [SupportedOSPlatform ("tvos11.0")] [SupportedOSPlatform ("macos10.13")] [SupportedOSPlatform ("ios11.0")] #else [Watch (4,0)] [TV (11,0)] [Mac (10,13)] [iOS (11,0)] #endif public Task<T> LoadObjectAsync<T> (out NSProgress result) where T: NSObject, INSItemProviderReading { var rv = LoadObjectAsync (new Class (typeof (T)), out result); return rv.ContinueWith ((v) => { var obj = v.Result as T; if (obj == null && v.Result != null) obj = Runtime.ConstructNSObject<T> (v.Result.Handle); return obj; }); } } #endif // MONOMAC || IOS }
25.676768
114
0.675059
[ "BSD-3-Clause" ]
SotoiGhost/xamarin-macios
src/Foundation/NSItemProvider.cs
2,542
C#
using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Newtonsoft.Json.Serialization; using Oxide.Core; using System; using System.Collections.Generic; using System.Linq; using static TechTreeData; namespace Oxide.Plugins { [Info("Tech Tree Control", "WhiteThunder", "0.2.0")] [Description("Allows customizing Tech Tree research requirements.")] internal class TechTreeControl : CovalencePlugin { #region Fields private static TechTreeControl _pluginInstance; private static Configuration _pluginConfig; private const string PermissionAnyOrderLevel1 = "techtreecontrol.anyorder.level1"; private const string PermissionAnyOrderLevel2 = "techtreecontrol.anyorder.level2"; private const string PermissionAnyOrderLevel3 = "techtreecontrol.anyorder.level3"; private const string PermissionRulesetFormat = "techtreecontrol.ruleset.{0}"; #endregion #region Hooks private void Init() { _pluginInstance = this; permission.RegisterPermission(PermissionAnyOrderLevel1, this); permission.RegisterPermission(PermissionAnyOrderLevel2, this); permission.RegisterPermission(PermissionAnyOrderLevel3, this); foreach (var ruleset in _pluginConfig.BlueprintRulesets) { if (!string.IsNullOrEmpty(ruleset.Name)) permission.RegisterPermission(GetRulesetPermission(ruleset.Name), this); } } private void Unload() { _pluginInstance = null; _pluginConfig = null; } private bool? CanUnlockTechTreeNode(BasePlayer player, NodeInstance node, TechTreeData techTree) { var blueprintRuleset = _pluginConfig.GetPlayerBlueprintRuleset(player.UserIDString); if (blueprintRuleset == null) return null; if (node.itemDef != null && !blueprintRuleset.IsAllowed(node.itemDef)) return false; return null; } private bool? CanUnlockTechTreeNodePath(BasePlayer player, NodeInstance node, TechTreeData techTree) { if (HasPermissionToUnlockAny(player, techTree)) return true; var blueprintRuleset = _pluginConfig.GetPlayerBlueprintRuleset(player.UserIDString); if (blueprintRuleset == null) return null; if (node.itemDef != null && !blueprintRuleset.HasPrerequisites(node.itemDef)) return true; if (HasUnlockPath(player, node, techTree, blueprintRuleset)) return true; return null; } private int? OnResearchCostDetermine(ItemDefinition itemDefinition) { return _pluginConfig.GetResearchCostOverride(itemDefinition); } #endregion #region Helper Methods private static bool TechTreeNodeUnlockWasBlocked(Drone drone, BasePlayer deployer) { object hookResult = Interface.CallHook("OnTechTreeNodeForceUnlock", drone, deployer); return hookResult is bool && (bool)hookResult == false; } private static bool HasUnlockPath(BasePlayer player, NodeInstance node, TechTreeData techTree, BlueprintRuleset blueprintRuleset) { if (node.inputs.Count == 0) return true; var hasUnlockPath = false; foreach (var inputNodeId in node.inputs) { var inputNode = techTree.GetByID(inputNodeId); if (inputNode.itemDef == null) { // This input node appears to be an entry node, so consider it unlocked. return true; } if (!techTree.HasPlayerUnlocked(player, inputNode) && !blueprintRuleset.IsOptional(inputNode.itemDef)) { // This input node does not provide an unlock path. // Continue iterating the other input nodes in case they provide an unlock path. continue; } if (HasUnlockPath(player, inputNode, techTree, blueprintRuleset)) hasUnlockPath = true; } return hasUnlockPath; } private static bool HasPermissionToUnlockAny(BasePlayer player, TechTreeData techTree) { if (techTree.name == "TechTreeT3") return _pluginInstance.permission.UserHasPermission(player.UserIDString, PermissionAnyOrderLevel3); if (techTree.name == "TechTreeT2") return _pluginInstance.permission.UserHasPermission(player.UserIDString, PermissionAnyOrderLevel2); else if (techTree.name == "TechTreeT0") return _pluginInstance.permission.UserHasPermission(player.UserIDString, PermissionAnyOrderLevel1); return false; } private static string GetRulesetPermission(string name) => String.Format(PermissionRulesetFormat, name); #endregion #region Configuration private class Configuration : SerializableConfiguration { [JsonProperty("ResearchCosts")] public Dictionary<string, int> ResearchCosts = new Dictionary<string, int>(); [JsonProperty("BlueprintRulesets")] public BlueprintRuleset[] BlueprintRulesets = new BlueprintRuleset[0]; public int? GetResearchCostOverride(ItemDefinition itemDefinition) { foreach (var entry in _pluginConfig.ResearchCosts) { if (entry.Key == itemDefinition.shortname) return entry.Value; } return null; } public BlueprintRuleset GetPlayerBlueprintRuleset(string userIdString) { var blueprintRulesets = BlueprintRulesets; if (blueprintRulesets == null) return null; for (var i = blueprintRulesets.Length - 1; i >= 0; i--) { var ruleset = blueprintRulesets[i]; if (!string.IsNullOrEmpty(ruleset.Name) && _pluginInstance.permission.UserHasPermission(userIdString, GetRulesetPermission(ruleset.Name))) return ruleset; } return BlueprintRuleset.DefaultRuleset; } } private class BlueprintRuleset { public static BlueprintRuleset DefaultRuleset = new BlueprintRuleset(); [JsonProperty("Name")] public string Name; [JsonProperty("OptionalBlueprints")] public HashSet<string> OptionalBlueprints = new HashSet<string>(); [JsonProperty("AllowedBlueprints", DefaultValueHandling = DefaultValueHandling.Ignore)] public HashSet<string> AllowedBlueprints; [JsonProperty("DisallowedBlueprints", DefaultValueHandling = DefaultValueHandling.Ignore)] public HashSet<string> DisallowedBlueprints; [JsonProperty("BlueprintsWithNoPrerequisites")] public HashSet<string> BlueprintsWithNoPrerequisites = new HashSet<string>(); public bool HasPrerequisites(ItemDefinition itemDefinition) => !BlueprintsWithNoPrerequisites.Contains(itemDefinition.shortname); public bool IsAllowed(ItemDefinition itemDefinition) { if (AllowedBlueprints != null) return AllowedBlueprints.Contains(itemDefinition.shortname); if (DisallowedBlueprints != null) return !DisallowedBlueprints.Contains(itemDefinition.shortname); return true; } public bool IsOptional(ItemDefinition itemDefinition) => OptionalBlueprints.Contains(itemDefinition.shortname); } private Configuration GetDefaultConfig() => new Configuration(); #endregion #region Configuration Boilerplate private class SerializableConfiguration { public string ToJson() => JsonConvert.SerializeObject(this); public Dictionary<string, object> ToDictionary() => JsonHelper.Deserialize(ToJson()) as Dictionary<string, object>; } private static class JsonHelper { public static object Deserialize(string json) => ToObject(JToken.Parse(json)); private static object ToObject(JToken token) { switch (token.Type) { case JTokenType.Object: return token.Children<JProperty>() .ToDictionary(prop => prop.Name, prop => ToObject(prop.Value)); case JTokenType.Array: return token.Select(ToObject).ToList(); default: return ((JValue)token).Value; } } } private bool MaybeUpdateConfig(SerializableConfiguration config) { var currentWithDefaults = config.ToDictionary(); var currentRaw = Config.ToDictionary(x => x.Key, x => x.Value); return MaybeUpdateConfigDict(currentWithDefaults, currentRaw); } private bool MaybeUpdateConfigDict(Dictionary<string, object> currentWithDefaults, Dictionary<string, object> currentRaw) { bool changed = false; foreach (var key in currentWithDefaults.Keys) { object currentRawValue; if (currentRaw.TryGetValue(key, out currentRawValue)) { var defaultDictValue = currentWithDefaults[key] as Dictionary<string, object>; var currentDictValue = currentRawValue as Dictionary<string, object>; if (defaultDictValue != null) { if (currentDictValue == null) { currentRaw[key] = currentWithDefaults[key]; changed = true; } else if (MaybeUpdateConfigDict(defaultDictValue, currentDictValue)) changed = true; } } else { currentRaw[key] = currentWithDefaults[key]; changed = true; } } return changed; } protected override void LoadDefaultConfig() => _pluginConfig = GetDefaultConfig(); protected override void LoadConfig() { base.LoadConfig(); try { _pluginConfig = Config.ReadObject<Configuration>(); if (_pluginConfig == null) { throw new JsonException(); } if (MaybeUpdateConfig(_pluginConfig)) { LogWarning("Configuration appears to be outdated; updating and saving"); SaveConfig(); } } catch { LogWarning($"Configuration file {Name}.json is invalid; using defaults"); LoadDefaultConfig(); } } protected override void SaveConfig() { Log($"Configuration changes saved to {Name}.json"); Config.WriteObject(_pluginConfig, true); } #endregion } }
35.854103
137
0.576212
[ "MIT" ]
WheteThunger/TechTreeControl
TechTreeControl.cs
11,798
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace HackTest.Properties { /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if ((resourceMan == null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("HackTest.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } } }
33.680556
159
0.68866
[ "MIT" ]
kobush/Toolkit
Source/Samples/HackTest/Properties/Resources.Designer.cs
2,427
C#
using System; using System.Xml.Serialization; namespace Niue.Alipay.Domain { /// <summary> /// KbAdvertChannelResponse Data Structure. /// </summary> [Serializable] public class KbAdvertChannelResponse : AopObject { /// <summary> /// 渠道ID /// </summary> [XmlElement("channel_id")] public string ChannelId { get; set; } /// <summary> /// 备注 /// </summary> [XmlElement("memo")] public string Memo { get; set; } /// <summary> /// 渠道名称 /// </summary> [XmlElement("name")] public string Name { get; set; } /// <summary> /// 渠道状态 EFFECTIVE:有效 INVALID:无效 /// </summary> [XmlElement("status")] public string Status { get; set; } /// <summary> /// OFFLINE:线下推广 /// </summary> [XmlElement("type")] public string Type { get; set; } } }
22.348837
52
0.497399
[ "MIT" ]
P79N6A/abp-ant-design-pro-vue
Niue.Alipay/Domain/KbAdvertChannelResponse.cs
1,009
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace BTCPayServer.Models.AppViewModels { public class ViewPointOfSaleViewModel { public class Item { public class ItemPrice { public string Formatted { get; set; } public decimal Value { get; set; } } public string Description { get; set; } public string Id { get; set; } public string Image { get; set; } public ItemPrice Price { get; set; } public string Title { get; set; } public bool Custom { get; set; } } public bool ShowCustomAmount { get; set; } public string Step { get; set; } public string Title { get; set; } public Item[] Items { get; set; } public string CurrencySymbol { get; set; } public string ButtonText { get; set; } public string CustomButtonText { get; set; } public string CustomCSSLink { get; set; } } }
29.081081
53
0.564126
[ "MIT" ]
Deimoscoin/btcpayserver
BTCPayServer/Models/AppViewModels/ViewPointOfSaleViewModel.cs
1,078
C#
namespace RealPollSignalR.Migrations { using System; using System.Data.Entity.Migrations; public partial class Start : DbMigration { public override void Up() { CreateTable( "dbo.Answers", c => new { Id = c.Int(nullable: false, identity: true), QuestionId = c.Int(nullable: false), AnswerText = c.String(), IsCorrect = c.Boolean(nullable: false), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Questions", t => t.QuestionId, cascadeDelete: true) .Index(t => t.QuestionId); CreateTable( "dbo.Questions", c => new { Id = c.Int(nullable: false, identity: true), QuestionText = c.String(), AdminHash = c.Int(nullable: false), DisplayHash = c.Int(nullable: false), }) .PrimaryKey(t => t.Id); } public override void Down() { DropForeignKey("dbo.Answers", "QuestionId", "dbo.Questions"); DropIndex("dbo.Answers", new[] { "QuestionId" }); DropTable("dbo.Questions"); DropTable("dbo.Answers"); } } }
32.6
84
0.427403
[ "MIT" ]
rlbisbe/RealPollSignalR
RealPollSignalR/Migrations/201402232204183_Start.cs
1,467
C#
/* SPDX-License-Identifier: Apache-2.0 * * The OpenSearch Contributors require contributions made to * this file be licensed under the Apache-2.0 license or a * compatible open source license. * * Modifications Copyright OpenSearch Contributors. See * GitHub history for details. * * Licensed to Elasticsearch B.V. under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch B.V. licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ using Osc; namespace Tests.Mapping.Types.Specialized.TokenCount { public class TokenCountTest { [TokenCount( Index = false, Analyzer = "standard", EnablePositionIncrements = false, NullValue = 0)] public int Full { get; set; } [TokenCount] public int Minimal { get; set; } } public class TokenCountAttributeTests : AttributeTestsBase<TokenCountTest> { protected override object ExpectJson => new { properties = new { full = new { type = "token_count", analyzer = "standard", enable_position_increments = false, index = false, null_value = 0.0, }, minimal = new { type = "token_count" } } }; } }
26.358209
75
0.713477
[ "Apache-2.0" ]
Bit-Quill/opensearch-net
tests/Tests/Mapping/Types/Specialized/TokenCount/TokenCountAttributeTests.cs
1,766
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Sum Adjacent Equal Numbers")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Sum Adjacent Equal Numbers")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("0d16f64f-48a9-44f6-93fe-e49d85718212")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.513514
84
0.745965
[ "MIT" ]
BlueDress/School
Programming Fundamentals C#/Lists/Sum Adjacent Equal Numbers/Properties/AssemblyInfo.cs
1,428
C#
// //#if CSHARP_7_OR_LATER || (UNITY_2018_3_OR_NEWER && (NET_STANDARD_2_0 || NET_4_6)) //#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member // //using System.Collections.Generic; //using System.Threading; //using UnityEngine; //using UnityEngine.EventSystems; // //namespace UniRx.Async.Triggers //{ // [DisallowMultipleComponent] // public class AsyncJointTrigger : AsyncTriggerBase // { // AsyncTriggerPromise<float> onJointBreak; // AsyncTriggerPromiseDictionary<float> onJointBreaks; // AsyncTriggerPromise<Joint2D> onJointBreak2D; // AsyncTriggerPromiseDictionary<Joint2D> onJointBreak2Ds; // // // protected override IEnumerable<ICancelablePromise> GetPromises() // { // return Concat(onJointBreak, onJointBreaks, onJointBreak2D, onJointBreak2Ds); // } // // // void OnJointBreak(float breakForce) // { // TrySetResult(onJointBreak, onJointBreaks, breakForce); // } // // // public UniTask OnJointBreakAsync(CancellationToken cancellationToken = default(CancellationToken)) // { // return GetOrAddPromise(ref onJointBreak, ref onJointBreaks, cancellationToken); // } // // // void OnJointBreak2D(Joint2D brokenJoint) // { // TrySetResult(onJointBreak2D, onJointBreak2Ds, brokenJoint); // } // // // public UniTask OnJointBreak2DAsync(CancellationToken cancellationToken = default(CancellationToken)) // { // return GetOrAddPromise(ref onJointBreak2D, ref onJointBreak2Ds, cancellationToken); // } // // // } //} // //#endif //
29.857143
110
0.66567
[ "MIT" ]
MaxShwachko/unirxrealis
Assets/Runtime/Async/Triggers/AsyncJointTrigger.cs
1,672
C#
using System.Linq; using System.Threading; using FlaUI.Core.AutomationElements.PatternElements; using FlaUI.Core.Definitions; namespace FlaUI.Core.AutomationElements { /// <summary> /// Class to interact with a menu item element. /// </summary> public class MenuItem : AutomationElement { private readonly InvokeAutomationElement _invokeAutomationElement; private readonly ExpandCollapseAutomationElement _expandCollapseAutomationElement; private readonly ToggleAutomationElement _toggleAutomationElement; /// <summary> /// Creates a <see cref="MenuItem"/> element. /// </summary> public MenuItem(FrameworkAutomationElementBase frameworkAutomationElement) : base(frameworkAutomationElement) { _invokeAutomationElement = new InvokeAutomationElement(frameworkAutomationElement); _expandCollapseAutomationElement = new ExpandCollapseAutomationElement(frameworkAutomationElement); _toggleAutomationElement = new ToggleAutomationElement(frameworkAutomationElement); } /// <summary> /// Flag to indicate if the containing menu is a Win32 menu because that one needs special handling /// </summary> internal bool IsWin32Menu { get; set; } /// <summary> /// Gets the text of the element. /// </summary> public string Text => Properties.Name.Value; /// <summary> /// Gets all <see cref="MenuItem"/> which are inside this element. /// </summary> public MenuItems Items { get { // Special handling for Win32 context menus if (IsWin32Menu) { // Click the item to load the child items Click(); // In Win32, the nested menu items are below a menu control which is below the application window // So search the app window first var appWindow = FrameworkAutomationElement.Automation.GetDesktop().FindFirstChild(cf => cf.ByControlType(ControlType.Window).And(cf.ByProcessId(Properties.ProcessId))); // Then search the menu below the window var menu = appWindow.FindFirstChild(cf => cf.ByControlType(ControlType.Menu).And(cf.ByName(Text))).AsMenu(); menu.IsWin32Menu = true; // Now return the menu items return menu.Items; } // Expand if needed, WinForms does not have the expand pattern but all children are already visible so it works as well if (Patterns.ExpandCollapse.IsSupported) { ExpandCollapseState state; do { state = _expandCollapseAutomationElement.ExpandCollapseState; if (state == ExpandCollapseState.Collapsed) { Expand(); } Thread.Sleep(50); } while (state != ExpandCollapseState.Expanded); } var childItems = FindAllChildren(cf => cf.ByControlType(ControlType.MenuItem)).Select(e => e.AsMenuItem()); return new MenuItems(childItems); } } /// <summary> /// Invokes the element. /// </summary> public MenuItem Invoke() { _invokeAutomationElement.Invoke(); return this; } /// <summary> /// Expands the element. /// </summary> public MenuItem Expand() { _expandCollapseAutomationElement.Expand(); return this; } /// <summary> /// Collapses the element. /// </summary> public MenuItem Collapse() { _expandCollapseAutomationElement.Collapse(); return this; } /// <summary> /// Gets or sets if a menu item is checked or unchecked, if checking is supported. /// For some applications, like WPF, setting this property doesn't execute the action that happens when a user clicks the menu item, only the checked state is changed. /// For WPF and Windows Forms applications, if you want to execute the action too, you need to use Invoke() method. /// </summary> public bool? IsChecked { get { if (FrameworkType == FrameworkType.Win32) { if (Patterns.Toggle.IsSupported) { return _toggleAutomationElement.IsToggled; } else { // Toggle pattern is supported only for checked menu items. This strange behaviour happens only for Win32 applications. // Toggle pattern is not present on menu items that support checking but are unchecked. // Menu items that doesn't support Toggle pattern are considered unchecked. return false; } } else { // WinForms doesn't support Toggle pattern at all. WPF fully supports Toggle pattern. return _toggleAutomationElement.IsToggled; } } set { if (FrameworkType == FrameworkType.Win32) { if (Patterns.Toggle.IsSupported) { _toggleAutomationElement.IsToggled = value; } else { // here the menu item is unchecked because Toggle pattern is not supported if (value == true) { _invokeAutomationElement.Invoke(); } } } else { _toggleAutomationElement.IsToggled = value; } } } } }
39.78481
188
0.527999
[ "MIT" ]
ChrisZhang95/FlaUI
src/FlaUI.Core/AutomationElements/MenuItem.cs
6,288
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // ------------------------------------------------------------------------------ // Changes to this file must follow the https://aka.ms/api-review process. // ------------------------------------------------------------------------------ namespace System { public sealed partial class LocalDataStoreSlot { internal LocalDataStoreSlot() { } ~LocalDataStoreSlot() { } } } namespace System.Threading { public enum ApartmentState { STA = 0, MTA = 1, Unknown = 2, } public sealed partial class CompressedStack : System.Runtime.Serialization.ISerializable { internal CompressedStack() { } public static System.Threading.CompressedStack Capture() { throw null; } public System.Threading.CompressedStack CreateCopy() { throw null; } public static System.Threading.CompressedStack GetCompressedStack() { throw null; } public void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public static void Run(System.Threading.CompressedStack compressedStack, System.Threading.ContextCallback callback, object? state) { } } public delegate void ParameterizedThreadStart(object? obj); public sealed partial class Thread : System.Runtime.ConstrainedExecution.CriticalFinalizerObject { public Thread(System.Threading.ParameterizedThreadStart start) { } public Thread(System.Threading.ParameterizedThreadStart start, int maxStackSize) { } public Thread(System.Threading.ThreadStart start) { } public Thread(System.Threading.ThreadStart start, int maxStackSize) { } [System.ObsoleteAttribute("The ApartmentState property has been deprecated. Use GetApartmentState, SetApartmentState or TrySetApartmentState instead.", false)] public System.Threading.ApartmentState ApartmentState { get { throw null; } set { } } public System.Globalization.CultureInfo CurrentCulture { get { throw null; } set { } } public static System.Security.Principal.IPrincipal? CurrentPrincipal { get { throw null; } set { } } public static System.Threading.Thread CurrentThread { get { throw null; } } public System.Globalization.CultureInfo CurrentUICulture { get { throw null; } set { } } public System.Threading.ExecutionContext? ExecutionContext { get { throw null; } } public bool IsAlive { get { throw null; } } public bool IsBackground { get { throw null; } set { } } public bool IsThreadPoolThread { get { throw null; } } public int ManagedThreadId { get { throw null; } } public string? Name { get { throw null; } set { } } public System.Threading.ThreadPriority Priority { get { throw null; } set { } } public System.Threading.ThreadState ThreadState { get { throw null; } } [System.ObsoleteAttribute("Thread.Abort is not supported and throws PlatformNotSupportedException.", DiagnosticId = "SYSLIB0006", UrlFormat = "https://aka.ms/dotnet-warnings/{0}")] public void Abort() { } [System.ObsoleteAttribute("Thread.Abort is not supported and throws PlatformNotSupportedException.", DiagnosticId = "SYSLIB0006", UrlFormat = "https://aka.ms/dotnet-warnings/{0}")] public void Abort(object? stateInfo) { } public static System.LocalDataStoreSlot AllocateDataSlot() { throw null; } public static System.LocalDataStoreSlot AllocateNamedDataSlot(string name) { throw null; } public static void BeginCriticalRegion() { } public static void BeginThreadAffinity() { } public void DisableComObjectEagerCleanup() { } public static void EndCriticalRegion() { } public static void EndThreadAffinity() { } ~Thread() { } public static void FreeNamedDataSlot(string name) { } public System.Threading.ApartmentState GetApartmentState() { throw null; } [System.ObsoleteAttribute("Thread.GetCompressedStack is no longer supported. Please use the System.Threading.CompressedStack class")] public System.Threading.CompressedStack GetCompressedStack() { throw null; } public static int GetCurrentProcessorId() { throw null; } public static object? GetData(System.LocalDataStoreSlot slot) { throw null; } public static System.AppDomain GetDomain() { throw null; } public static int GetDomainID() { throw null; } public override int GetHashCode() { throw null; } public static System.LocalDataStoreSlot GetNamedDataSlot(string name) { throw null; } public void Interrupt() { } public void Join() { } public bool Join(int millisecondsTimeout) { throw null; } public bool Join(System.TimeSpan timeout) { throw null; } public static void MemoryBarrier() { } [System.ObsoleteAttribute("Thread.ResetAbort is not supported and throws PlatformNotSupportedException.", DiagnosticId = "SYSLIB0006", UrlFormat = "https://aka.ms/dotnet-warnings/{0}")] public static void ResetAbort() { } [System.ObsoleteAttribute("Thread.Resume has been deprecated. Please use other classes in System.Threading, such as Monitor, Mutex, Event, and Semaphore, to synchronize Threads or protect resources. https://go.microsoft.com/fwlink/?linkid=14202", false)] public void Resume() { } [System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")] public void SetApartmentState(System.Threading.ApartmentState state) { } [System.ObsoleteAttribute("Thread.SetCompressedStack is no longer supported. Please use the System.Threading.CompressedStack class")] public void SetCompressedStack(System.Threading.CompressedStack stack) { } public static void SetData(System.LocalDataStoreSlot slot, object? data) { } public static void Sleep(int millisecondsTimeout) { } public static void Sleep(System.TimeSpan timeout) { } public static void SpinWait(int iterations) { } [System.Runtime.Versioning.UnsupportedOSPlatformAttribute("browser")] public void Start() { } [System.Runtime.Versioning.UnsupportedOSPlatformAttribute("browser")] public void Start(object? parameter) { } [System.ObsoleteAttribute("Thread.Suspend has been deprecated. Please use other classes in System.Threading, such as Monitor, Mutex, Event, and Semaphore, to synchronize Threads or protect resources. https://go.microsoft.com/fwlink/?linkid=14202", false)] public void Suspend() { } public bool TrySetApartmentState(System.Threading.ApartmentState state) { throw null; } [System.Runtime.Versioning.UnsupportedOSPlatformAttribute("browser")] public void UnsafeStart() { } [System.Runtime.Versioning.UnsupportedOSPlatformAttribute("browser")] public void UnsafeStart(object? parameter) { } public static byte VolatileRead(ref byte address) { throw null; } public static double VolatileRead(ref double address) { throw null; } public static short VolatileRead(ref short address) { throw null; } public static int VolatileRead(ref int address) { throw null; } public static long VolatileRead(ref long address) { throw null; } public static System.IntPtr VolatileRead(ref System.IntPtr address) { throw null; } [return: System.Diagnostics.CodeAnalysis.NotNullIfNotNullAttribute("address")] public static object? VolatileRead([System.Diagnostics.CodeAnalysis.NotNullIfNotNullAttribute("address")] ref object? address) { throw null; } [System.CLSCompliantAttribute(false)] public static sbyte VolatileRead(ref sbyte address) { throw null; } public static float VolatileRead(ref float address) { throw null; } [System.CLSCompliantAttribute(false)] public static ushort VolatileRead(ref ushort address) { throw null; } [System.CLSCompliantAttribute(false)] public static uint VolatileRead(ref uint address) { throw null; } [System.CLSCompliantAttribute(false)] public static ulong VolatileRead(ref ulong address) { throw null; } [System.CLSCompliantAttribute(false)] public static System.UIntPtr VolatileRead(ref System.UIntPtr address) { throw null; } public static void VolatileWrite(ref byte address, byte value) { } public static void VolatileWrite(ref double address, double value) { } public static void VolatileWrite(ref short address, short value) { } public static void VolatileWrite(ref int address, int value) { } public static void VolatileWrite(ref long address, long value) { } public static void VolatileWrite(ref System.IntPtr address, System.IntPtr value) { } public static void VolatileWrite([System.Diagnostics.CodeAnalysis.NotNullIfNotNullAttribute("value")] ref object? address, object? value) { } [System.CLSCompliantAttribute(false)] public static void VolatileWrite(ref sbyte address, sbyte value) { } public static void VolatileWrite(ref float address, float value) { } [System.CLSCompliantAttribute(false)] public static void VolatileWrite(ref ushort address, ushort value) { } [System.CLSCompliantAttribute(false)] public static void VolatileWrite(ref uint address, uint value) { } [System.CLSCompliantAttribute(false)] public static void VolatileWrite(ref ulong address, ulong value) { } [System.CLSCompliantAttribute(false)] public static void VolatileWrite(ref System.UIntPtr address, System.UIntPtr value) { } public static bool Yield() { throw null; } } public sealed partial class ThreadAbortException : System.SystemException { internal ThreadAbortException() { } public object? ExceptionState { get { throw null; } } } public partial class ThreadExceptionEventArgs : System.EventArgs { public ThreadExceptionEventArgs(System.Exception t) { } public System.Exception Exception { get { throw null; } } } public delegate void ThreadExceptionEventHandler(object sender, System.Threading.ThreadExceptionEventArgs e); public partial class ThreadInterruptedException : System.SystemException { public ThreadInterruptedException() { } protected ThreadInterruptedException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public ThreadInterruptedException(string? message) { } public ThreadInterruptedException(string? message, System.Exception? innerException) { } } public enum ThreadPriority { Lowest = 0, BelowNormal = 1, Normal = 2, AboveNormal = 3, Highest = 4, } public delegate void ThreadStart(); public sealed partial class ThreadStartException : System.SystemException { internal ThreadStartException() { } } [System.FlagsAttribute] public enum ThreadState { Running = 0, StopRequested = 1, SuspendRequested = 2, Background = 4, Unstarted = 8, Stopped = 16, WaitSleepJoin = 32, Suspended = 64, AbortRequested = 128, Aborted = 256, } public partial class ThreadStateException : System.SystemException { public ThreadStateException() { } protected ThreadStateException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public ThreadStateException(string? message) { } public ThreadStateException(string? message, System.Exception? innerException) { } } }
61.107692
265
0.694444
[ "MIT" ]
Acidburn0zzz/runtime
src/libraries/System.Threading.Thread/ref/System.Threading.Thread.cs
11,916
C#
// ------------------------------------------------------------------------------ // <autogenerated> // This code was generated by a tool. // Mono Runtime Version: 4.0.30319.1 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </autogenerated> // ------------------------------------------------------------------------------ namespace Web.pages { public partial class cloudEdit { protected System.Web.UI.WebControls.Content cHead; protected System.Web.UI.WebControls.Content cDetail; protected System.Web.UI.WebControls.HiddenField hidSortColumn; protected System.Web.UI.WebControls.HiddenField hidPage; protected System.Web.UI.WebControls.TextBox txtSearch; protected System.Web.UI.WebControls.Literal ltClouds; protected System.Web.UI.WebControls.Literal ltProviders; protected System.Web.UI.WebControls.DropDownList ddlTestAccount; } }
29.30303
81
0.611169
[ "Apache-2.0" ]
remotesyssupport/cato
web/pages/cloudEdit.aspx.designer.cs
967
C#
using Microsoft.AspNetCore.Mvc; namespace PokemonApi.Controllers { [ApiController] [Route("[controller]")] public class WeatherForecastController : ControllerBase { private static readonly string[] Summaries = new[] { "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" }; private readonly ILogger<WeatherForecastController> _logger; public WeatherForecastController(ILogger<WeatherForecastController> logger) { _logger = logger; } [HttpGet(Name = "GetWeatherForecast")] public IEnumerable<WeatherForecast> Get() { return Enumerable.Range(1, 5).Select(index => new WeatherForecast { Date = DateTime.Now.AddDays(index), TemperatureC = Random.Shared.Next(-20, 55), Summary = Summaries[Random.Shared.Next(Summaries.Length)] }) .ToArray(); } } }
30.666667
106
0.591897
[ "MIT" ]
220328-uta-sh-net-ext/EdithKennedyTynes
220328 Training/PokemonApp/PokemonApi/Controllers/WeatherForecastController.cs
1,012
C#
using System.Collections; using System.Collections.Generic; using System.IO; using System.Text.RegularExpressions; using UnityEditor; using UnityEngine; namespace BlueToolkit { public class AutoAddNameSpace : UnityEditor.AssetModificationProcessor { private static void OnWillCreateAsset(string path) { if (!IsOn()) return; path = path.Replace(".meta", ""); if (path.EndsWith(".cs")) { string text = ""; text += File.ReadAllText(path); string name = GetClassName(text); if (string.IsNullOrEmpty(name)) { return; } var newText = GetNewScriptContext(name); File.WriteAllText(path, newText); } AssetDatabase.Refresh(); } public static NamespaceData GetData() { return AssetDatabase.LoadAssetAtPath<NamespaceData>(PathManager.NameSpaceDataPath); } private static bool IsOn() { NamespaceData data = GetData(); if (data != null) { return data.IsOn; } return false; } //获取新的脚本内容 private static string GetNewScriptContext(string className) { var script = new ScriptBuildHelp(); script.WriteEmptyLine(); var data = AddNamespaceWindow.GetData(); string name = data == null ? "UIFrame" : data.name; script.WriteNamespace(name); script.IndentTimes++; script.WriteClass(className); return script.ToString(); } //获取类名 private static string GetClassName(string text) { //string[] data = text.Split(' '); //int index = 0; //for (int i = 0; i < data.Length; i++) //{ // if (data[i].Contains("class")) // { // index = i + 1; // break; // } //} //if (data[index].Contains(":")) //{ // return data[index].Split(':')[0]; //} //else //{ // return data[index]; //} //public class NewBehaviourScript : MonoBehaviour string patterm = "public class ([A-Za-z0-9_]+)\\s*:\\s*MonoBehaviour"; var match = Regex.Match(text, patterm); if (match.Success) { return match.Groups[1].Value; } return ""; } } }
26.359223
95
0.465562
[ "MIT" ]
BlueMonk1107/BlueGameAI
Assets/ToolKit/AutoAddNamespace/AutoAddNameSpace.cs
2,741
C#
using System; using System.Collections.Generic; namespace NetDependencyWalker.Walking { using System.Linq; using NetDependencyWalker.ViewModel; using Mono.Cecil; internal class TypeInspector { private readonly OrderingType _orderingType; public TypeInspector(OrderingType orderingType) { _orderingType = orderingType; } readonly Dictionary<string, ReferencedTypeNode> _referencedTypeNodes = new Dictionary<string, ReferencedTypeNode>(); public IList<ReferencedTypeNode> CalculateReferencedTypes(string sourcePath, string targetPath) { var child = AssemblyDefinition.ReadAssembly(targetPath); var parent = AssemblyDefinition.ReadAssembly(sourcePath); var resultNodes = new List<ReferencedTypeNode>(); foreach (var type in parent.MainModule.Types) { CheckAndAddTypeReference(type.BaseType, type, ReferencingMemberType.TypeHierarchy, string.Empty, child, false); foreach (var fieldDefinition in type.Fields) { if (fieldDefinition.IsSpecialName || fieldDefinition.IsRuntimeSpecialName || fieldDefinition.Name.EndsWith("__BackingField", StringComparison.Ordinal)) { continue; } CheckAndAddTypeReference(fieldDefinition.FieldType, type, ReferencingMemberType.Field, fieldDefinition.Name, child, false); } foreach (var propertyDefinition in type.Properties) { CheckAndAddTypeReference(propertyDefinition.PropertyType, type, ReferencingMemberType.Property, propertyDefinition.Name, child, false); if (propertyDefinition.GetMethod != null) { ScanMethodBody(propertyDefinition.GetMethod, type, ReferencingMemberType.Property, propertyDefinition.Name, child); } if (propertyDefinition.SetMethod != null) { ScanMethodBody(propertyDefinition.SetMethod, type, ReferencingMemberType.Property, propertyDefinition.Name, child); } } foreach (var methodDefinition in type.Methods) { if (methodDefinition.IsGetter || methodDefinition.IsSetter) { continue; } CheckAndAddTypeReference(methodDefinition.ReturnType, type, ReferencingMemberType.Method, methodDefinition.Name, child, false); ScanMethodBody(methodDefinition, type, ReferencingMemberType.Method, methodDefinition.Name, child); } } foreach (var node in _referencedTypeNodes.Values.OrderBy(x => x.Namespace + "." + x.ClassName)) { Clean(node); resultNodes.Add(node); } return resultNodes; } private void Clean(ReferencedTypeNode node) { foreach (var childNode in node.Children) { Clean(childNode); } node.Children.Sort((x, y) => string.Compare(x.Initial + x.Secondary, y.Initial + y.Secondary, StringComparison.Ordinal)); } void ReferencedThenReferencingThenMember(TypeReference typeReference, string ns, TypeDefinition typeDefinition, string memberName, ReferencingMemberType referencingMemberType, bool isBodyReference) { var key = typeReference.Scope.Name + ":" + typeReference.FullName; if (!_referencedTypeNodes.TryGetValue(key, out var referencedTypeNode)) { referencedTypeNode = new ReferencedTypeNode(ns, typeReference.FullName.Substring(ns.Length + 1), null, null); _referencedTypeNodes[key] = referencedTypeNode; } var childReferencingTypeNode = referencedTypeNode.Children.FirstOrDefault(x => x.Namespace == typeDefinition.Namespace && x.ClassName == typeDefinition.Name); if (childReferencingTypeNode == null) { childReferencingTypeNode = new ReferencedTypeNode(typeDefinition.Namespace, typeDefinition.Name, false, typeDefinition.Name + " contains references to " + typeReference.FullName.Substring(ns.Length + 1)); referencedTypeNode.Children.Add(childReferencingTypeNode); } if (!childReferencingTypeNode.Children.Any(x => x.MemberName == memberName && x.MemberType == referencingMemberType)) { var description = GetReferenceDescription(typeReference, ns, typeDefinition, memberName, referencingMemberType, isBodyReference); childReferencingTypeNode.Children.Add(new ReferencedTypeNode(referencingMemberType, memberName, description)); } } private static string GetReferenceDescription(TypeReference typeReference, string ns, TypeDefinition typeDefinition, string memberName, ReferencingMemberType referencingMemberType, bool isBodyReference) { if (isBodyReference) { return "The implementation of " + typeDefinition.Name + "." + memberName + " contains references to " + typeReference.FullName.Substring(ns.Length + 1); } if (referencingMemberType == ReferencingMemberType.Field || referencingMemberType == ReferencingMemberType.Property) { return typeDefinition.Name + "." + memberName + " is of a type that is or includes " + typeReference.FullName.Substring(ns.Length + 1); } if (referencingMemberType == ReferencingMemberType.Method) { return typeDefinition.Name + "." + memberName + " has a return type that is or includes " + typeReference.FullName.Substring(ns.Length + 1); } if (referencingMemberType == ReferencingMemberType.TypeHierarchy) { return typeDefinition.Name + " inherits a type that is or includes " + typeReference.FullName.Substring(ns.Length + 1); } return null; } void ReferencingThenReferencedThenMember(TypeReference typeReference, string ns, TypeDefinition typeDefinition, string memberName, ReferencingMemberType referencingMemberType, bool isBodyReference) { var key = typeDefinition.FullName; if (!_referencedTypeNodes.TryGetValue(key, out var referencedTypeNode)) { referencedTypeNode = new ReferencedTypeNode(typeDefinition.Namespace, typeDefinition.Name, null, null); _referencedTypeNodes[key] = referencedTypeNode; } var memberNode = referencedTypeNode.Children.FirstOrDefault(x => x.MemberName == memberName && x.MemberType == referencingMemberType); if (memberNode == null) { memberNode = new ReferencedTypeNode(referencingMemberType, memberName, null); referencedTypeNode.Children.Add(memberNode); } var description = GetReferenceDescription(typeReference, ns, typeDefinition, memberName, referencingMemberType, isBodyReference); var childReferencingType = new ReferencedTypeNode(ns, typeReference.FullName.Substring(ns.Length + 1), true, description); var childReferencingTypeNode = memberNode.Children.FirstOrDefault(x => x.Namespace == childReferencingType.Namespace && x.ClassName == childReferencingType.ClassName); if (childReferencingTypeNode == null) { memberNode.Children.Add(childReferencingType); } } void ReferencingThenReferenced(TypeReference typeReference, string ns, TypeDefinition typeDefinition) { var key = typeDefinition.FullName; if (!_referencedTypeNodes.TryGetValue(key, out var referencedTypeNode)) { referencedTypeNode = new ReferencedTypeNode(typeDefinition.Namespace, typeDefinition.Name, null, null); _referencedTypeNodes[key] = referencedTypeNode; } var childReferencingType = new ReferencedTypeNode(ns, typeReference.FullName.Substring(ns.Length + 1), true, typeDefinition.Name + " contains references to " + typeReference.FullName.Substring(ns.Length + 1)); var childReferencingTypeNode = referencedTypeNode.Children.FirstOrDefault(x => x.Namespace == childReferencingType.Namespace && x.ClassName == childReferencingType.ClassName); if (childReferencingTypeNode == null) { referencedTypeNode.Children.Add(childReferencingType); } } void AddReference(TypeReference referencedType, TypeDefinition referencingType, ReferencingMemberType memberType, string memberName, bool isBodyReference) { var @namespace = referencedType.Namespace; var current = referencedType; while (current != null && current.IsNested) { if (current.DeclaringType != null) { @namespace = current.DeclaringType.Namespace; } current = current.DeclaringType; } switch (_orderingType) { case OrderingType.ReferencedThenReferencingThenMember: ReferencedThenReferencingThenMember(referencedType, @namespace, referencingType, memberName, memberType, isBodyReference); break; case OrderingType.ReferencingThenMemberThenReferenced: ReferencingThenReferencedThenMember(referencedType, @namespace, referencingType, memberName, memberType, isBodyReference); break; case OrderingType.ReferencingThenReferenced: ReferencingThenReferenced(referencedType, @namespace, referencingType); break; } } void CheckAndAddTypeReference(TypeReference referencedType, TypeDefinition referencingType, ReferencingMemberType memberType, string memberName, AssemblyDefinition child, bool isBodyReference) { if (referencedType == null) { return; } if (referencedType.IsNested) { CheckAndAddTypeReference(referencedType.DeclaringType, referencingType, memberType, memberName, child, isBodyReference); return; } if (referencedType.IsGenericInstance) { GenericInstanceType instance = (GenericInstanceType)referencedType; foreach (var genericArgument in instance.GenericArguments) { CheckAndAddTypeReference(genericArgument, referencingType, memberType, memberName, child, isBodyReference); } } if (referencedType.Name.StartsWith("!")) { return; } if (referencedType.Scope.Name != child.Name.Name) { return; } AddReference(referencedType, referencingType, memberType, memberName, isBodyReference); } void ScanMethodBody(MethodDefinition methodDefinition, TypeDefinition referencingType, ReferencingMemberType memberType, string memberName, AssemblyDefinition child) { if (methodDefinition.Body == null) { return; } foreach (var operand in methodDefinition.Body.Instructions.Select(i => i.Operand)) { if (operand is TypeReference typeRef) { CheckAndAddTypeReference(typeRef, referencingType, memberType, memberName, child, true); } else if (operand is FieldReference fieldRef) { CheckAndAddTypeReference(fieldRef.FieldType, referencingType, memberType, memberName, child, true); } else if (operand is PropertyReference propertyRef) { CheckAndAddTypeReference(propertyRef.PropertyType, referencingType, memberType, memberName, child, true); } else if (operand is MethodReference methodReference) { CheckAndAddTypeReference(methodReference.ReturnType, referencingType, memberType, memberName, child, true); } } } } }
46.456204
221
0.62283
[ "MIT" ]
mattwhitfield/NetDependencyWalker
src/Walking/TypeInspector.cs
12,731
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using static System.Linq.Utilities; namespace System.Linq { public static partial class Enumerable { public static IEnumerable<TSource> Where<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate) { if (source == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.source); } if (predicate == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.predicate); } if (source is Iterator<TSource> iterator) { return iterator.Where(predicate); } if (source is TSource[] array) { return array.Length == 0 ? Empty<TSource>() : new WhereArrayIterator<TSource>(array, predicate); } if (source is List<TSource> list) { return new WhereListIterator<TSource>(list, predicate); } return new WhereEnumerableIterator<TSource>(source, predicate); } public static IEnumerable<TSource> Where<TSource>(this IEnumerable<TSource> source, Func<TSource, int, bool> predicate) { if (source == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.source); } if (predicate == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.predicate); } return WhereIterator(source, predicate); } private static IEnumerable<TSource> WhereIterator<TSource>(IEnumerable<TSource> source, Func<TSource, int, bool> predicate) { int index = -1; foreach (TSource element in source) { checked { index++; } if (predicate(element, index)) { yield return element; } } } /// <summary> /// An iterator that filters each item of an <see cref="IEnumerable{TSource}"/>. /// </summary> /// <typeparam name="TSource">The type of the source enumerable.</typeparam> private sealed partial class WhereEnumerableIterator<TSource> : Iterator<TSource> { private readonly IEnumerable<TSource> _source; private readonly Func<TSource, bool> _predicate; private IEnumerator<TSource>? _enumerator; public WhereEnumerableIterator(IEnumerable<TSource> source, Func<TSource, bool> predicate) { Debug.Assert(source != null); Debug.Assert(predicate != null); _source = source; _predicate = predicate; } public override Iterator<TSource> Clone() => new WhereEnumerableIterator<TSource>(_source, _predicate); public override void Dispose() { if (_enumerator != null) { _enumerator.Dispose(); _enumerator = null; } base.Dispose(); } public override bool MoveNext() { switch (_state) { case 1: _enumerator = _source.GetEnumerator(); _state = 2; goto case 2; case 2: Debug.Assert(_enumerator != null); while (_enumerator.MoveNext()) { TSource item = _enumerator.Current; if (_predicate(item)) { _current = item; return true; } } Dispose(); break; } return false; } public override IEnumerable<TResult> Select<TResult>(Func<TSource, TResult> selector) => new WhereSelectEnumerableIterator<TSource, TResult>(_source, _predicate, selector); public override IEnumerable<TSource> Where(Func<TSource, bool> predicate) => new WhereEnumerableIterator<TSource>(_source, CombinePredicates(_predicate, predicate)); } /// <summary> /// An iterator that filters each item of an array. /// </summary> /// <typeparam name="TSource">The type of the source array.</typeparam> internal sealed partial class WhereArrayIterator<TSource> : Iterator<TSource> { private readonly TSource[] _source; private readonly Func<TSource, bool> _predicate; public WhereArrayIterator(TSource[] source, Func<TSource, bool> predicate) { Debug.Assert(source != null && source.Length > 0); Debug.Assert(predicate != null); _source = source; _predicate = predicate; } public override Iterator<TSource> Clone() => new WhereArrayIterator<TSource>(_source, _predicate); public override bool MoveNext() { int index = _state - 1; TSource[] source = _source; while (unchecked((uint)index < (uint)source.Length)) { TSource item = source[index]; index = _state++; if (_predicate(item)) { _current = item; return true; } } Dispose(); return false; } public override IEnumerable<TResult> Select<TResult>(Func<TSource, TResult> selector) => new WhereSelectArrayIterator<TSource, TResult>(_source, _predicate, selector); public override IEnumerable<TSource> Where(Func<TSource, bool> predicate) => new WhereArrayIterator<TSource>(_source, CombinePredicates(_predicate, predicate)); } /// <summary> /// An iterator that filters each item of a <see cref="List{TSource}"/>. /// </summary> /// <typeparam name="TSource">The type of the source list.</typeparam> private sealed partial class WhereListIterator<TSource> : Iterator<TSource> { private readonly List<TSource> _source; private readonly Func<TSource, bool> _predicate; private List<TSource>.Enumerator _enumerator; public WhereListIterator(List<TSource> source, Func<TSource, bool> predicate) { Debug.Assert(source != null); Debug.Assert(predicate != null); _source = source; _predicate = predicate; } public override Iterator<TSource> Clone() => new WhereListIterator<TSource>(_source, _predicate); public override bool MoveNext() { switch (_state) { case 1: _enumerator = _source.GetEnumerator(); _state = 2; goto case 2; case 2: while (_enumerator.MoveNext()) { TSource item = _enumerator.Current; if (_predicate(item)) { _current = item; return true; } } Dispose(); break; } return false; } public override IEnumerable<TResult> Select<TResult>(Func<TSource, TResult> selector) => new WhereSelectListIterator<TSource, TResult>(_source, _predicate, selector); public override IEnumerable<TSource> Where(Func<TSource, bool> predicate) => new WhereListIterator<TSource>(_source, CombinePredicates(_predicate, predicate)); } /// <summary> /// An iterator that filters, then maps, each item of an array. /// </summary> /// <typeparam name="TSource">The type of the source array.</typeparam> /// <typeparam name="TResult">The type of the mapped items.</typeparam> private sealed partial class WhereSelectArrayIterator<TSource, TResult> : Iterator<TResult> { private readonly TSource[] _source; private readonly Func<TSource, bool> _predicate; private readonly Func<TSource, TResult> _selector; public WhereSelectArrayIterator(TSource[] source, Func<TSource, bool> predicate, Func<TSource, TResult> selector) { Debug.Assert(source != null && source.Length > 0); Debug.Assert(predicate != null); Debug.Assert(selector != null); _source = source; _predicate = predicate; _selector = selector; } public override Iterator<TResult> Clone() => new WhereSelectArrayIterator<TSource, TResult>(_source, _predicate, _selector); public override bool MoveNext() { int index = _state - 1; TSource[] source = _source; while (unchecked((uint)index < (uint)source.Length)) { TSource item = source[index]; index = _state++; if (_predicate(item)) { _current = _selector(item); return true; } } Dispose(); return false; } public override IEnumerable<TResult2> Select<TResult2>(Func<TResult, TResult2> selector) => new WhereSelectArrayIterator<TSource, TResult2>(_source, _predicate, CombineSelectors(_selector, selector)); } /// <summary> /// An iterator that filters, then maps, each item of a <see cref="List{TSource}"/>. /// </summary> /// <typeparam name="TSource">The type of the source list.</typeparam> /// <typeparam name="TResult">The type of the mapped items.</typeparam> private sealed partial class WhereSelectListIterator<TSource, TResult> : Iterator<TResult> { private readonly List<TSource> _source; private readonly Func<TSource, bool> _predicate; private readonly Func<TSource, TResult> _selector; private List<TSource>.Enumerator _enumerator; public WhereSelectListIterator(List<TSource> source, Func<TSource, bool> predicate, Func<TSource, TResult> selector) { Debug.Assert(source != null); Debug.Assert(predicate != null); Debug.Assert(selector != null); _source = source; _predicate = predicate; _selector = selector; } public override Iterator<TResult> Clone() => new WhereSelectListIterator<TSource, TResult>(_source, _predicate, _selector); public override bool MoveNext() { switch (_state) { case 1: _enumerator = _source.GetEnumerator(); _state = 2; goto case 2; case 2: while (_enumerator.MoveNext()) { TSource item = _enumerator.Current; if (_predicate(item)) { _current = _selector(item); return true; } } Dispose(); break; } return false; } public override IEnumerable<TResult2> Select<TResult2>(Func<TResult, TResult2> selector) => new WhereSelectListIterator<TSource, TResult2>(_source, _predicate, CombineSelectors(_selector, selector)); } /// <summary> /// An iterator that filters, then maps, each item of an <see cref="IEnumerable{TSource}"/>. /// </summary> /// <typeparam name="TSource">The type of the source enumerable.</typeparam> /// <typeparam name="TResult">The type of the mapped items.</typeparam> private sealed partial class WhereSelectEnumerableIterator<TSource, TResult> : Iterator<TResult> { private readonly IEnumerable<TSource> _source; private readonly Func<TSource, bool> _predicate; private readonly Func<TSource, TResult> _selector; private IEnumerator<TSource>? _enumerator; public WhereSelectEnumerableIterator(IEnumerable<TSource> source, Func<TSource, bool> predicate, Func<TSource, TResult> selector) { Debug.Assert(source != null); Debug.Assert(predicate != null); Debug.Assert(selector != null); _source = source; _predicate = predicate; _selector = selector; } public override Iterator<TResult> Clone() => new WhereSelectEnumerableIterator<TSource, TResult>(_source, _predicate, _selector); public override void Dispose() { if (_enumerator != null) { _enumerator.Dispose(); _enumerator = null; } base.Dispose(); } public override bool MoveNext() { switch (_state) { case 1: _enumerator = _source.GetEnumerator(); _state = 2; goto case 2; case 2: Debug.Assert(_enumerator != null); while (_enumerator.MoveNext()) { TSource item = _enumerator.Current; if (_predicate(item)) { _current = _selector(item); return true; } } Dispose(); break; } return false; } public override IEnumerable<TResult2> Select<TResult2>(Func<TResult, TResult2> selector) => new WhereSelectEnumerableIterator<TSource, TResult2>(_source, _predicate, CombineSelectors(_selector, selector)); } } }
37.596618
141
0.498554
[ "MIT" ]
06needhamt/runtime
src/libraries/System.Linq/src/System/Linq/Where.cs
15,567
C#
//------------------------------------------------------------------------------ // <auto-generated> // Ce code a été généré par un outil. // Version du runtime :4.0.30319.42000 // // Les modifications apportées à ce fichier peuvent provoquer un comportement incorrect et seront perdues si // le code est régénéré. // </auto-generated> //------------------------------------------------------------------------------ namespace RoundScreenCorner.Properties { using System; /// <summary> /// Une classe de ressource fortement typée destinée, entre autres, à la consultation des chaînes localisées. /// </summary> // Cette classe a été générée automatiquement par la classe StronglyTypedResourceBuilder // à l'aide d'un outil, tel que ResGen ou Visual Studio. // Pour ajouter ou supprimer un membre, modifiez votre fichier .ResX, puis réexécutez ResGen // avec l'option /str ou régénérez votre projet VS. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Retourne l'instance ResourceManager mise en cache utilisée par cette classe. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("RoundScreenCorner.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Remplace la propriété CurrentUICulture du thread actuel pour toutes /// les recherches de ressources à l'aide de cette classe de ressource fortement typée. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } /// <summary> /// Recherche une ressource localisée de type System.Drawing.Bitmap. /// </summary> internal static System.Drawing.Bitmap corner_bl { get { object obj = ResourceManager.GetObject("corner-bl", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Recherche une ressource localisée de type System.Drawing.Bitmap. /// </summary> internal static System.Drawing.Bitmap corner_br { get { object obj = ResourceManager.GetObject("corner-br", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Recherche une ressource localisée de type System.Drawing.Bitmap. /// </summary> internal static System.Drawing.Bitmap corner_ul { get { object obj = ResourceManager.GetObject("corner-ul", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Recherche une ressource localisée de type System.Drawing.Bitmap. /// </summary> internal static System.Drawing.Bitmap corner_ur { get { object obj = ResourceManager.GetObject("corner-ur", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } } }
43.826923
184
0.581615
[ "MIT" ]
mk-dev-team/mk-roundscreen
src/RoundScreenCorner/Properties/Resources.Designer.cs
4,596
C#
using System; using System.Collections.Generic; using UnityEngine; using UnityEditor; using IODirection = ActionConnection.IODirection; using InterfaceTypes = NodeInterface.InterfaceTypes; using Ifaces = WalkAction.Ifaces; public class WalkNode : BaseNode { public float walkSpeed; public float walkDuration; public WalkAction.WalkOptions walkOption; private int selectedWalkOptionIndex; protected override void AddInterfaces() { AddInput((int)Ifaces.Input); AddInput((int)Ifaces.Direction, InterfaceTypes.Object); AddOutput((int)Ifaces.StartWalk); AddOutput((int)Ifaces.EndWalk); AddOutput((int)Ifaces.HitWall); } private void SetInterfacePositions() { SetInterface((int)Ifaces.Input, 1); SetInterface((int)Ifaces.Direction, 6); SetInterface((int)Ifaces.StartWalk, 1, "Begin"); SetInterface((int)Ifaces.EndWalk, 2, "End"); SetInterface((int)Ifaces.HitWall, 3, "Hit Wall"); } public override void Draw() { WindowTitle = "Walk"; Transform.Width = 170; Transform.Height = 150; NodeGUI.Space(3); walkSpeed = NodeGUI.FloatFieldLayout(walkSpeed, "Speed:"); walkDuration = NodeGUI.FloatFieldLayout(walkDuration, "Duration:"); if (GetInterface((int)Ifaces.Direction).IsConnected()) NodeGUI.LabelLayout("To " + GetInterface((int)Ifaces.Direction).ConnectedInterface.GetNode().WindowTitle); else walkOption = (WalkAction.WalkOptions)NodeGUI.EnumPopupLayout("Direction:", walkOption); SetInterfacePositions(); DrawInterfaces(); } public override BaseAction GetAction() { return new WalkAction() { WalkDuration = walkDuration, WalkSpeed = walkSpeed, WalkOption = walkOption }; } private void AddSpaces(int numSpaces) { for (int i = 0; i < numSpaces; i++) { EditorGUILayout.LabelField(""); } } }
27.810811
118
0.639942
[ "Apache-2.0" ]
Aspekt1024/ClumsyBat
Assets/Scripts/Editor/NodeEditor/BossEditor/Nodes/WalkNode.cs
2,060
C#
/* * Copyright (c) 2022 ETH Zürich, Educational Development and Technology (LET) * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ using System; namespace SafeExamBrowser.WindowsApi.Constants { /// <remarks> /// See https://docs.microsoft.com/de-de/windows/desktop/SecAuthZ/access-mask /// </remarks> [Flags] internal enum AccessMask : uint { DESKTOP_NONE = 0, DESKTOP_READOBJECTS = 0x0001, DESKTOP_CREATEWINDOW = 0x0002, DESKTOP_CREATEMENU = 0x0004, DESKTOP_HOOKCONTROL = 0x0008, DESKTOP_JOURNALRECORD = 0x0010, DESKTOP_JOURNALPLAYBACK = 0x0020, DESKTOP_ENUMERATE = 0x0040, DESKTOP_WRITEOBJECTS = 0x0080, DESKTOP_SWITCHDESKTOP = 0x0100, GENERIC_ALL = (DESKTOP_READOBJECTS | DESKTOP_CREATEWINDOW | DESKTOP_CREATEMENU | DESKTOP_HOOKCONTROL | DESKTOP_JOURNALRECORD | DESKTOP_JOURNALPLAYBACK | DESKTOP_ENUMERATE | DESKTOP_WRITEOBJECTS | DESKTOP_SWITCHDESKTOP | Constant.STANDARD_RIGHTS_REQUIRED) } }
31.342857
126
0.757521
[ "MPL-2.0" ]
RickAllMighty8195/seb-win-refactoring
SafeExamBrowser.WindowsApi/Constants/AccessMask.cs
1,100
C#
using System.Collections.Generic; using System.Reflection; using UnityEngine; using UnityEngine.Experimental.Rendering.Universal; namespace TilemapShadowCaster.Runtime { public class PathShadow : ShadowCaster2D { static FieldInfo shapeFieldInfo = typeof(ShadowCaster2D).GetField("m_ShapePath", BindingFlags.NonPublic | BindingFlags.Instance); static FieldInfo shapeHashFieldInfo = typeof(ShadowCaster2D).GetField("m_ShapePathHash", BindingFlags.NonPublic | BindingFlags.Instance); static FieldInfo sortingLayersFieldInfo = typeof(ShadowCaster2D).GetField("m_ApplyToSortingLayers", BindingFlags.NonPublic | BindingFlags.Instance); internal void SetShape(List<Vector2> points, int[] sortingLayers) { Vector3[] shapev3 = points.ConvertAll((point) => new Vector3(point.x, point.y)).ToArray(); shapeFieldInfo.SetValue(this, shapev3); sortingLayersFieldInfo.SetValue(this, sortingLayers); shapeHashFieldInfo.SetValue(this, (int) UnityEngine.Random.Range(0f, 10000000f)); } } }
41.481481
107
0.713393
[ "Apache-2.0" ]
corynorris/brackeys-2020.2
Assets/Tilemap-Shadow-Caster-main/Runtime/PathShadow.cs
1,122
C#
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Net; using System.Reflection; using System.Timers; using log4net; using Nini.Config; using Mono.Addins; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Servers.HttpServer; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Framework.Capabilities; using Caps = OpenSim.Framework.Capabilities.Caps; namespace OpenSim.Region.ClientStack.Linden { [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "UploadBakedTextureModule")] public class UploadBakedTextureModule : ISharedRegionModule { private static readonly ILog m_log =LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private int m_nscenes; IAssetCache m_assetCache = null; private string m_URL; public void Initialise(IConfigSource source) { IConfig config = source.Configs["ClientStack.LindenCaps"]; if (config == null) return; m_URL = config.GetString("Cap_UploadBakedTexture", string.Empty); } public void AddRegion(Scene s) { } public void RemoveRegion(Scene s) { s.EventManager.OnRegisterCaps -= RegisterCaps; --m_nscenes; if(m_nscenes <= 0) m_assetCache = null; } public void RegionLoaded(Scene s) { if (m_assetCache == null) m_assetCache = s.RequestModuleInterface <IAssetCache>(); if (m_assetCache != null) { ++m_nscenes; s.EventManager.OnRegisterCaps += RegisterCaps; } } public void PostInitialise() { } public void Close() { } public string Name { get { return "UploadBakedTextureModule"; } } public Type ReplaceableInterface { get { return null; } } public void RegisterCaps(UUID agentID, Caps caps) { if (m_URL == "localhost") { caps.RegisterSimpleHandler("UploadBakedTexture", new SimpleStreamHandler("/" + UUID.Random(), delegate (IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { UploadBakedTexture(httpRequest, httpResponse, agentID, caps, m_assetCache); })); } else if(!string.IsNullOrWhiteSpace(m_URL)) { caps.RegisterHandler("UploadBakedTexture", m_URL); } } public void UploadBakedTexture(IOSHttpRequest httpRequest, IOSHttpResponse httpResponse, UUID agentID, Caps caps, IAssetCache cache) { if(httpRequest.HttpMethod != "POST") { httpResponse.StatusCode = (int)HttpStatusCode.NotFound; return; } try { string capsBase = "/" + UUID.Random()+"-BK"; string protocol = caps.SSLCaps ? "https://" : "http://"; string uploaderURL = protocol + caps.HostName + ":" + caps.Port.ToString() + capsBase; LLSDAssetUploadResponse uploadResponse = new LLSDAssetUploadResponse(); uploadResponse.uploader = uploaderURL; uploadResponse.state = "upload"; BakedTextureUploader uploader = new BakedTextureUploader(capsBase, caps.HttpListener, agentID, cache, httpRequest.RemoteIPEndPoint.Address); var uploaderHandler = new SimpleBinaryHandler("POST", capsBase, uploader.process); uploaderHandler.MaxDataSize = 6000000; // change per asset type? caps.HttpListener.AddSimpleStreamHandler(uploaderHandler); httpResponse.RawBuffer = Util.UTF8NBGetbytes(LLSDHelpers.SerialiseLLSDReply(uploadResponse)); httpResponse.StatusCode = (int)HttpStatusCode.OK; return; } catch (Exception e) { m_log.ErrorFormat("[UPLOAD BAKED TEXTURE HANDLER]: {0}{1}", e.Message, e.StackTrace); } httpResponse.StatusCode = (int)HttpStatusCode.BadRequest; } } class BakedTextureUploader { // private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private string m_uploaderPath = String.Empty; private IHttpServer m_httpListener; private UUID m_agentID = UUID.Zero; private IPAddress m_remoteAddress; private IAssetCache m_assetCache; private Timer m_timeout; public BakedTextureUploader(string path, IHttpServer httpServer, UUID agentID, IAssetCache cache, IPAddress remoteAddress) { m_uploaderPath = path; m_httpListener = httpServer; m_agentID = agentID; m_remoteAddress = remoteAddress; m_assetCache = cache; m_timeout = new Timer(); m_timeout.Elapsed += Timeout; m_timeout.AutoReset = false; m_timeout.Interval = 30000; m_timeout.Start(); } private void Timeout(Object source, ElapsedEventArgs e) { m_httpListener.RemoveSimpleStreamHandler(m_uploaderPath); m_timeout.Dispose(); } /// <summary> /// Handle raw uploaded baked texture data. /// </summary> /// <param name="data"></param> /// <param name="path"></param> /// <param name="param"></param> /// <returns></returns> public void process(IOSHttpRequest httpRequest, IOSHttpResponse httpResponse, byte[] data) { m_timeout.Stop(); m_httpListener.RemoveSimpleStreamHandler(m_uploaderPath); m_timeout.Dispose(); if (!httpRequest.RemoteIPEndPoint.Address.Equals(m_remoteAddress)) { httpResponse.StatusCode = (int)HttpStatusCode.Unauthorized; return; } // need to check if data is a baked try { UUID newAssetID = UUID.Random(); AssetBase asset = new AssetBase(newAssetID, "Baked Texture", (sbyte)AssetType.Texture, m_agentID.ToString()); asset.Data = data; asset.Temporary = true; asset.Local = true; //asset.Flags = AssetFlags.AvatarBake; m_assetCache.Cache(asset); LLSDAssetUploadComplete uploadComplete = new LLSDAssetUploadComplete(); uploadComplete.new_asset = newAssetID.ToString(); uploadComplete.new_inventory_item = UUID.Zero; uploadComplete.state = "complete"; httpResponse.RawBuffer = Util.UTF8NBGetbytes(LLSDHelpers.SerialiseLLSDReply(uploadComplete)); httpResponse.StatusCode = (int)HttpStatusCode.OK; return; } catch { } httpResponse.StatusCode = (int)HttpStatusCode.BadRequest; } } }
38.321739
140
0.619923
[ "BSD-3-Clause" ]
AI-Grid/AI-Grid-2.0
OpenSim/Region/ClientStack/Linden/Caps/UploadBakedTextureModule.cs
8,814
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.TestPlatform.Extensions.TrxLogger.UnitTests { using Microsoft.TestPlatform.Extensions.TrxLogger.XML; using Microsoft.VisualStudio.TestTools.UnitTesting; [TestClass] public class XmlPersistenceTests { [TestMethod] public void SaveObjectShouldReplaceInvalidCharacter() { XmlPersistence xmlPersistence = new XmlPersistence(); var node = xmlPersistence.CreateRootElement("TestRun"); // we are handling only #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] char[] invalidXmlCharacterArray = new char[7]; invalidXmlCharacterArray[0] = (char)0x5; invalidXmlCharacterArray[1] = (char)0xb; invalidXmlCharacterArray[2] = (char)0xf; invalidXmlCharacterArray[3] = (char)0xd800; invalidXmlCharacterArray[4] = (char)0xdc00; invalidXmlCharacterArray[5] = (char)0xfffe; invalidXmlCharacterArray[6] = (char)0x0; string strWithInvalidCharForXml = new string(invalidXmlCharacterArray); xmlPersistence.SaveObject(strWithInvalidCharForXml, node, null, "dummy"); string expectedResult = "\\u0005\\u000b\\u000f\\ud800\\udc00\\ufffe\\u0000"; Assert.AreEqual(0, string.Compare(expectedResult, node.InnerXml)); } [TestMethod] public void SaveObjectShouldNotReplaceValidCharacter() { XmlPersistence xmlPersistence = new XmlPersistence(); var node = xmlPersistence.CreateRootElement("TestRun"); // we are handling only #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] char[] validXmlCharacterArray = new char[8]; validXmlCharacterArray[0] = (char)0x9; validXmlCharacterArray[1] = (char)0xa; validXmlCharacterArray[2] = (char)0xd; validXmlCharacterArray[3] = (char)0x20; validXmlCharacterArray[4] = (char)0xc123; validXmlCharacterArray[5] = (char)0xe000; validXmlCharacterArray[6] = (char)0xea12; validXmlCharacterArray[7] = (char)0xfffd; string strWithValidCharForXml = new string(validXmlCharacterArray); xmlPersistence.SaveObject(strWithValidCharForXml, node, null, "dummy"); string expectedResult = "\t\n\r 섣�"; Assert.AreEqual(0, string.Compare(expectedResult, node.InnerXml)); } [TestMethod] public void SaveObjectShouldReplaceOnlyInvalidCharacter() { XmlPersistence xmlPersistence = new XmlPersistence(); var node = xmlPersistence.CreateRootElement("TestRun"); string strWithInvalidCharForXml = "This string has these \0 \v invalid characters"; xmlPersistence.SaveObject(strWithInvalidCharForXml, node, null, "dummy"); string expectedResult = "This string has these \\u0000 \\u000b invalid characters"; Assert.AreEqual(0, string.Compare(expectedResult, node.InnerXml)); } } }
44.680556
101
0.648119
[ "MIT" ]
5259807/vstest
test/Microsoft.TestPlatform.Extensions.TrxLogger.UnitTests/XmlPersistenceTests.cs
3,227
C#
[Serializable] public class Win32Exception : ExternalException, ISerializable // TypeDefIndex: 1820 { // Fields private readonly int nativeErrorCode; // 0x88 private static bool s_ErrorMessagesInitialized; // 0x0 private static Dictionary<int, string> s_ErrorMessage; // 0x8 // Properties public int NativeErrorCode { get; } // Methods // RVA: 0x28E83E0 Offset: 0x28E84E1 VA: 0x28E83E0 public void .ctor() { } // RVA: 0x28E84C0 Offset: 0x28E85C1 VA: 0x28E84C0 public void .ctor(int error) { } // RVA: 0x28E86A0 Offset: 0x28E87A1 VA: 0x28E86A0 public void .ctor(int error, string message) { } // RVA: 0x28E86D0 Offset: 0x28E87D1 VA: 0x28E86D0 protected void .ctor(SerializationInfo info, StreamingContext context) { } // RVA: 0x28E8770 Offset: 0x28E8871 VA: 0x28E8770 public int get_NativeErrorCode() { } // RVA: 0x28E8780 Offset: 0x28E8881 VA: 0x28E8780 Slot: 15 public override void GetObjectData(SerializationInfo info, StreamingContext context) { } // RVA: 0x28E8550 Offset: 0x28E8651 VA: 0x28E8550 internal static string GetErrorMessage(int error) { } // RVA: 0x28E8850 Offset: 0x28E8951 VA: 0x28E8850 private static void InitializeErrorMessages() { } // RVA: 0x28E9C20 Offset: 0x28E9D21 VA: 0x28E9C20 private static void .cctor() { } }
30.428571
89
0.745696
[ "MIT" ]
SinsofSloth/RF5-global-metadata
System/ComponentModel/Win32Exception.cs
1,278
C#
using Newtonsoft.Json.Linq; namespace DevLab.JmesPath.Expressions { public sealed class JmesPathEqualOperator : JmesPathComparison { /// <summary> /// Initialize a new instance of the <see cref="JmesPathEqualOperator"/> class. /// </summary> /// <param name="left"></param> /// <param name="right"></param> public JmesPathEqualOperator(JmesPathExpression left, JmesPathExpression right) : base(left, right) { } protected override bool? Compare(JToken left, JToken right) { return JToken.DeepEquals(left, right); } protected override JmesPathExpression CreateWith(JmesPathExpression left, JmesPathExpression right) => new JmesPathEqualOperator(left, right); } }
32.5
108
0.605917
[ "Apache-2.0" ]
IntranetFactory/JmesPath.Net
src/jmespath.net/Expressions/JmesPathEqualOperator.cs
845
C#
using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; namespace Farenzena.Lib.EventAggregator { public interface IEventHub { void Subscribe(object subscriber); void Unsubscribe(object subscriber); void Publish<TEvent>(TEvent eventToPublish); } }
21.8
52
0.724771
[ "MIT" ]
iurifarenzena/Farenzena.Lib
Farenzena.Lib.EventAggregator/IEventHub.cs
329
C#
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using AloysAdjustments.Common.JsonConverters; using AloysAdjustments.Configuration; using AloysAdjustments.Logic; using AloysAdjustments.Plugins.Common; using AloysAdjustments.Plugins.Common.Characters; using AloysAdjustments.Plugins.Common.Data; using AloysAdjustments.Plugins.NPC; using AloysAdjustments.Plugins.NPC.Characters; using AloysAdjustments.Utility; using HZDCoreEditor.Util; using Newtonsoft.Json; namespace AloysAdjustments.Tools { public class NpcRefGenerator { private const string ResultsFile = "results.json"; private const string ReferencesFile = "npc-refs.json"; private readonly object _lock = new object(); public NpcRefGenerator() { IoC.Bind(Configs.LoadModuleConfig<CommonConfig>(CommonConfig.ConfigName)); } public void SearchDir(string path) { var search = new ByteSearch(path, LoadResults()?.Select(x => x.File)); var charGen = new CharacterGenerator(); var models = charGen.GetCharacterModels(true); models.AddRange(charGen.GetCharacterModels(false)); var modelPatterns = models.Select(x => (x, x.Id.ToBytes())).ToList(); var processed = new BlockingCollection<ByteSearchResult<CharacterModel>>(); TrackProgress(processed); search.Search(modelPatterns, result => { foreach (var item in result.Results) Console.WriteLine($"{item.Key} -> {result.File}"); processed.Add(result); }); processed.CompleteAdding(); var results = LoadResults().Where(x => x.Found); var refs = new Dictionary<Model, HashSet<string>>(); foreach (var result in results) { foreach (var entry in result.Results) { if (!refs.TryGetValue(entry.Key, out var files)) { files = new HashSet<string>(); refs.Add(entry.Key, files); } var fileName = result.File.Substring(path.Length + 1).Replace("\\", "/"); if (fileName.EndsWith(".core")) fileName = fileName.Substring(0, fileName.Length - 5); files.Add(fileName); } } var references = refs.Select(x => new CharacterReference() { Source = x.Key.Source, Name = x.Key.Name, Files = x.Value.ToArray() }); var json = JsonConvert.SerializeObject(references, Formatting.Indented); File.WriteAllText(ReferencesFile, json); } private List<ByteSearchResult<CharacterModel>> LoadResults() { lock (_lock) { List<ByteSearchResult<CharacterModel>> results = null; FileBackup.RunWithBackup(ResultsFile, () => { if (!File.Exists(ResultsFile)) return false; var json = File.ReadAllText(ResultsFile); results = JsonConvert.DeserializeObject<List<ByteSearchResult<CharacterModel>>>(json, JsonHelper.Converters); return true; }); return results; } } private void SaveResults(List<ByteSearchResult<CharacterModel>> results) { lock (_lock) { var json = JsonConvert.SerializeObject(results, Formatting.Indented, JsonHelper.Converters); using (var fb = new FileBackup(ResultsFile)) { File.WriteAllText(ResultsFile, json); fb.Delete(); } } } private void TrackProgress(BlockingCollection<ByteSearchResult<CharacterModel>> processed) { Task.Run(() => { var results = LoadResults() ?? new List<ByteSearchResult<CharacterModel>>(); foreach (var file in processed.GetConsumingEnumerable()) { results.Add(file); if (results.Count % 100 == 0) SaveResults(results); } SaveResults(results); }); } } }
34.533333
105
0.543973
[ "MIT" ]
AkiniKites/AloysAdjustments
src/AloysAdjustments.Tools/CharacterReferences.cs
4,664
C#
using System.Collections.Generic; using UnityEngine; namespace PofyTools { [System.Serializable] public class ProficiencyDefinition : Definition { public ProficiencyDefinition(string id) { this.id = id; } /// <summary> /// Level represents key-value pair collection where key is current level (index + 1) and the value is required points for next level /// </summary> public int[] levels = new int[0]; } [System.Serializable] public class ProficiencyData : DefinableData<ProficiencyDefinition> { #region Constructors public ProficiencyData() { } public ProficiencyData(ProficiencyDefinition definition) : base(definition) { } #endregion #region Serializable Data [SerializeField] private int _currentLevelIndex; public int CurrentLevelIndex { get { return this._currentLevelIndex; } } [SerializeField] public int _currentPointCount; public int CurrentPointCount => this._currentPointCount; #endregion #region API /// <summary> /// Formatted string for displaying current level (index + 1). /// </summary> public string DisplayLevel => (this.HasNextLevel) ? (this._currentLevelIndex + 1).ToString() : (this._currentLevelIndex + 1).ToString() + "(MAX)"; /// <summary> /// Is next level of proficiency available /// </summary> public bool HasNextLevel => this.Definition.levels.Length - 1 > this._currentLevelIndex; /// <summary> /// Required points for next level of proficiency. /// </summary> public int NextLevelRequirements => this.HasNextLevel ? this.Definition.levels[this._currentLevelIndex + 1] : int.MaxValue; public bool AddPoints(int amount = 1) { this._currentPointCount += amount; Debug.Log(this.id + " current point count: " + this._currentPointCount + " current level: " + this.DisplayLevel); return false; } #endregion public void LevelUp() { this._currentLevelIndex++; //this.buff += this.CurrentLevel.value; Debug.Log("Level Up! " + this.id); } public void ApplyPoints() { while (this.HasNextLevel && this._currentPointCount >= this.NextLevelRequirements) { this._currentPointCount -= this.NextLevelRequirements; LevelUp(); } } } [System.Serializable] public class ProficiencyDataSet : DefinableDataSet<ProficiencyData, ProficiencyDefinition> { #region Constructors public ProficiencyDataSet() { } public ProficiencyDataSet(DefinitionSet<ProficiencyDefinition> definitionSet) : base(definitionSet) { } public ProficiencyDataSet(List<ProficiencyDefinition> _content) : base(_content) { } #endregion #region API public void AddPoints(CategoryData.Descriptor descriptor, int amount = 1) { foreach (var superactegory in descriptor.supercategoryIds) { GetValue(superactegory).AddPoints(amount); } var data = GetValue(descriptor.id); if (data != null) { data.AddPoints(amount); return; } Debug.LogErrorFormat("Id \"{0}\" not found!", descriptor.id); } public void ApplyPoints() { foreach (var data in this._content) { data.ApplyPoints(); } } //public void CalculateBuffs(CategoryDataSet categoryDataSet) //{ // //Calculate self buff for each data // foreach (var data in this._content) // { // data.buff = 0f; // data._inheritedBuff = 0f; // for (int i = data.CurrentLevelIndex; i >= 0; --i) // { // data.buff += data.Definition.levels[i].value; // } // } // //add buffs to subcategories // foreach (var data in this._content) // { // foreach (var subId in categoryDataSet.GetValue(data.id).descriptor.subcategoryIds) // { // GetValue(subId)._inheritedBuff += data.buff; // } // } //} #endregion } /// <summary> /// Generic proficiency reward solver. /// </summary> /// <typeparam name="TKey"></typeparam> /// <typeparam name="TValue"></typeparam> public class ProficiencyRewardSolver<TKey, TValue> { //category id public string id; //reward key public TKey key; //reward for each proficiency level public TValue[] values; } }
31.119497
154
0.563662
[ "MIT" ]
PofyTeam/PofyTools
Data/Proficiency.cs
4,950
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.ML.Probabilistic.Learners.Tests { using Microsoft.ML.Probabilistic.Collections; using Microsoft.ML.Probabilistic.Learners.Mappings; using Microsoft.ML.Probabilistic.Math; using System; using System.Collections.Generic; using System.Linq; using Xunit; using Assert = AssertHelper; using LabelDistribution = System.Collections.Generic.IDictionary<string, double>; /// <summary> /// Tests classifier evaluation methods. /// </summary> public class ClassifierEvaluatorTests { #region Test initialization /// <summary> /// Tolerance for comparisons. /// </summary> private const double Tolerance = 1e-15; /// <summary> /// The set of labels. /// </summary> private static readonly string[] LabelSet = { "A", "B", "C" }; /// <summary> /// The ground truth labels. /// </summary> private LabelDistribution[] groundTruth; /// <summary> /// The predictive distributions. /// </summary> private LabelDistribution[] predictions; /// <summary> /// The classifier evaluator. /// </summary> private ClassifierEvaluator<IEnumerable<LabelDistribution>, LabelDistribution, IEnumerable<LabelDistribution>, string> evaluator; /// <summary> /// Prepares the environment before each test. /// </summary> public ClassifierEvaluatorTests() { // Ground truth labels (no uncertainty) this.groundTruth = new LabelDistribution[5]; this.groundTruth[0] = new Dictionary<string, double> { { LabelSet[0], 1 }, { LabelSet[1], 0 }, { LabelSet[2], 0 } }; this.groundTruth[1] = new Dictionary<string, double> { { LabelSet[0], 0 }, { LabelSet[1], 1 }, { LabelSet[2], 0 } }; this.groundTruth[2] = new Dictionary<string, double> { { LabelSet[0], 0 }, { LabelSet[1], 0 }, { LabelSet[2], 1 } }; this.groundTruth[3] = new Dictionary<string, double> { { LabelSet[0], 1 }, { LabelSet[1], 0 }, { LabelSet[2], 0 } }; this.groundTruth[4] = new Dictionary<string, double> { { LabelSet[0], 1 }, { LabelSet[1], 0 }, { LabelSet[2], 0 } }; // Predictions this.predictions = new LabelDistribution[5]; this.predictions[0] = new Dictionary<string, double> { { LabelSet[0], 0 }, { LabelSet[1], 0 }, { LabelSet[2], 1 } }; this.predictions[1] = new Dictionary<string, double> { { LabelSet[0], 0 }, { LabelSet[1], 1 }, { LabelSet[2], 0 } }; this.predictions[2] = new Dictionary<string, double> { { LabelSet[0], 1 }, { LabelSet[1], 0 }, { LabelSet[2], 0 } }; this.predictions[3] = new Dictionary<string, double> { { LabelSet[0], 1 / 6.0 }, { LabelSet[1], 2 / 3.0 }, { LabelSet[2], 1 / 6.0 } }; this.predictions[4] = new Dictionary<string, double> { { LabelSet[0], 1 / 8.0 }, { LabelSet[1], 1 / 8.0 }, { LabelSet[2], 3 / 4.0 } }; // Classifier evaluator var classifierMapping = new ClassifierMapping(); var evaluatorMapping = classifierMapping.ForEvaluation(); this.evaluator = new ClassifierEvaluator<IEnumerable<LabelDistribution>, LabelDistribution, IEnumerable<LabelDistribution>, string>(evaluatorMapping); } #endregion #region Test methods /// <summary> /// Tests correctness of the performance metric evaluation. /// </summary> [Fact] public void PerformanceMetricEvaluationTest() { // Perfect predictions double negativeLogProbability = this.evaluator.Evaluate(this.groundTruth, this.groundTruth, Metrics.NegativeLogProbability); Assert.Equal(0.0, negativeLogProbability); // Imperfect predictions negativeLogProbability = this.evaluator.Evaluate(this.groundTruth, this.predictions, Metrics.NegativeLogProbability); Assert.Equal(double.PositiveInfinity, negativeLogProbability); var uncertainPredictions = new LabelDistribution[5]; uncertainPredictions[0] = new Dictionary<string, double> { { LabelSet[0], 0.5 }, { LabelSet[1], 0.25 }, { LabelSet[2], 0.25 } }; uncertainPredictions[1] = new Dictionary<string, double> { { LabelSet[0], 0 }, { LabelSet[1], 1 }, { LabelSet[2], 0 } }; uncertainPredictions[2] = new Dictionary<string, double> { { LabelSet[0], 0.25 }, { LabelSet[1], 0.25 }, { LabelSet[2], 0.5 } }; uncertainPredictions[3] = new Dictionary<string, double> { { LabelSet[0], 1 / 6.0 }, { LabelSet[1], 2 / 3.0 }, { LabelSet[2], 1 / 6.0 } }; uncertainPredictions[4] = new Dictionary<string, double> { { LabelSet[0], 1 / 8.0 }, { LabelSet[1], 1 / 8.0 }, { LabelSet[2], 3 / 4.0 } }; negativeLogProbability = this.evaluator.Evaluate(this.groundTruth, uncertainPredictions, Metrics.NegativeLogProbability); Assert.Equal(5.2574953720277815, negativeLogProbability, Tolerance); // Insufficient number of predictions var insufficientPredictions = new LabelDistribution[1]; insufficientPredictions[0] = new Dictionary<string, double> { { LabelSet[0], 0.5 }, { LabelSet[1], 0.25 }, { LabelSet[2], 0.25 } }; Assert.Throws<ArgumentException>(() => this.evaluator.Evaluate(this.groundTruth, insufficientPredictions, Metrics.NegativeLogProbability)); } /// <summary> /// Tests correctness of the confusion matrix. /// </summary> [Fact] public void ConfusionMatrixTest() { string expectedConfusionMatrixString = "Truth \\ Prediction ->" + Environment.NewLine + " A B C" + Environment.NewLine + " A 3 0 0" + Environment.NewLine + " B 1 0 0" + Environment.NewLine + " C 1 0 0" + Environment.NewLine; var predictedLabels = new[] { LabelSet[0], LabelSet[0], LabelSet[0], LabelSet[0], LabelSet[0] }; var confusionMatrix = this.evaluator.ConfusionMatrix(this.groundTruth, predictedLabels); // Verify ToString method Assert.Equal(expectedConfusionMatrixString, confusionMatrix.ToString()); // Counts Assert.Equal(3, confusionMatrix[LabelSet[0], LabelSet[0]]); Assert.Equal(0, confusionMatrix[LabelSet[0], LabelSet[1]]); Assert.Equal(0, confusionMatrix[LabelSet[0], LabelSet[2]]); Assert.Equal(1, confusionMatrix[LabelSet[1], LabelSet[0]]); Assert.Equal(0, confusionMatrix[LabelSet[1], LabelSet[1]]); Assert.Equal(0, confusionMatrix[LabelSet[1], LabelSet[2]]); Assert.Equal(1, confusionMatrix[LabelSet[2], LabelSet[0]]); Assert.Equal(0, confusionMatrix[LabelSet[2], LabelSet[1]]); Assert.Equal(0, confusionMatrix[LabelSet[2], LabelSet[2]]); // Precision Assert.Equal(0.6, confusionMatrix.Precision(LabelSet[0])); Assert.Equal(double.NaN, confusionMatrix.Precision(LabelSet[1])); // undefined result Assert.Equal(double.NaN, confusionMatrix.Precision(LabelSet[2])); // undefined result Assert.Equal(0.6, confusionMatrix.MacroPrecision); Assert.Equal(0.36, confusionMatrix.MicroPrecision); // Recall Assert.Equal(1, confusionMatrix.Recall(LabelSet[0])); Assert.Equal(0, confusionMatrix.Recall(LabelSet[1])); Assert.Equal(0, confusionMatrix.Recall(LabelSet[2])); Assert.Equal(1 / 3.0, confusionMatrix.MacroRecall); Assert.Equal(0.6, confusionMatrix.MicroRecall); // Accuracy Assert.Equal(1, confusionMatrix.Accuracy(LabelSet[0])); Assert.Equal(0, confusionMatrix.Accuracy(LabelSet[1])); Assert.Equal(0, confusionMatrix.Accuracy(LabelSet[2])); Assert.Equal(1 / 3.0, confusionMatrix.MacroAccuracy); Assert.Equal(0.6, confusionMatrix.MicroAccuracy); // F1-measure Assert.Equal(0.75, confusionMatrix.F1(LabelSet[0]), Tolerance); Assert.Equal(double.NaN, confusionMatrix.F1(LabelSet[1])); // undefined result Assert.Equal(double.NaN, confusionMatrix.F1(LabelSet[2])); // undefined result Assert.Equal(0.75, confusionMatrix.MacroF1, Tolerance); Assert.Equal(0.45, confusionMatrix.MicroF1, Tolerance); } /// <summary> /// Tests correctness of the receiver operating characteristic curve (ROC). /// </summary> [Fact] public void RocCurveTest() { // Curve for perfect predictions var expected = new[] { new FalseAndTruePositiveRate(0.0, 0.0), new FalseAndTruePositiveRate(0.0, 1.0), new FalseAndTruePositiveRate(1.0, 1.0) }; var actual = this.evaluator.ReceiverOperatingCharacteristicCurve(LabelSet[0], this.groundTruth, this.groundTruth).ToArray(); Xunit.Assert.Equal(expected, actual); // Curve for imperfect predictions (one-versus-rest) expected = new[] { new FalseAndTruePositiveRate(0.0, 0.0), new FalseAndTruePositiveRate(0.5, 0.0), new FalseAndTruePositiveRate(0.5, 1 / 3.0), new FalseAndTruePositiveRate(0.5, 2 / 3.0), new FalseAndTruePositiveRate(1.0, 1.0) }; actual = this.evaluator.ReceiverOperatingCharacteristicCurve(LabelSet[0], this.groundTruth, this.predictions).ToArray(); Xunit.Assert.Equal(expected, actual); // matches below AUC = 5/12 // Curve for imperfect predictions (one-versus-another) expected = new[] { new FalseAndTruePositiveRate(0.0, 0.0), new FalseAndTruePositiveRate(0.0, 1 / 3.0), new FalseAndTruePositiveRate(0.0, 2 / 3.0), new FalseAndTruePositiveRate(1.0, 1.0) }; actual = this.evaluator.ReceiverOperatingCharacteristicCurve(LabelSet[0], LabelSet[1], this.groundTruth, this.predictions).ToArray(); Xunit.Assert.Equal(expected, actual); // matches below AUC = 5/6 // No positive or negative class labels var actualLabelDistribution = new LabelDistribution[1]; actualLabelDistribution[0] = new Dictionary<string, double> { { LabelSet[0], 1 }, { LabelSet[1], 0 }, { LabelSet[2], 0 } }; // One-versus-rest Assert.Throws<ArgumentException>(() => this.evaluator.ReceiverOperatingCharacteristicCurve(LabelSet[0], actualLabelDistribution, actualLabelDistribution)); Assert.Throws<ArgumentException>(() => this.evaluator.ReceiverOperatingCharacteristicCurve(LabelSet[1], actualLabelDistribution, actualLabelDistribution)); Assert.Throws<ArgumentException>(() => this.evaluator.ReceiverOperatingCharacteristicCurve(LabelSet[2], actualLabelDistribution, actualLabelDistribution)); // One-versus-another Assert.Throws<ArgumentException>(() => this.evaluator.ReceiverOperatingCharacteristicCurve(LabelSet[0], LabelSet[2], actualLabelDistribution, actualLabelDistribution)); Assert.Throws<ArgumentException>(() => this.evaluator.ReceiverOperatingCharacteristicCurve(LabelSet[1], LabelSet[0], actualLabelDistribution, actualLabelDistribution)); Assert.Throws<ArgumentException>(() => this.evaluator.ReceiverOperatingCharacteristicCurve(LabelSet[2], LabelSet[1], actualLabelDistribution, actualLabelDistribution)); // Positive and negative class labels are identical Assert.Throws<ArgumentException>(() => this.evaluator.ReceiverOperatingCharacteristicCurve(LabelSet[0], LabelSet[0], actualLabelDistribution, actualLabelDistribution)); } /// <summary> /// Tests correctness of the precision-recall curve. /// </summary> [Fact] public void PrecisionRecallCurveTest() { // Curve for perfect predictions var expected = new[] { new PrecisionRecall(1.0, 0.0), new PrecisionRecall(1.0, 1 / 3.0), new PrecisionRecall(1.0, 2 / 3.0), new PrecisionRecall(1.0, 1.0), new PrecisionRecall(0.75, 1.0), new PrecisionRecall(0.6, 1.0) }; var actual = this.evaluator.PrecisionRecallCurve(LabelSet[0], this.groundTruth, this.groundTruth).ToArray(); Xunit.Assert.Equal(expected, actual); // Curve for imperfect predictions (one-versus-rest) expected = new[] { new PrecisionRecall(1.0, 0.0), new PrecisionRecall(0.0, 0.0), new PrecisionRecall(0.5, 1 / 3.0), new PrecisionRecall(2 / 3.0, 2 / 3.0), new PrecisionRecall(0.75, 1.0), new PrecisionRecall(0.6, 1.0) }; actual = this.evaluator.PrecisionRecallCurve(LabelSet[0], this.groundTruth, this.predictions).ToArray(); Xunit.Assert.Equal(expected, actual); // Curve for imperfect predictions (one-versus-another) expected = new[] { new PrecisionRecall(1.0, 0.0), new PrecisionRecall(1.0, 1.0), new PrecisionRecall(0.5, 1.0) }; actual = this.evaluator.PrecisionRecallCurve(LabelSet[1], LabelSet[2], this.groundTruth, this.predictions).ToArray(); Xunit.Assert.Equal(expected, actual); // No positive class labels var actualLabelDistribution = new LabelDistribution[1]; actualLabelDistribution[0] = new Dictionary<string, double> { { LabelSet[0], 1 }, { LabelSet[1], 0 }, { LabelSet[2], 0 } }; // One-versus-rest Assert.Throws<ArgumentException>(() => this.evaluator.PrecisionRecallCurve(LabelSet[1], actualLabelDistribution, actualLabelDistribution)); Assert.Throws<ArgumentException>(() => this.evaluator.PrecisionRecallCurve(LabelSet[2], actualLabelDistribution, actualLabelDistribution)); // One-versus-another Assert.Throws<ArgumentException>(() => this.evaluator.PrecisionRecallCurve(LabelSet[1], LabelSet[0], actualLabelDistribution, actualLabelDistribution)); Assert.Throws<ArgumentException>(() => this.evaluator.PrecisionRecallCurve(LabelSet[2], LabelSet[0], actualLabelDistribution, actualLabelDistribution)); // Positive and negative class labels are identical Assert.Throws<ArgumentException>(() => this.evaluator.PrecisionRecallCurve(LabelSet[0], LabelSet[0], actualLabelDistribution, actualLabelDistribution)); } /// <summary> /// Tests correctness of the calibration curve. /// </summary> [Fact] public void CalibrationCurveTest() { // Curve for perfect predictions var expected = new[] { new CalibrationPair(0.25, 0.0), new CalibrationPair(0.75, 1.0) }; var actual = this.evaluator.CalibrationCurve(LabelSet[0], this.groundTruth, this.groundTruth).ToArray(); Xunit.Assert.Equal(expected, actual); // Curve for imperfect predictions (one-versus-rest) expected = new[] { new CalibrationPair(0.25, 0.75), new CalibrationPair(0.75, 0.0) }; actual = this.evaluator.CalibrationCurve(LabelSet[0], this.groundTruth, this.predictions).ToArray(); Xunit.Assert.Equal(expected, actual); // Curve for imperfect predictions (3 bins) const int BinCount = 4; expected = new[] { new CalibrationPair(1 / 8.0, 0.75), new CalibrationPair(7 / 8.0, 0.0) }; actual = this.evaluator.CalibrationCurve(LabelSet[0], this.groundTruth, this.predictions, BinCount).ToArray(); Xunit.Assert.Equal(expected, actual); // Ground truth instances without corresponding predictions var insufficientPredictions = new LabelDistribution[1]; insufficientPredictions[0] = this.predictions[0]; Assert.Throws<ArgumentException>(() => this.evaluator.CalibrationCurve(LabelSet[0], this.groundTruth, insufficientPredictions)); } /// <summary> /// Tests correctness of the area under the receiver operating characteristic curve (AUC). /// </summary> [Fact] public void AreaUnderRocCurveTest() { // AUC for perfect predictions // Per-label AUC Assert.Equal(1.0, this.evaluator.AreaUnderRocCurve(LabelSet[0], this.groundTruth, this.groundTruth)); Assert.Equal(1.0, this.evaluator.AreaUnderRocCurve(LabelSet[1], this.groundTruth, this.groundTruth)); Assert.Equal(1.0, this.evaluator.AreaUnderRocCurve(LabelSet[2], this.groundTruth, this.groundTruth)); // M-measure IDictionary<string, IDictionary<string, double>> computedAucMatrix; Assert.Equal(1.0, this.evaluator.AreaUnderRocCurve(this.groundTruth, this.groundTruth, out computedAucMatrix)); Assert.Equal(1.0, this.evaluator.AreaUnderRocCurve(this.groundTruth, this.groundTruth)); // Pairwise AUC (upper triangle) Assert.Equal(1.0, computedAucMatrix[LabelSet[0]][LabelSet[1]]); Assert.Equal(1.0, computedAucMatrix[LabelSet[0]][LabelSet[2]]); Assert.Equal(1.0, computedAucMatrix[LabelSet[1]][LabelSet[2]]); // Pairwise AUC (diagnonal) foreach (string label in LabelSet) { Assert.Equal(double.NaN, computedAucMatrix[label][label]); // undefined result } // Pairwise AUC (lower triangle) Assert.Equal(1.0, computedAucMatrix[LabelSet[1]][LabelSet[0]]); Assert.Equal(1.0, computedAucMatrix[LabelSet[2]][LabelSet[0]]); Assert.Equal(1.0, computedAucMatrix[LabelSet[2]][LabelSet[1]]); // AUC for imperfect predictions // Per-label AUC Assert.Equal(5 / 12.0, this.evaluator.AreaUnderRocCurve(LabelSet[0], this.groundTruth, this.predictions)); // matches ROC curve Assert.Equal(1.0, this.evaluator.AreaUnderRocCurve(LabelSet[1], this.groundTruth, this.predictions)); Assert.Equal(1 / 8.0, this.evaluator.AreaUnderRocCurve(LabelSet[2], this.groundTruth, this.predictions)); // M-measure Assert.Equal(5 / 9.0, this.evaluator.AreaUnderRocCurve(this.groundTruth, this.predictions, out computedAucMatrix)); Assert.Equal(5 / 9.0, this.evaluator.AreaUnderRocCurve(this.groundTruth, this.predictions)); // Pairwise AUC (upper triangle) Assert.Equal(5 / 6.0, computedAucMatrix[LabelSet[0]][LabelSet[1]]); // matches ROC curve Assert.Equal(0.0, computedAucMatrix[LabelSet[0]][LabelSet[2]]); Assert.Equal(1.0, computedAucMatrix[LabelSet[1]][LabelSet[2]]); // Pairwise AUC (diagnonal) foreach (string label in LabelSet) { Assert.Equal(double.NaN, computedAucMatrix[label][label]); // undefined result } // Pairwise AUC (lower triangle) Assert.Equal(1.0, computedAucMatrix[LabelSet[1]][LabelSet[0]]); Assert.Equal(0.0, computedAucMatrix[LabelSet[2]][LabelSet[0]]); Assert.Equal(0.5, computedAucMatrix[LabelSet[2]][LabelSet[1]]); // Test code path for symmetric two-class case var binaryGroundTruth = new LabelDistribution[2]; binaryGroundTruth[0] = new Dictionary<string, double> { { LabelSet[0], 1 }, { LabelSet[1], 0 } }; binaryGroundTruth[1] = new Dictionary<string, double> { { LabelSet[0], 0 }, { LabelSet[1], 1 } }; var binaryPredictions = new LabelDistribution[2]; binaryPredictions[0] = new Dictionary<string, double> { { LabelSet[0], 0.9 }, { LabelSet[1], 0.1 } }; binaryPredictions[1] = new Dictionary<string, double> { { LabelSet[0], 0.8 }, { LabelSet[1], 0.2 } }; Assert.Equal(1.0, this.evaluator.AreaUnderRocCurve(binaryGroundTruth, binaryPredictions, out computedAucMatrix)); Assert.Equal(1.0, this.evaluator.AreaUnderRocCurve(binaryGroundTruth, binaryPredictions)); Assert.Equal(double.NaN, computedAucMatrix[LabelSet[0]][LabelSet[0]]); // undefined result Assert.Equal(1.0, computedAucMatrix[LabelSet[0]][LabelSet[1]]); Assert.Equal(1.0, computedAucMatrix[LabelSet[1]][LabelSet[0]]); Assert.Equal(double.NaN, computedAucMatrix[LabelSet[1]][LabelSet[1]]); // undefined result // No positive or negative class labels var actualLabelDistribution = new LabelDistribution[1]; actualLabelDistribution[0] = new Dictionary<string, double> { { LabelSet[0], 1 }, { LabelSet[1], 0 }, { LabelSet[2], 0 } }; // One-versus-rest Assert.Throws<ArgumentException>(() => this.evaluator.AreaUnderRocCurve(LabelSet[0], actualLabelDistribution, actualLabelDistribution)); Assert.Throws<ArgumentException>(() => this.evaluator.AreaUnderRocCurve(LabelSet[1], actualLabelDistribution, actualLabelDistribution)); Assert.Throws<ArgumentException>(() => this.evaluator.AreaUnderRocCurve(LabelSet[2], actualLabelDistribution, actualLabelDistribution)); // One-versus-another Assert.Throws<ArgumentException>(() => this.evaluator.AreaUnderRocCurve(LabelSet[0], LabelSet[2], actualLabelDistribution, actualLabelDistribution)); Assert.Throws<ArgumentException>(() => this.evaluator.AreaUnderRocCurve(LabelSet[1], LabelSet[0], actualLabelDistribution, actualLabelDistribution)); Assert.Throws<ArgumentException>(() => this.evaluator.AreaUnderRocCurve(LabelSet[2], LabelSet[1], actualLabelDistribution, actualLabelDistribution)); // Positive and negative class labels are identical Assert.Throws<ArgumentException>(() => this.evaluator.ReceiverOperatingCharacteristicCurve(LabelSet[0], LabelSet[0], actualLabelDistribution, actualLabelDistribution)); } #endregion #region IClassifierMapping implementation /// <summary> /// The classifier mapping. /// </summary> private class ClassifierMapping : IClassifierMapping<IEnumerable<LabelDistribution>, LabelDistribution, IEnumerable<LabelDistribution>, string, Vector> { /// <summary> /// Provides the instances for a given instance source. /// </summary> /// <param name="instanceSource">The source of instances.</param> /// <returns>The instances provided by the instance source.</returns> /// <remarks>Assumes that the same instance source always provides the same instances.</remarks> public IEnumerable<LabelDistribution> GetInstances(IEnumerable<LabelDistribution> instanceSource) { if (instanceSource == null) { throw new ArgumentNullException(nameof(instanceSource)); } return instanceSource; } /// <summary> /// Provides the features for a given instance. /// </summary> /// <param name="instance">The instance to provide features for.</param> /// <param name="instanceSource">An optional source of instances.</param> /// <returns>The features for the given instance.</returns> /// <remarks>Assumes that the same instance source always provides the same features for a given instance.</remarks> public Vector GetFeatures(LabelDistribution instance, IEnumerable<LabelDistribution> instanceSource = null) { throw new NotImplementedException("Features are not required in evaluation."); } /// <summary> /// Provides the label for a given instance. /// </summary> /// <param name="instance">The instance to provide the label for.</param> /// <param name="instanceSource">An optional source of instances.</param> /// <param name="labelSource">An optional source of labels.</param> /// <returns>The label of the given instance.</returns> /// <remarks>Assumes that the same sources always provide the same label for a given instance.</remarks> public string GetLabel(LabelDistribution instance, IEnumerable<LabelDistribution> instanceSource = null, IEnumerable<LabelDistribution> labelSource = null) { if (instance == null) { throw new ArgumentNullException(nameof(instance)); } // Use zero-one loss function to determine point estimate (mode of distribution) string mode = string.Empty; double maximum = double.NegativeInfinity; foreach (var element in instance) { if (element.Value > maximum) { maximum = element.Value; mode = element.Key; } } return mode; } /// <summary> /// Gets all class labels. /// </summary> /// <param name="instanceSource">An optional instance source.</param> /// <param name="labelSource">An optional label source.</param> /// <returns>All possible values of a label.</returns> public IEnumerable<string> GetClassLabels(IEnumerable<LabelDistribution> instanceSource = null, IEnumerable<LabelDistribution> labelSource = null) { if (instanceSource == null) { throw new ArgumentNullException(nameof(instanceSource)); } return new HashSet<string>(instanceSource.SelectMany(instance => instance.Keys)); } } #endregion } }
57.353712
240
0.627836
[ "MIT" ]
RinSer/infer
test/Learners/LearnersTests/ClassifierEvaluatorTests.cs
26,268
C#
using System; using System.Collections.Generic; namespace Com.Ctrip.Framework.Apollo.Core.Utils { public static class CollectionUtil { public static bool IsNullOrEmpty<T>(List<T> list) { return list == null || list.Count == 0; } public static V TryGet<K, V>(IDictionary<K, V> d, K key) { V result = default(V); if (d == null || key == null) { return result; } else { d.TryGetValue(key, out result); return result; } } public static void Shuffle<T>(this IList<T> list) { Random rnd = new Random(); int n = list.Count; while (n > 1) { n--; int k = rnd.Next(n + 1); T value = list[k]; list[k] = list[n]; list[n] = value; } } } }
21.782609
64
0.41517
[ "Apache-2.0" ]
307209239/apollo-net
Apollo/Core/Utils/CollectionUtil.cs
1,004
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.Design; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Drawing; using System.Drawing.Design; using System.Reflection; using System.Security; using System.Security.Permissions; using System.Windows.Forms.Design.Behavior; using Microsoft.Win32; namespace System.Windows.Forms.Design { internal sealed class ToolStripDesignerUtils { private static readonly Type s_toolStripItemType = typeof(ToolStripItem); [ThreadStatic] private static Dictionary<Type, ToolboxItem> s_cachedToolboxItems; [ThreadStatic] private static int s_customToolStripItemCount = 0; private const int TOOLSTRIPCHARCOUNT = 9; // used to cache in the selection. This is used when the selection is changing and we need to invalidate the original selection Especially, when the selection is changed through NON UI designer action like through propertyGrid or through Doc Outline. public static ArrayList originalSelComps; [ThreadStatic] private static Dictionary<Type, Bitmap> s_cachedWinformsImages; private static string s_systemWindowsFormsNamespace = typeof(ToolStripItem).Namespace; private ToolStripDesignerUtils() { } #region NewItemTypeLists // This section controls the ordering of standard item types in all the various pieces of toolstrip designer UI. // ToolStrip - Default item is determined by being first in the list private static readonly Type[] s_newItemTypesForToolStrip = new Type[]{typeof(ToolStripButton), typeof(ToolStripLabel), typeof(ToolStripSplitButton), typeof(ToolStripDropDownButton), typeof(ToolStripSeparator), typeof(ToolStripComboBox), typeof(ToolStripTextBox), typeof(ToolStripProgressBar)}; // StatusStrip - Default item is determined by being first in the list private static readonly Type[] s_newItemTypesForStatusStrip = new Type[]{typeof(ToolStripStatusLabel), typeof(ToolStripProgressBar), typeof(ToolStripDropDownButton), typeof(ToolStripSplitButton)}; // MenuStrip - Default item is determined by being first in the list private static readonly Type[] s_newItemTypesForMenuStrip = new Type[]{typeof(ToolStripMenuItem), typeof(ToolStripComboBox), typeof(ToolStripTextBox)}; // ToolStripDropDown - roughly same as menu strip. private static readonly Type[] s_newItemTypesForToolStripDropDownMenu = new Type[]{typeof(ToolStripMenuItem), typeof(ToolStripComboBox), typeof(ToolStripSeparator), typeof(ToolStripTextBox)}; #endregion // Get the Correct bounds for painting... [SuppressMessage("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily")] public static void GetAdjustedBounds(ToolStripItem item, ref Rectangle r) { // adjust bounds as per item if (!(item is ToolStripControlHost && item.IsOnDropDown)) { //Deflate the SelectionGlyph for the MenuItems... if (item is ToolStripMenuItem && item.IsOnDropDown) { r.Inflate(-3, -2); r.Width++; } else if (item is ToolStripControlHost && !item.IsOnDropDown) { r.Inflate(0, -2); } else if (item is ToolStripMenuItem && !item.IsOnDropDown) { r.Inflate(-3, -3); } else { r.Inflate(-1, -1); } } } /// <summary> /// If IComponent is ToolStrip return ToolStrip /// If IComponent is ToolStripItem return the Owner ToolStrip /// If IComponent is ToolStripDropDownItem return the child DropDown ToolStrip /// </summary> private static ToolStrip GetToolStripFromComponent(IComponent component) { ToolStrip parent; if (component is ToolStripItem stripItem) { if (!(stripItem is ToolStripDropDownItem)) { parent = stripItem.Owner; } else { parent = ((ToolStripDropDownItem)stripItem).DropDown; } } else { parent = component as ToolStrip; } return parent; } private static ToolboxItem GetCachedToolboxItem(Type itemType) { ToolboxItem tbxItem = null; if (s_cachedToolboxItems == null) { s_cachedToolboxItems = new Dictionary<Type, ToolboxItem>(); } else if (s_cachedToolboxItems.ContainsKey(itemType)) { tbxItem = s_cachedToolboxItems[itemType]; return tbxItem; } // no cache hit - load the item. if (tbxItem == null) { // create a toolbox item to match tbxItem = new ToolboxItem(itemType); } s_cachedToolboxItems[itemType] = tbxItem; if (s_customToolStripItemCount > 0 && (s_customToolStripItemCount * 2 < s_cachedToolboxItems.Count)) { // time to clear the toolbox item cache - we've got twice the number of toolbox items than actual custom item types. s_cachedToolboxItems.Clear(); } return tbxItem; } // only call this for well known items. private static Bitmap GetKnownToolboxBitmap(Type itemType) { if (s_cachedWinformsImages == null) { s_cachedWinformsImages = new Dictionary<Type, Bitmap>(); } if (!s_cachedWinformsImages.ContainsKey(itemType)) { Bitmap knownImage = ToolboxBitmapAttribute.GetImageFromResource(itemType, null, false) as Bitmap; s_cachedWinformsImages[itemType] = knownImage; return knownImage; } return s_cachedWinformsImages[itemType]; } public static Bitmap GetToolboxBitmap(Type itemType) { // if and only if the namespace of the type is System.Windows.Forms. try to pull the image out of the manifest. if (itemType.Namespace == s_systemWindowsFormsNamespace) { return GetKnownToolboxBitmap(itemType); } // check to see if we've got a toolbox item, and use it. ToolboxItem tbxItem = GetCachedToolboxItem(itemType); if (tbxItem != null) { return tbxItem.Bitmap; } // if all else fails, throw up a default image. return GetKnownToolboxBitmap(typeof(Component)); } /// <summary> /// Fishes out the display name attribute from the Toolbox item if not present, uses Type.Name /// </summary> public static string GetToolboxDescription(Type itemType) { string currentName = null; ToolboxItem tbxItem = GetCachedToolboxItem(itemType); if (tbxItem != null) { currentName = tbxItem.DisplayName; } if (currentName == null) { currentName = itemType.Name; } if (currentName.StartsWith("ToolStrip")) { return currentName.Substring(TOOLSTRIPCHARCOUNT); } return currentName; } /// <summary> /// The first item returned should be the DefaultItem to create on the ToolStrip /// </summary> public static Type[] GetStandardItemTypes(IComponent component) { ToolStrip toolStrip = GetToolStripFromComponent(component); if (toolStrip is MenuStrip) { return s_newItemTypesForMenuStrip; } else if (toolStrip is ToolStripDropDownMenu) { // ToolStripDropDown gets default items. return s_newItemTypesForToolStripDropDownMenu; } else if (toolStrip is StatusStrip) { return s_newItemTypesForStatusStrip; } Debug.Assert(toolStrip != null, "why werent we handed a toolstrip here? returning default list"); return s_newItemTypesForToolStrip; } private static ToolStripItemDesignerAvailability GetDesignerVisibility(ToolStrip toolStrip) { ToolStripItemDesignerAvailability visiblity; if (toolStrip is StatusStrip) { visiblity = ToolStripItemDesignerAvailability.StatusStrip; } else if (toolStrip is MenuStrip) { visiblity = ToolStripItemDesignerAvailability.MenuStrip; } else if (toolStrip is ToolStripDropDownMenu) { visiblity = ToolStripItemDesignerAvailability.ContextMenuStrip; } else { visiblity = ToolStripItemDesignerAvailability.ToolStrip; } return visiblity; } public static Type[] GetCustomItemTypes(IComponent component, IServiceProvider serviceProvider) { ITypeDiscoveryService discoveryService = null; if (serviceProvider != null) { discoveryService = serviceProvider.GetService(typeof(ITypeDiscoveryService)) as ITypeDiscoveryService; } return GetCustomItemTypes(component, discoveryService); } public static Type[] GetCustomItemTypes(IComponent component, ITypeDiscoveryService discoveryService) { if (discoveryService != null) { // fish out all types which derive from toolstrip item ICollection itemTypes = discoveryService.GetTypes(s_toolStripItemType, false /*excludeGlobalTypes*/); ToolStrip toolStrip = GetToolStripFromComponent(component); // determine the value of the visibility attribute which matches the current toolstrip type. ToolStripItemDesignerAvailability currentToolStripVisibility = GetDesignerVisibility(toolStrip); Debug.Assert(currentToolStripVisibility != ToolStripItemDesignerAvailability.None, "Why is GetDesignerVisibility returning None?"); // fish out the ones we've already listed. Type[] stockItemTypeList = GetStandardItemTypes(component); if (currentToolStripVisibility != ToolStripItemDesignerAvailability.None) { ArrayList createableTypes = new ArrayList(itemTypes.Count); foreach (Type t in itemTypes) { if (t.IsAbstract) { continue; } if (!t.IsPublic && !t.IsNestedPublic) { continue; } if (t.ContainsGenericParameters) { continue; } // Check if we have public constructor... ConstructorInfo ctor = t.GetConstructor(new Type[0]); if (ctor == null) { continue; } // if the visibility matches the current toolstrip type, add it to the list of possible types to create. ToolStripItemDesignerAvailabilityAttribute visiblityAttribute = (ToolStripItemDesignerAvailabilityAttribute)TypeDescriptor.GetAttributes(t)[typeof(ToolStripItemDesignerAvailabilityAttribute)]; if (visiblityAttribute != null && ((visiblityAttribute.ItemAdditionVisibility & currentToolStripVisibility) == currentToolStripVisibility)) { bool isStockType = false; // PERF: consider a dictionary - but this list will usually be 3-7 items. foreach (Type stockType in stockItemTypeList) { if (stockType == t) { isStockType = true; break; } } if (!isStockType) { createableTypes.Add(t); } } } if (createableTypes.Count > 0) { Type[] createableTypesArray = new Type[createableTypes.Count]; createableTypes.CopyTo(createableTypesArray, 0); s_customToolStripItemCount = createableTypes.Count; return createableTypesArray; } } } s_customToolStripItemCount = 0; return new Type[0]; } /// <summary> /// wraps the result of GetStandardItemTypes in ItemTypeToolStripMenuItems. /// </summary> public static ToolStripItem[] GetStandardItemMenuItems(IComponent component, EventHandler onClick, bool convertTo) { Type[] standardTypes = GetStandardItemTypes(component); ToolStripItem[] items = new ToolStripItem[standardTypes.Length]; for (int i = 0; i < standardTypes.Length; i++) { ItemTypeToolStripMenuItem item = new ItemTypeToolStripMenuItem(standardTypes[i]) { ConvertTo = convertTo }; if (onClick != null) { item.Click += onClick; } items[i] = item; } return items; } /// <summary> /// wraps the result of GetCustomItemTypes in ItemTypeToolStripMenuItems. /// </summary> public static ToolStripItem[] GetCustomItemMenuItems(IComponent component, EventHandler onClick, bool convertTo, IServiceProvider serviceProvider) { Type[] customTypes = GetCustomItemTypes(component, serviceProvider); ToolStripItem[] items = new ToolStripItem[customTypes.Length]; for (int i = 0; i < customTypes.Length; i++) { ItemTypeToolStripMenuItem item = new ItemTypeToolStripMenuItem(customTypes[i]) { ConvertTo = convertTo }; if (onClick != null) { item.Click += onClick; } items[i] = item; } return items; } /// <summary> /// build up a list of standard items separated by the custom items /// </summary> public static NewItemsContextMenuStrip GetNewItemDropDown(IComponent component, ToolStripItem currentItem, EventHandler onClick, bool convertTo, IServiceProvider serviceProvider, bool populateCustom) { NewItemsContextMenuStrip contextMenu = new NewItemsContextMenuStrip(component, currentItem, onClick, convertTo, serviceProvider); contextMenu.GroupOrdering.Add("StandardList"); contextMenu.GroupOrdering.Add("CustomList"); // plumb through the standard and custom items. foreach (ToolStripItem item in GetStandardItemMenuItems(component, onClick, convertTo)) { contextMenu.Groups["StandardList"].Items.Add(item); if (convertTo) { if (item is ItemTypeToolStripMenuItem toolItem && currentItem != null && toolItem.ItemType == currentItem.GetType()) { toolItem.Enabled = false; } } } if (populateCustom) { GetCustomNewItemDropDown(contextMenu, component, currentItem, onClick, convertTo, serviceProvider); } if (serviceProvider.GetService(typeof(IUIService)) is IUIService uis) { contextMenu.Renderer = (ToolStripProfessionalRenderer)uis.Styles["VsRenderer"]; contextMenu.Font = (Font)uis.Styles["DialogFont"]; if (uis.Styles["VsColorPanelText"] is Color) { contextMenu.ForeColor = (Color)uis.Styles["VsColorPanelText"]; } } contextMenu.Populate(); return contextMenu; } public static void GetCustomNewItemDropDown(NewItemsContextMenuStrip contextMenu, IComponent component, ToolStripItem currentItem, EventHandler onClick, bool convertTo, IServiceProvider serviceProvider) { foreach (ToolStripItem item in GetCustomItemMenuItems(component, onClick, convertTo, serviceProvider)) { contextMenu.Groups["CustomList"].Items.Add(item); if (convertTo) { if (item is ItemTypeToolStripMenuItem toolItem && currentItem != null && toolItem.ItemType == currentItem.GetType()) { toolItem.Enabled = false; } } } contextMenu.Populate(); } public static void InvalidateSelection(ArrayList originalSelComps, ToolStripItem nextSelection, IServiceProvider provider, bool shiftPressed) { // if we are not selecting a ToolStripItem then return (dont invalidate). if (nextSelection == null || provider == null) { return; } //InvalidateOriginal SelectedComponents. Region invalidateRegion = null; Region itemRegion = null; int GLYPHBORDER = 1; int GLYPHINSET = 2; ToolStripItemDesigner designer = null; bool templateNodeSelected = false; try { Rectangle invalidateBounds = Rectangle.Empty; IDesignerHost designerHost = (IDesignerHost)provider.GetService(typeof(IDesignerHost)); if (designerHost != null) { foreach (Component comp in originalSelComps) { if (comp is ToolStripItem selItem) { if ((originalSelComps.Count > 1) || (originalSelComps.Count == 1 && selItem.GetCurrentParent() != nextSelection.GetCurrentParent()) || selItem is ToolStripSeparator || selItem is ToolStripControlHost || !selItem.IsOnDropDown || selItem.IsOnOverflow) { // finally Invalidate the selection rect ... designer = designerHost.GetDesigner(selItem) as ToolStripItemDesigner; if (designer != null) { invalidateBounds = designer.GetGlyphBounds(); GetAdjustedBounds(selItem, ref invalidateBounds); invalidateBounds.Inflate(GLYPHBORDER, GLYPHBORDER); if (invalidateRegion == null) { invalidateRegion = new Region(invalidateBounds); invalidateBounds.Inflate(-GLYPHINSET, -GLYPHINSET); invalidateRegion.Exclude(invalidateBounds); } else { itemRegion = new Region(invalidateBounds); invalidateBounds.Inflate(-GLYPHINSET, -GLYPHINSET); itemRegion.Exclude(invalidateBounds); invalidateRegion.Union(itemRegion); } } } } } } if (invalidateRegion != null || templateNodeSelected || shiftPressed) { BehaviorService behaviorService = (BehaviorService)provider.GetService(typeof(BehaviorService)); if (behaviorService != null) { if (invalidateRegion != null) { behaviorService.Invalidate(invalidateRegion); } // When a ToolStripItem is PrimarySelection, the glyph bounds are not invalidated through the SelectionManager so we have to do this. designer = designerHost.GetDesigner(nextSelection) as ToolStripItemDesigner; if (designer != null) { invalidateBounds = designer.GetGlyphBounds(); GetAdjustedBounds(nextSelection, ref invalidateBounds); invalidateBounds.Inflate(GLYPHBORDER, GLYPHBORDER); invalidateRegion = new Region(invalidateBounds); invalidateBounds.Inflate(-GLYPHINSET, -GLYPHINSET); invalidateRegion.Exclude(invalidateBounds); behaviorService.Invalidate(invalidateRegion); } } } } finally { if (invalidateRegion != null) { invalidateRegion.Dispose(); } if (itemRegion != null) { itemRegion.Dispose(); } } } /// <summary> represents cached information about the display</summary> internal static class DisplayInformation { private static bool s_highContrast; //whether we are under hight contrast mode private static bool s_lowRes; //whether we are under low resolution mode private static bool s_isTerminalServerSession; //whether this application is run on a terminal server (remote desktop) private static bool s_highContrastSettingValid; //indicates whether the high contrast setting is correct private static bool s_lowResSettingValid; //indicates whether the low resolution setting is correct private static bool s_terminalSettingValid; //indicates whether the terminal server setting is correct private static short s_bitsPerPixel; private static bool s_dropShadowSettingValid; private static bool s_dropShadowEnabled; static DisplayInformation() { SystemEvents.UserPreferenceChanged += new UserPreferenceChangedEventHandler(UserPreferenceChanged); SystemEvents.DisplaySettingsChanged += new EventHandler(DisplaySettingChanged); } public static short BitsPerPixel { get { if (s_bitsPerPixel == 0) { new EnvironmentPermission(PermissionState.Unrestricted).Assert(); try { foreach (Screen s in Screen.AllScreens) { if (s_bitsPerPixel == 0) { s_bitsPerPixel = (short)s.BitsPerPixel; } else { s_bitsPerPixel = (short)Math.Min(s.BitsPerPixel, s_bitsPerPixel); } } } finally { CodeAccessPermission.RevertAssert(); } } return s_bitsPerPixel; } } ///<summary> ///tests to see if the monitor is in low resolution mode (8-bit color depth or less). ///</summary> public static bool LowResolution { get { if (s_lowResSettingValid) { return s_lowRes; } s_lowRes = BitsPerPixel <= 8; s_lowResSettingValid = true; return s_lowRes; } } ///<summary> ///tests to see if we are under high contrast mode ///</summary> public static bool HighContrast { get { if (s_highContrastSettingValid) { return s_highContrast; } s_highContrast = SystemInformation.HighContrast; s_highContrastSettingValid = true; return s_highContrast; } } public static bool IsDropShadowEnabled { [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] get { if (s_dropShadowSettingValid) { return s_dropShadowEnabled; } s_dropShadowEnabled = SystemInformation.IsDropShadowEnabled; s_dropShadowSettingValid = true; return s_dropShadowEnabled; } } ///<summary> ///test to see if we are under terminal server mode ///</summary> public static bool TerminalServer { get { if (s_terminalSettingValid) { return s_isTerminalServerSession; } s_isTerminalServerSession = SystemInformation.TerminalServerSession; s_terminalSettingValid = true; return s_isTerminalServerSession; } } ///<summary> ///event handler for change in display setting ///</summary> private static void DisplaySettingChanged(object obj, EventArgs ea) { s_highContrastSettingValid = false; s_lowResSettingValid = false; s_terminalSettingValid = false; s_dropShadowSettingValid = false; } ///<summary> ///event handler for change in user preference ///</summary> private static void UserPreferenceChanged(object obj, UserPreferenceChangedEventArgs ea) { s_highContrastSettingValid = false; s_lowResSettingValid = false; s_terminalSettingValid = false; s_dropShadowSettingValid = false; s_bitsPerPixel = 0; } } } }
43.300305
258
0.528569
[ "MIT" ]
DiogoMartinh0/winforms
src/System.Windows.Forms.Design/src/System/Windows/Forms/Design/ToolStripDesignerUtils.cs
28,407
C#
// Crest Ocean System // This file is subject to the MIT License as seen in the root of this folder structure (LICENSE) using UnityEngine; using UnityEngine.Experimental.Rendering; using UnityEngine.Rendering; namespace Crest { /// <summary> /// Base class for data/behaviours created on each LOD. /// </summary> public abstract class LodDataMgr { public abstract string SimName { get; } // This is the texture format we want to use. protected abstract GraphicsFormat RequestedTextureFormat { get; } // This is the platform compatible texture format we will use. public GraphicsFormat CompatibleTextureFormat { get; private set; } // NOTE: This MUST match the value in OceanConstants.hlsl, as it // determines the size of the texture arrays in the shaders. public const int MAX_LOD_COUNT = 15; // NOTE: these MUST match the values in OceanConstants.hlsl // 64 recommended as a good common minimum: https://www.reddit.com/r/GraphicsProgramming/comments/aeyfkh/for_compute_shaders_is_there_an_ideal_numthreads/ public const int THREAD_GROUP_SIZE_X = 8; public const int THREAD_GROUP_SIZE_Y = 8; // NOTE: This is a temporary solution to keywords having prefixes downstream. internal const string MATERIAL_KEYWORD_PREFIX = ""; protected abstract int GetParamIdSampler(bool sourceLod = false); protected abstract bool NeedToReadWriteTextureData { get; } protected RenderTexture _targets; public RenderTexture DataTexture { get { return _targets; } } protected virtual Texture2DArray NullTexture => TextureArrayHelpers.BlackTextureArray; public static int sp_LD_SliceIndex = Shader.PropertyToID("_LD_SliceIndex"); protected static int sp_LODChange = Shader.PropertyToID("_LODChange"); // shape texture resolution int _shapeRes = -1; // ocean scale last frame - used to detect scale changes float _oceanLocalScalePrev = -1f; int _scaleDifferencePow2 = 0; protected int ScaleDifferencePow2 { get { return _scaleDifferencePow2; } } public bool enabled { get; protected set; } protected OceanRenderer _ocean; // Implement in any sub-class which supports having an asset file for settings. This is used for polymorphic // operations. A sub-class will also implement an alternative for the specialised type called Settings. public virtual SimSettingsBase SettingsBase => null; SimSettingsBase _defaultSettings; /// <summary> /// Returns the default value of the settings asset for the provided type. /// </summary> protected SettingsType GetDefaultSettings<SettingsType>() where SettingsType : SimSettingsBase { if (_defaultSettings == null) { _defaultSettings = ScriptableObject.CreateInstance<SettingsType>(); _defaultSettings.name = SimName + " Auto-generated Settings"; } return (SettingsType)_defaultSettings; } public LodDataMgr(OceanRenderer ocean) { _ocean = ocean; } public virtual void Start() { InitData(); enabled = true; } public static RenderTexture CreateLodDataTextures(RenderTextureDescriptor desc, string name, bool needToReadWriteTextureData) { RenderTexture result = new RenderTexture(desc); result.wrapMode = TextureWrapMode.Clamp; result.antiAliasing = 1; result.filterMode = FilterMode.Bilinear; result.anisoLevel = 0; result.useMipMap = false; result.name = name; result.dimension = TextureDimension.Tex2DArray; result.volumeDepth = OceanRenderer.Instance.CurrentLodCount; result.enableRandomWrite = needToReadWriteTextureData; result.Create(); return result; } protected virtual void InitData() { // Find a compatible texture format. var formatUsage = NeedToReadWriteTextureData ? FormatUsage.LoadStore : FormatUsage.Sample; CompatibleTextureFormat = SystemInfo.GetCompatibleFormat(RequestedTextureFormat, formatUsage); if (CompatibleTextureFormat != RequestedTextureFormat) { Debug.Log($"Crest: Using render texture format {CompatibleTextureFormat} instead of {RequestedTextureFormat}"); } Debug.Assert(CompatibleTextureFormat != GraphicsFormat.None, $"Crest: The graphics device does not support the render texture format {RequestedTextureFormat}"); Debug.Assert(OceanRenderer.Instance.CurrentLodCount <= MAX_LOD_COUNT); var resolution = OceanRenderer.Instance.LodDataResolution; var desc = new RenderTextureDescriptor(resolution, resolution, CompatibleTextureFormat, 0); _targets = CreateLodDataTextures(desc, SimName, NeedToReadWriteTextureData); // Bind globally once here on init, which will bind to all graphics shaders (not compute) Shader.SetGlobalTexture(GetParamIdSampler(), _targets); } public virtual void UpdateLodData() { int width = OceanRenderer.Instance.LodDataResolution; // debug functionality to resize RT if different size was specified. if (_shapeRes == -1) { _shapeRes = width; } else if (width != _shapeRes) { _targets.Release(); _targets.width = _targets.height = _shapeRes; _targets.Create(); _shapeRes = width; } // determine if this LOD has changed scale and by how much (in exponent of 2) float oceanLocalScale = OceanRenderer.Instance.Root.localScale.x; if (_oceanLocalScalePrev == -1f) _oceanLocalScalePrev = oceanLocalScale; float ratio = oceanLocalScale / _oceanLocalScalePrev; _oceanLocalScalePrev = oceanLocalScale; float ratio_l2 = Mathf.Log(ratio) / Mathf.Log(2f); _scaleDifferencePow2 = Mathf.RoundToInt(ratio_l2); } public virtual void BuildCommandBuffer(OceanRenderer ocean, CommandBuffer buf) { } public static void Swap<T>(ref T a, ref T b) { var temp = b; b = a; a = temp; } public interface IDrawFilter { float Filter(ILodDataInput data, out int isTransition); } protected void SubmitDraws(int lodIdx, CommandBuffer buf) { var lt = OceanRenderer.Instance._lodTransform; lt._renderData[lodIdx].Validate(0, SimName); lt.SetViewProjectionMatrices(lodIdx, buf); var drawList = RegisterLodDataInputBase.GetRegistrar(GetType()); foreach (var draw in drawList) { if (!draw.Value.Enabled) { continue; } draw.Value.Draw(buf, 1f, 0, lodIdx); } } protected void SubmitDrawsFiltered(int lodIdx, CommandBuffer buf, IDrawFilter filter) { var lt = OceanRenderer.Instance._lodTransform; lt._renderData[lodIdx].Validate(0, SimName); lt.SetViewProjectionMatrices(lodIdx, buf); var drawList = RegisterLodDataInputBase.GetRegistrar(GetType()); foreach (var draw in drawList) { if (!draw.Value.Enabled) { continue; } int isTransition; float weight = filter.Filter(draw.Value, out isTransition); if (weight > 0f) { draw.Value.Draw(buf, weight, isTransition, lodIdx); } } } protected struct TextureArrayParamIds { private int _paramId; private int _paramId_Source; public TextureArrayParamIds(string textureArrayName) { _paramId = Shader.PropertyToID(textureArrayName); // Note: string concatonation does generate a small amount of // garbage. However, this is called on initialisation so should // be ok for now? Something worth considering for the future if // we want to go garbage-free. _paramId_Source = Shader.PropertyToID(textureArrayName + "_Source"); } public int GetId(bool sourceLod) { return sourceLod ? _paramId_Source : _paramId; } } internal virtual void OnEnable() { } internal virtual void OnDisable() { // Unbind from all graphics shaders (not compute) Shader.SetGlobalTexture(GetParamIdSampler(), NullTexture); } [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.SubsystemRegistration)] static void InitStatics() { // Init here from 2019.3 onwards sp_LD_SliceIndex = Shader.PropertyToID("_LD_SliceIndex"); sp_LODChange = Shader.PropertyToID("_LODChange"); } } }
37.907631
172
0.617968
[ "MIT" ]
573456721/-1
crest/Assets/Crest/Crest/Scripts/LodData/LodDataMgr.cs
9,441
C#
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using SapphireDb.Models.Exceptions; namespace SapphireDb.Helper { public static class ExpressionHelper { public static MethodCallExpression ToLower(Expression input) { return Expression.Call(input, ReflectionMethodHelper.StringToLower); } public static MethodCallExpression Contains(Expression input, Expression checkString) { return Expression.Call(input, ReflectionMethodHelper.StringContains, checkString); } public static MethodCallExpression ContainsCaseInsensitive(Expression input, Expression checkString) { return Contains(ToLower(input), ToLower(checkString)); } public static MethodCallExpression StartsWith(Expression input, Expression checkString) { return Expression.Call(input, ReflectionMethodHelper.StringStartsWith, checkString); } public static MethodCallExpression StartsWithCaseInsensitive(Expression input, Expression checkString) { return StartsWith(ToLower(input), ToLower(checkString)); } public static MethodCallExpression EndsWith(Expression input, Expression checkString) { return Expression.Call(input, ReflectionMethodHelper.StringEndsWith, checkString); } public static MethodCallExpression EndsWithCaseInsensitive(Expression input, Expression checkString) { return EndsWith(ToLower(input), ToLower(checkString)); } public static MethodCallExpression ArrayContains(Expression input, Expression checkValue, Type propertyType) { MethodInfo method = typeof(List<>).MakeGenericType(propertyType).GetMethod(nameof(Contains)); return Expression.Call(input, method, checkValue); } public static MethodCallExpression InArray(Expression input, Expression checkArray, Type propertyType) { return ArrayContains(checkArray, input, propertyType); } public static Expression CreateCompareExpression(Type modelType, JArray compareParts, Expression modelExpression) { PropertyInfo compareProperty = modelType.GetProperty(compareParts.First().Value<string>(), BindingFlags.Default | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.IgnoreCase | BindingFlags.Instance); if (compareProperty == null) { return Expression.Constant(true); } MemberExpression propertyExpression = Expression.PropertyOrField(modelExpression, compareProperty.Name); string compareOperation = compareParts.Skip(1).First().Value<string>(); Type targetType = compareProperty.PropertyType; if (compareOperation == "InArray") { targetType = typeof(List<>).MakeGenericType(targetType); } object compareValue = compareParts.Last.ToObject(targetType); Expression compareValueExpression = Expression.Constant(compareValue); switch (compareOperation) { case "Contains": return Contains(propertyExpression, compareValueExpression); case "ContainsCaseInsensitive": return ContainsCaseInsensitive(propertyExpression, compareValueExpression); case "StartsWith": return StartsWith(propertyExpression, compareValueExpression); case "StartsWithCaseInsensitive": return StartsWithCaseInsensitive(propertyExpression, compareValueExpression); case "EndsWith": return EndsWith(propertyExpression, compareValueExpression); case "EndsWithCaseInsensitive": return EndsWithCaseInsensitive(propertyExpression, compareValueExpression); case "ArrayContains": return ArrayContains(propertyExpression, compareValueExpression, compareProperty.PropertyType); case "InArray": return InArray(propertyExpression, compareValueExpression, compareProperty.PropertyType); case "NotEqualIgnoreCase": return Expression.NotEqual(ToLower(propertyExpression), ToLower(compareValueExpression)); case "EqualIgnoreCase": return Expression.Equal(ToLower(propertyExpression), ToLower(compareValueExpression)); case "!=": return Expression.NotEqual(propertyExpression, compareValueExpression); case "<": return Expression.LessThan(propertyExpression, compareValueExpression); case "<=": return Expression.LessThanOrEqual(propertyExpression, compareValueExpression); case ">": return Expression.GreaterThan(propertyExpression, compareValueExpression); case ">=": return Expression.GreaterThanOrEqual(propertyExpression, compareValueExpression); case "==": default: return Expression.Equal(propertyExpression, compareValueExpression); } } public static Expression ConvertConditionParts(Type modelType, JToken conditionParts, Expression modelExpression) { if (conditionParts.Type == JTokenType.Array) { if (conditionParts.First().Type == JTokenType.Array) { Expression completeExpression = null; Expression prevExpression = null; foreach (JToken combineOperator in conditionParts.Where(t => t.Type == JTokenType.String)) { if (prevExpression == null) { prevExpression = ConvertConditionParts(modelType, combineOperator.Previous, modelExpression); } else { prevExpression = completeExpression; } Expression nextExpression = ConvertConditionParts(modelType, combineOperator.Next, modelExpression); string operatorValue = combineOperator.Value<string>(); if (operatorValue == "and") { completeExpression = Expression.AndAlso(prevExpression, nextExpression); } else { completeExpression = Expression.OrElse(prevExpression, nextExpression); } } if (completeExpression == null) { completeExpression = ConvertConditionParts(modelType, conditionParts.First(), modelExpression); } return completeExpression; } return CreateCompareExpression(modelType, conditionParts.Value<JArray>(), modelExpression); } throw new WrongConditionOrderException(conditionParts); } public static string ToString(this Expression expression, object expressionCompiled) { string expressionString = expression.ToString(); object target = expressionCompiled.GetType().GetProperty("Target")?.GetValue(expressionCompiled); if (target?.GetType().GetField("Constants")?.GetValue(target) is object[] constants) { foreach (object constantContainer in constants) { Type objectType = constantContainer.GetType(); string objectName = objectType.FullName; foreach (FieldInfo field in objectType.GetFields().OrderByDescending(f => f.Name)) { object value = field.GetValue(constantContainer); string valueString = JsonConvert.SerializeObject(value); // string valueString = Expression.Constant(value).ToString(); string placeholder = $"value({objectName}).{field.Name}"; string valueExpressionString = $"value({valueString})"; expressionString = expressionString.Replace(placeholder, valueExpressionString); } } } return expressionString; } } }
44.615
124
0.5961
[ "MIT" ]
SapphireDb/SapphireDb
SapphireDb/Helper/ExpressionHelper.cs
8,925
C#
using System; using System.IO; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; namespace VPX.Presentation.WebClient.Infrastructure.Managers.Uploader { public class FileUploader { public static async Task<string> UploadToBase64(IFormFile file) { using var stream = new MemoryStream(); await file.CopyToAsync(stream); var base64 = Convert.ToBase64String(stream.ToArray()); var mime = file.ContentType; var image = $"data:{mime};base64,{base64}"; return image; } } }
25.695652
71
0.63621
[ "MIT" ]
VadimProkopchuk/JML
src/VPX.Presentation.WebClient/Infrastructure/Managers/Uploader/FileUploader.cs
593
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Azure.Messaging.EventHubs { /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Azure.Messaging.EventHubs.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } /// <summary> /// Looks up a localized string similar to The argument &apos;{0}&apos; may not be null or empty.. /// </summary> internal static string ArgumentNullOrEmpty { get { return ResourceManager.GetString("ArgumentNullOrEmpty", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The argument &apos;{0}&apos; may not be null or white space.. /// </summary> internal static string ArgumentNullOrWhiteSpace { get { return ResourceManager.GetString("ArgumentNullOrWhiteSpace", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The argument &apos;{0}&apos; cannot exceed {1} characters.. /// </summary> internal static string ArgumentStringTooLong { get { return ResourceManager.GetString("ArgumentStringTooLong", resourceCulture); } } /// <summary> /// Looks up a localized string similar to A sender created for a specific partition cannot send events using a partition key. This sender is associated with partition &apos;{0}&apos;.. /// </summary> internal static string CannotSendWithPartitionIdAndPartitionKey { get { return ResourceManager.GetString("CannotSendWithPartitionIdAndPartitionKey", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The connection string could not be parsed; either it was malformed or contains no well-known tokens.. /// </summary> internal static string InvalidConnectionString { get { return ResourceManager.GetString("InvalidConnectionString", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The string has an invalid encoding format.. /// </summary> internal static string InvalidEncoding { get { return ResourceManager.GetString("InvalidEncoding", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The shared access signature could not be parsed; it was either malformed or incorrectly encoded.. /// </summary> internal static string InvalidSharedAccessSignature { get { return ResourceManager.GetString("InvalidSharedAccessSignature", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The time period may not be Zero or Infinite.. /// </summary> internal static string InvalidTimePeriod { get { return ResourceManager.GetString("InvalidTimePeriod", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The requested transport type, &apos;{0}&apos; is not supported.. /// </summary> internal static string InvalidTransportType { get { return ResourceManager.GetString("InvalidTransportType", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The connection string used for an Event Hub client must specify the Event Hubs namespace host, the path to an Event Hub, and a Shared Access Signature (both the name and value) to be valid.. /// </summary> internal static string MalformedEventHubClientConnectionString { get { return ResourceManager.GetString("MalformedEventHubClientConnectionString", resourceCulture); } } /// <summary> /// Looks up a localized string similar to System property &apos;{0}&apos; is missing in the event.. /// </summary> internal static string MissingSystemProperty { get { return ResourceManager.GetString("MissingSystemProperty", resourceCulture); } } /// <summary> /// Looks up a localized string similar to A proxy may only be used for a websockets connection.. /// </summary> internal static string ProxyMustUseWebsockets { get { return ResourceManager.GetString("ProxyMustUseWebsockets", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The &apos;identifier&apos; parameter exceeds the maximum allowed size of {0} characters.. /// </summary> internal static string ReceiverIdentifierOverMaxValue { get { return ResourceManager.GetString("ReceiverIdentifierOverMaxValue", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The reqested resource, &apos;{0}&apos;, does not match the resource of the shared access signature, &apos;{1}&apos;. A token cannot be issued.. /// </summary> internal static string ResourceMustMatchSharedAccessSignature { get { return ResourceManager.GetString("ResourceMustMatchSharedAccessSignature", resourceCulture); } } /// <summary> /// Looks up a localized string similar to A retry must be set for the options; if no retry is desired, please set the value to Retry.NoRetry. /// </summary> internal static string RetryMustBeSet { get { return ResourceManager.GetString("RetryMustBeSet", resourceCulture); } } /// <summary> /// Looks up a localized string similar to In order to update the signature, a shared access key must have been provided when the shared access signature was created.. /// </summary> internal static string SharedAccessKeyIsRequired { get { return ResourceManager.GetString("SharedAccessKeyIsRequired", resourceCulture); } } /// <summary> /// Looks up a localized string similar to A timeout value must be positive. To request using the default timeout, please use TimeSpan.Zero or null.. /// </summary> internal static string TimeoutMustBePositive { get { return ResourceManager.GetString("TimeoutMustBePositive", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Argument {0} must be a non-negative timespan value. The provided value was {1}.. /// </summary> internal static string TimeSpanMustBeNonNegative { get { return ResourceManager.GetString("TimeSpanMustBeNonNegative", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The specified connection type, &quot;{0}&quot;, is not recognized as valid in this context.. /// </summary> internal static string UnknownConnectionType { get { return ResourceManager.GetString("UnknownConnectionType", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The value supplied must be between {0} and {1}.. /// </summary> internal static string ValueOutOfRange { get { return ResourceManager.GetString("ValueOutOfRange", resourceCulture); } } } }
37.424138
243
0.580116
[ "MIT" ]
kinelski/azure-sdk-for-net
sdk/eventhub/Azure.Messaging.EventHubs/src/Resources.Designer.cs
10,855
C#
using System; using System.Collections.Generic; using System.Linq; namespace Storage.Net.Blob { /// <summary> /// Blob item description /// </summary> public class BlobId : IEquatable<BlobId> { /// <summary> /// Gets the kind of item /// </summary> public BlobItemKind Kind { get; private set; } /// <summary> /// Gets the folder path containing this item /// </summary> public string FolderPath { get; private set; } /// <summary> /// Gets the id of this blob, uniqueue within the folder /// </summary> public string Id { get; private set; } /// <summary> /// Contains blob metadata when known, optional. /// </summary> public BlobMeta Meta { get; set; } /// <summary> /// Gets full path to this blob which is a combination of folder path and blob name /// </summary> public string FullPath => StoragePath.Combine(FolderPath, Id); /// <summary> /// Custom provider-specific properties /// </summary> public Dictionary<string, string> Properties { get; set; } /// <summary> /// Create a new instance /// </summary> /// <param name="fullId"></param> /// <param name="kind"></param> public BlobId(string fullId, BlobItemKind kind = BlobItemKind.File) { string path = StoragePath.Normalize(fullId); string[] parts = StoragePath.Split(path); Id = parts.Last(); FolderPath = StoragePath.GetParent(path); Kind = kind; } /// <summary> /// Creates a new instance /// </summary> /// <param name="folderPath"></param> /// <param name="id"></param> /// <param name="kind"></param> public BlobId(string folderPath, string id, BlobItemKind kind) { Id = id ?? throw new ArgumentNullException(nameof(id)); FolderPath = folderPath; Kind = kind; } /// <summary> /// Full blob info, i.e type, id and path /// </summary> public override string ToString() { string k = Kind == BlobItemKind.File ? "file" : "folder"; return $"{k}: {Id}@{FolderPath}"; } /// <summary> /// Equality check /// </summary> /// <param name="other"></param> public bool Equals(BlobId other) { if (ReferenceEquals(other, null)) return false; return other.FullPath == FullPath && other.Kind == Kind; } /// <summary> /// Equality check /// </summary> /// <param name="other"></param> public override bool Equals(object other) { if (ReferenceEquals(other, null)) return false; if (ReferenceEquals(other, this)) return true; if (other.GetType() != typeof(BlobId)) return false; return Equals((BlobId)other); } /// <summary> /// Hash code calculation /// </summary> public override int GetHashCode() { return FullPath.GetHashCode() * Kind.GetHashCode(); } /// <summary> /// Constructs a file blob by full ID /// </summary> public static implicit operator BlobId(string fileId) { return new BlobId(fileId, BlobItemKind.File); } } }
27.016129
89
0.549851
[ "MIT" ]
romkij/storage
src/Storage.Net/Blob/BlobId.cs
3,352
C#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; using System.Collections.Immutable; using System.Runtime.CompilerServices; using System.Threading.Tasks; namespace Roslyn.Utilities { internal static class SpecializedTasks { public static readonly Task<bool> True = Task.FromResult<bool>(true); public static readonly Task<bool> False = Task.FromResult<bool>(false); public static readonly Task EmptyTask = Empty<object>.Default; public static Task<T> Default<T>() { return Empty<T>.Default; } public static Task<ImmutableArray<T>> EmptyImmutableArray<T>() { return Empty<T>.EmptyImmutableArray; } public static Task<IEnumerable<T>> EmptyEnumerable<T>() { return Empty<T>.EmptyEnumerable; } public static Task<T> FromResult<T>(T t) where T : class { return FromResultCache<T>.FromResult(t); } private static class Empty<T> { public static readonly Task<T> Default = Task.FromResult<T>(default(T)); public static readonly Task<IEnumerable<T>> EmptyEnumerable = Task.FromResult<IEnumerable<T>>(SpecializedCollections.EmptyEnumerable<T>()); public static readonly Task<ImmutableArray<T>> EmptyImmutableArray = Task.FromResult(ImmutableArray<T>.Empty); } private static class FromResultCache<T> where T : class { private static readonly ConditionalWeakTable<T, Task<T>> s_fromResultCache = new ConditionalWeakTable<T, Task<T>>(); private static readonly ConditionalWeakTable<T, Task<T>>.CreateValueCallback s_taskCreationCallback = Task.FromResult<T>; public static Task<T> FromResult(T t) { return s_fromResultCache.GetValue(t, s_taskCreationCallback); } } } }
37.327273
161
0.654652
[ "Apache-2.0" ]
0x53A/roslyn
src/Workspaces/Core/Portable/Utilities/SpecializedTasks.cs
2,055
C#
using System; using Moq; using IMDB.Repository.Interfaces; using System.Collections.Generic; using IMDBApp.Models.Classes; using System.Linq; namespace IMDB.Test.MockResources { public class ProducerMock { public static readonly Mock<IProducerRepository> ProducerRepoMock = new Mock<IProducerRepository>(); private static IEnumerable<Producer> ListOfProducers() { return new List<Producer> { new Producer { Id = 1, Name = "Arjun", Bio = "--", Gender = "Male", Dob = Convert.ToDateTime("1998-05-14") }, new Producer { Id = 2, Name = "Arun", Bio = "--", Gender = "Male", Dob = Convert.ToDateTime("2004-09-11") } }; } public static void MockGetByMovieId() { ProducerRepoMock.Setup(repo => repo.GetByMovieId(It.IsAny<int>())).Returns((int id) => ListOfProducers().Single(a => a.Id == id)); } public static void MockGetAll() { ProducerRepoMock.Setup(repo => repo.GetAll()).Returns(ListOfProducers()); } public static void MockGet() { ProducerRepoMock.Setup(repo => repo.Get(It.IsAny<int>())).Returns((int id) => ListOfProducers().Single(a => a.Id == id)); } public static void MockAdd() { ProducerRepoMock.Setup(repo => repo.Add(It.IsAny<Producer>())).Returns(10); } public static void MockUpdate() { ProducerRepoMock.Setup(repo => repo.Update(It.IsAny<int>(), It.IsAny<Producer>())); } public static void MockDelete() { ProducerRepoMock.Setup(repo => repo.Delete(It.IsAny<int>())); } } }
29.782609
143
0.484185
[ "MIT" ]
cdrsonu/API
IMDBAppAPI/IMDBTest/MockResources/ProducerMock.cs
2,057
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Linq; using Microsoft.DotNet.RemoteExecutor; using Xunit; using Xunit.Sdk; namespace Microsoft.VisualBasic.Tests { public class FileSystemTests : System.IO.FileCleanupTestBase { protected override void Dispose(bool disposing) { try { FileSystem.FileClose(0); // close all files } catch (Exception) { } base.Dispose(disposing); } // On OSX, the temp directory /tmp/ is a symlink to /private/tmp, so setting the current // directory to a symlinked path will result in GetCurrentDirectory returning the absolute // path that followed the symlink. [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotOSX))] public void ChDir() { var savedDirectory = System.IO.Directory.GetCurrentDirectory(); FileSystem.ChDir(TestDirectory); Assert.Equal(TestDirectory, System.IO.Directory.GetCurrentDirectory()); FileSystem.ChDir(savedDirectory); Assert.Equal(savedDirectory, System.IO.Directory.GetCurrentDirectory()); } // Not tested: // public static void ChDrive(char Drive){ throw null; } // public static void ChDrive(string Drive){ throw null; } [ConditionalFact(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))] [ActiveIssue("https://github.com/dotnet/runtime/issues/49568", typeof(PlatformDetection), nameof(PlatformDetection.IsMacOsAppleSilicon))] public void CloseAllFiles() { var fileName1 = GetTestFilePath(); var fileName2 = GetTestFilePath(); RemoteExecutor.Invoke( (fileName1, fileName2) => { putStringNoClose(fileName1, "abc"); putStringNoClose(fileName2, "123"); // ProjectData.EndApp() should close all open files. Microsoft.VisualBasic.CompilerServices.ProjectData.EndApp(); static void putStringNoClose(string fileName, string str) { int fileNumber = FileSystem.FreeFile(); FileSystem.FileOpen(fileNumber, fileName, OpenMode.Random); FileSystem.FilePut(fileNumber, str); } }, fileName1, fileName2, new RemoteInvokeOptions() { ExpectedExitCode = 0 }).Dispose(); // Verify all text was written to the files. Assert.Equal("abc", getString(fileName1)); Assert.Equal("123", getString(fileName2)); static string getString(string fileName) { int fileNumber = FileSystem.FreeFile(); FileSystem.FileOpen(fileNumber, fileName, OpenMode.Random); string str = null; FileSystem.FileGet(fileNumber, ref str); FileSystem.FileClose(fileNumber); return str; } } // Can't get current directory on OSX before setting it. [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotOSX))] public void CurDir() { Assert.Equal(FileSystem.CurDir(), System.IO.Directory.GetCurrentDirectory()); } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsWindows))] public void CurDir_Drive() { var currentDirectory = System.IO.Directory.GetCurrentDirectory(); int index = currentDirectory.IndexOf(System.IO.Path.VolumeSeparatorChar); if (index == 1) { Assert.Equal(currentDirectory, FileSystem.CurDir(currentDirectory[0])); } } [Fact] public void Dir() { var fileNames = Enumerable.Range(0, 3).Select(i => GetTestFileName(i)).ToArray(); int n = fileNames.Length; for (int i = 0; i < n; i++) { System.IO.File.WriteAllText(System.IO.Path.Combine(TestDirectory, fileNames[i]), i.ToString()); } // Get all files. string fileName = FileSystem.Dir(System.IO.Path.Combine(TestDirectory, "*")); var foundNames = new string[n]; for (int i = 0; i < n; i++) { foundNames[i] = fileName; fileName = FileSystem.Dir(); } Assert.Null(fileName); Array.Sort(fileNames); Array.Sort(foundNames); for (int i = 0; i < n; i++) { Assert.Equal(fileNames[i], foundNames[i]); } // Get single file. fileName = FileSystem.Dir(System.IO.Path.Combine(TestDirectory, fileNames[2])); Assert.Equal(fileName, fileNames[2]); fileName = FileSystem.Dir(); Assert.Null(fileName); // Get missing file. fileName = FileSystem.Dir(GetTestFilePath(n)); Assert.Equal("", fileName); } [Fact] public void Dir_Volume() { if (PlatformDetection.IsWindows) { _ = FileSystem.Dir(TestDirectory, FileAttribute.Volume); } else { AssertThrows<PlatformNotSupportedException>(() => FileSystem.Dir(TestDirectory, FileAttribute.Volume)); } } [Fact] public void EOF() { int fileNumber = FileSystem.FreeFile(); var fileName = GetTestFilePath(); FileSystem.FileOpen(fileNumber, fileName, OpenMode.Output); FileSystem.Write(fileNumber, 'a'); FileSystem.Write(fileNumber, 'b'); FileSystem.Write(fileNumber, 'c'); FileSystem.FileClose(fileNumber); FileSystem.FileOpen(fileNumber, fileName, OpenMode.Input); for (int i = 0; i < 3; i++) { Assert.False(FileSystem.EOF(fileNumber)); char c = default; FileSystem.Input(fileNumber, ref c); } Assert.True(FileSystem.EOF(fileNumber)); FileSystem.FileClose(fileNumber); } // Not tested: // public static OpenMode FileAttr(int FileNumber){ throw null; } [Fact] public void FileClose() { int fileNumber = FileSystem.FreeFile(); // Close before opening. FileSystem.FileClose(fileNumber); createAndOpenFile(fileNumber); FileSystem.FileClose(fileNumber); // Close a second time. FileSystem.FileClose(fileNumber); // Close all files. fileNumber = FileSystem.FreeFile(); createAndOpenFile(fileNumber); createAndOpenFile(FileSystem.FreeFile()); Assert.NotEqual(fileNumber, FileSystem.FreeFile()); FileSystem.FileClose(0); Assert.Equal(fileNumber, FileSystem.FreeFile()); void createAndOpenFile(int fileNumber) { var fileName = GetTestFilePath(); System.IO.File.WriteAllText(fileName, "abc123"); FileSystem.FileOpen(fileNumber, fileName, OpenMode.Input); } } [Fact] public void FileCopy() { // Copy to a new file. var sourceName = GetTestFilePath(); System.IO.File.WriteAllText(sourceName, "abc"); var destName = GetTestFilePath(); FileSystem.FileCopy(sourceName, destName); Assert.Equal("abc", System.IO.File.ReadAllText(destName)); // Copy over an existing file. sourceName = GetTestFilePath(); System.IO.File.WriteAllText(sourceName, "def"); destName = GetTestFilePath(); System.IO.File.WriteAllText(destName, "123"); FileSystem.FileCopy(sourceName, destName); Assert.Equal("def", System.IO.File.ReadAllText(destName)); } // Not tested: // public static System.DateTime FileDateTime(string PathName){ throw null; } [Fact] public void FileGet_FilePut() { int fileNumber = FileSystem.FreeFile(); var fileName = GetTestFilePath(); DateTime dateTime = new DateTime(2019, 1, 1); FileSystem.FileOpen(fileNumber, fileName, OpenMode.Random); FileSystem.FilePut(fileNumber, true); FileSystem.FilePut(fileNumber, (byte)1); FileSystem.FilePut(fileNumber, (char)2); FileSystem.FilePut(fileNumber, (decimal)3); FileSystem.FilePut(fileNumber, 4.0); FileSystem.FilePut(fileNumber, 5.0f); FileSystem.FilePut(fileNumber, 6); FileSystem.FilePut(fileNumber, 7L); FileSystem.FilePut(fileNumber, (short)8); FileSystem.FilePut(fileNumber, "ABC"); FileSystem.FilePut(fileNumber, dateTime); FileSystem.FileClose(fileNumber); bool _bool = default; byte _byte = default; char _char = default; decimal _decimal = default; double _double = default; float _float = default; int _int = default; long _long = default; short _short = default; string _string = default; DateTime _dateTime = default; FileSystem.FileOpen(fileNumber, fileName, OpenMode.Random); FileSystem.FileGet(fileNumber, ref _bool); FileSystem.FileGet(fileNumber, ref _byte); FileSystem.FileGet(fileNumber, ref _char); FileSystem.FileGet(fileNumber, ref _decimal); FileSystem.FileGet(fileNumber, ref _double); FileSystem.FileGet(fileNumber, ref _float); FileSystem.FileGet(fileNumber, ref _int); FileSystem.FileGet(fileNumber, ref _long); FileSystem.FileGet(fileNumber, ref _short); FileSystem.FileGet(fileNumber, ref _string); FileSystem.FileGet(fileNumber, ref _dateTime); Assert.True(FileSystem.EOF(fileNumber)); FileSystem.FileClose(fileNumber); Assert.True(_bool); Assert.Equal((byte)1, _byte); Assert.Equal((char)2, _char); Assert.Equal((decimal)3, _decimal); Assert.Equal(4.0, _double); Assert.Equal(5.0f, _float); Assert.Equal(6, _int); Assert.Equal(7L, _long); Assert.Equal((short)8, _short); Assert.Equal("ABC", _string); Assert.Equal(dateTime, _dateTime); } // Not tested: // public static void FileGet(int FileNumber, ref System.Array Value, long RecordNumber = -1, bool ArrayIsDynamic = false, bool StringIsFixedLength = false) { } // public static void FileGet(int FileNumber, ref System.ValueType Value, long RecordNumber = -1) { } // public static void FilePut(int FileNumber, System.Array Value, long RecordNumber = -1, bool ArrayIsDynamic = false, bool StringIsFixedLength = false) { } // public static void FilePut(int FileNumber, System.ValueType Value, long RecordNumber = -1) { } // public static void FilePut(object FileNumber, object Value, object RecordNumber/* = -1*/) { } [Fact] public void FileGetObject_FilePutObject() { int fileNumber = FileSystem.FreeFile(); var fileName = GetTestFilePath(); DateTime dateTime = new DateTime(2019, 1, 1); FileSystem.FileOpen(fileNumber, fileName, OpenMode.Random); FileSystem.FilePutObject(fileNumber, true); FileSystem.FilePutObject(fileNumber, (byte)1); FileSystem.FilePutObject(fileNumber, (char)2); FileSystem.FilePutObject(fileNumber, (decimal)3); FileSystem.FilePutObject(fileNumber, 4.0); FileSystem.FilePutObject(fileNumber, 5.0f); FileSystem.FilePutObject(fileNumber, 6); FileSystem.FilePutObject(fileNumber, 7L); FileSystem.FilePutObject(fileNumber, (short)8); FileSystem.FilePutObject(fileNumber, "ABC"); FileSystem.FilePutObject(fileNumber, dateTime); FileSystem.FileClose(fileNumber); object _bool = null; object _byte = null; object _char = null; object _decimal = null; object _double = null; object _float = null; object _int = null; object _long = null; object _short = null; object _string = null; object _dateTime = null; FileSystem.FileOpen(fileNumber, fileName, OpenMode.Random); FileSystem.FileGetObject(fileNumber, ref _bool); FileSystem.FileGetObject(fileNumber, ref _byte); FileSystem.FileGetObject(fileNumber, ref _char); FileSystem.FileGetObject(fileNumber, ref _decimal); FileSystem.FileGetObject(fileNumber, ref _double); FileSystem.FileGetObject(fileNumber, ref _float); FileSystem.FileGetObject(fileNumber, ref _int); FileSystem.FileGetObject(fileNumber, ref _long); FileSystem.FileGetObject(fileNumber, ref _short); FileSystem.FileGetObject(fileNumber, ref _string); FileSystem.FileGetObject(fileNumber, ref _dateTime); Assert.True(FileSystem.EOF(fileNumber)); FileSystem.FileClose(fileNumber); Assert.Equal((object)true, _bool); Assert.Equal((byte)1, _byte); Assert.Equal((char)2, _char); Assert.Equal((decimal)3, _decimal); Assert.Equal(4.0, _double); Assert.Equal(5.0f, _float); Assert.Equal(6, _int); Assert.Equal(7L, _long); Assert.Equal((short)8, _short); Assert.Equal("ABC", _string); Assert.Equal(dateTime, _dateTime); } [Fact] public void FileLen() { int fileNumber = FileSystem.FreeFile(); string fileName = GetTestFilePath(); FileSystem.FileOpen(fileNumber, fileName, OpenMode.Append); FileSystem.FileClose(fileNumber); Assert.Equal(0, FileSystem.FileLen(fileName)); fileNumber = FileSystem.FreeFile(); fileName = GetTestFilePath(); System.IO.File.WriteAllText(fileName, "abc123"); Assert.Equal(6, FileSystem.FileLen(fileName)); } [Fact] public void FileOpen() { // OpenMode.Append: int fileNumber = FileSystem.FreeFile(); string fileName = GetTestFilePath(); FileSystem.FileOpen(fileNumber, fileName, OpenMode.Append); FileSystem.FileClose(fileNumber); // OpenMode.Binary: fileNumber = FileSystem.FreeFile(); fileName = GetTestFilePath(); FileSystem.FileOpen(fileNumber, fileName, OpenMode.Binary); FileSystem.FileClose(fileNumber); // OpenMode.Input: fileNumber = FileSystem.FreeFile(); fileName = GetTestFilePath(); AssertThrows<System.IO.FileNotFoundException>(() => FileSystem.FileOpen(fileNumber, fileName, OpenMode.Input)); System.IO.File.WriteAllText(fileName, "abc123"); FileSystem.FileOpen(fileNumber, fileName, OpenMode.Input); FileSystem.FileClose(fileNumber); // OpenMode.Output: fileNumber = FileSystem.FreeFile(); fileName = GetTestFilePath(); FileSystem.FileOpen(fileNumber, fileName, OpenMode.Output); FileSystem.FileClose(fileNumber); // OpenMode.Random: fileNumber = FileSystem.FreeFile(); fileName = GetTestFilePath(); FileSystem.FileOpen(fileNumber, fileName, OpenMode.Random); FileSystem.FileClose(fileNumber); // Open a second time. fileNumber = FileSystem.FreeFile(); fileName = GetTestFilePath(); FileSystem.FileOpen(fileNumber, fileName, OpenMode.Append); AssertThrows<System.IO.IOException>(() => FileSystem.FileOpen(fileNumber, fileName, OpenMode.Append)); FileSystem.FileClose(fileNumber); // Open an invalid fileNumber. AssertThrows<System.IO.IOException>(() => FileSystem.FileOpen(256, GetTestFilePath(), OpenMode.Append)); } // Not tested: // public static void FileWidth(int FileNumber, int RecordWidth) { } [Fact] public void FreeFile() { int fileNumber = FileSystem.FreeFile(); Assert.Equal(fileNumber, FileSystem.FreeFile()); FileSystem.FileOpen(fileNumber, GetTestFilePath(), OpenMode.Append); Assert.NotEqual(fileNumber, FileSystem.FreeFile()); } // Not tested: // public static FileAttribute GetAttr(string PathName) { throw null; } [Fact] public void Input_Write() { int fileNumber = FileSystem.FreeFile(); var fileName = GetTestFilePath(); DateTime dateTime = new DateTime(2019, 1, 1); FileSystem.FileOpen(fileNumber, fileName, OpenMode.Output); FileSystem.Write(fileNumber, true); FileSystem.Write(fileNumber, (byte)1, (char)2, (decimal)3, 4.0, 5.0f); FileSystem.Write(fileNumber, 6, 7L); FileSystem.Write(fileNumber, (short)8, "ABC", dateTime); FileSystem.FileClose(fileNumber); bool _bool = default; byte _byte = default; char _char = default; decimal _decimal = default; double _double = default; float _float = default; int _int = default; long _long = default; short _short = default; string _string = default; DateTime _dateTime = default; FileSystem.FileOpen(fileNumber, fileName, OpenMode.Input); FileSystem.Input(fileNumber, ref _bool); FileSystem.Input(fileNumber, ref _byte); FileSystem.Input(fileNumber, ref _char); FileSystem.Input(fileNumber, ref _decimal); FileSystem.Input(fileNumber, ref _double); FileSystem.Input(fileNumber, ref _float); FileSystem.Input(fileNumber, ref _int); FileSystem.Input(fileNumber, ref _long); FileSystem.Input(fileNumber, ref _short); FileSystem.Input(fileNumber, ref _string); FileSystem.Input(fileNumber, ref _dateTime); Assert.True(FileSystem.EOF(fileNumber)); FileSystem.FileClose(fileNumber); Assert.True(_bool); Assert.Equal((byte)1, _byte); Assert.Equal((char)2, _char); Assert.Equal((decimal)3, _decimal); Assert.Equal(4.0, _double); Assert.Equal(5.0f, _float); Assert.Equal(6, _int); Assert.Equal(7L, _long); Assert.Equal((short)8, _short); Assert.Equal("ABC", _string); Assert.Equal(dateTime, _dateTime); } [Fact] [ActiveIssue("https://github.com/dotnet/runtime/issues/34362", TestPlatforms.Windows, TargetFrameworkMonikers.Netcoreapp, TestRuntimes.Mono)] public void Input_Object_Write() { int fileNumber = FileSystem.FreeFile(); var fileName = GetTestFilePath(); DateTime dateTime = new DateTime(2019, 1, 1); FileSystem.FileOpen(fileNumber, fileName, OpenMode.Output); FileSystem.Write(fileNumber, DBNull.Value); FileSystem.Write(fileNumber, true); FileSystem.Write(fileNumber, (byte)1, (char)2, (decimal)3, 4.0, 5.0f); FileSystem.Write(fileNumber, 6, 7L); FileSystem.Write(fileNumber, (short)8, "ABC", dateTime); FileSystem.FileClose(fileNumber); object _dbnull = null; object _bool = null; object _byte = null; object _char = null; object _decimal = null; object _double = null; object _float = null; object _int = null; object _long = null; object _short = null; object _string = null; object _dateTime = null; FileSystem.FileOpen(fileNumber, fileName, OpenMode.Input); try { FileSystem.Input(fileNumber, ref _dbnull); FileSystem.Input(fileNumber, ref _bool); FileSystem.Input(fileNumber, ref _byte); FileSystem.Input(fileNumber, ref _char); FileSystem.Input(fileNumber, ref _decimal); FileSystem.Input(fileNumber, ref _double); FileSystem.Input(fileNumber, ref _float); FileSystem.Input(fileNumber, ref _int); FileSystem.Input(fileNumber, ref _long); FileSystem.Input(fileNumber, ref _short); FileSystem.Input(fileNumber, ref _string); FileSystem.Input(fileNumber, ref _dateTime); Assert.True(FileSystem.EOF(fileNumber)); Assert.Equal(DBNull.Value, _dbnull); Assert.Equal((object)true, _bool); Assert.Equal((short)1, _byte); Assert.Equal("\u0002", _char); Assert.Equal((short)3, _decimal); Assert.Equal((short)4, _double); Assert.Equal((short)5, _float); Assert.Equal((short)6, _int); Assert.Equal((short)7, _long); Assert.Equal((short)8, _short); Assert.Equal("ABC", _string); Assert.Equal(dateTime, _dateTime); } catch (PlatformNotSupportedException) { // Conversion.ParseInputField() is not supported on non-Windows platforms currently, // but this is also failing on some Windows platforms. Need to investigate. } FileSystem.FileClose(fileNumber); } // Not tested: // public static string InputString(int FileNumber, int CharCount) { throw null; } [Fact] public void Kill() { var fileName = GetTestFilePath(); System.IO.File.WriteAllText(fileName, "abc123"); Assert.True(System.IO.File.Exists(fileName)); FileSystem.Kill(fileName); Assert.False(System.IO.File.Exists(fileName)); // Missing file. fileName = GetTestFilePath(); AssertThrows<System.IO.FileNotFoundException>(() => FileSystem.Kill(fileName)); Assert.False(System.IO.File.Exists(fileName)); } // Not tested: // public static string LineInput(int FileNumber) { throw null; } // public static long Loc(int FileNumber) { throw null; } // Lock is supported on Windows only currently. [ConditionalFact(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))] [PlatformSpecific(TestPlatforms.Windows)] public void Lock_Unlock() { int fileNumber = FileSystem.FreeFile(); var fileName = GetTestFilePath(); FileSystem.FileOpen(fileNumber, fileName, OpenMode.Output, Share: OpenShare.Shared); remoteWrite(fileName, "abc"); try { FileSystem.Lock(fileNumber); remoteWrite(fileName, "123"); } finally { FileSystem.Unlock(fileNumber); } remoteWrite(fileName, "456"); FileSystem.FileClose(fileNumber); Assert.Equal("abc456", System.IO.File.ReadAllText(fileName)); static void remoteWrite(string fileName, string text) { RemoteExecutor.Invoke( (fileName, text) => { using (var stream = System.IO.File.Open(fileName, System.IO.FileMode.Append, System.IO.FileAccess.Write, System.IO.FileShare.ReadWrite)) { try { using (var writer = new System.IO.StreamWriter(stream)) { writer.Write(text); } } catch (System.IO.IOException) { } } }, fileName, text, new RemoteInvokeOptions() { ExpectedExitCode = 0 }).Dispose(); } } // Not tested: // public static void Lock(int FileNumber, long Record) { } // public static void Lock(int FileNumber, long FromRecord, long ToRecord) { } // public static long LOF(int FileNumber) { throw null; } // public static void Unlock(int FileNumber, long Record) { } // public static void Unlock(int FileNumber, long FromRecord, long ToRecord) { } [Fact] public void MkDir_RmDir() { var dirName = GetTestFilePath(); Assert.False(System.IO.Directory.Exists(dirName)); FileSystem.MkDir(dirName); Assert.True(System.IO.Directory.Exists(dirName)); // Create the directory a second time. AssertThrows<System.IO.IOException>(() => FileSystem.MkDir(dirName)); FileSystem.RmDir(dirName); Assert.False(System.IO.Directory.Exists(dirName)); // Remove the directory a second time. AssertThrows<System.IO.DirectoryNotFoundException>(() => FileSystem.RmDir(dirName)); } // Not tested: // public static void Print(int FileNumber, params object[] Output) { } // public static void PrintLine(int FileNumber, params object[] Output) { } [Fact] public void Rename() { // Rename to an unused name. var sourceName = GetTestFilePath(); System.IO.File.WriteAllText(sourceName, "abc"); var destName = GetTestFilePath(); if (PlatformDetection.IsWindows) { FileSystem.Rename(sourceName, destName); Assert.False(System.IO.File.Exists(sourceName)); Assert.True(System.IO.File.Exists(destName)); Assert.Equal("abc", System.IO.File.ReadAllText(destName)); } else { AssertThrows<PlatformNotSupportedException>(() => FileSystem.Rename(sourceName, destName)); Assert.True(System.IO.File.Exists(sourceName)); Assert.False(System.IO.File.Exists(destName)); Assert.Equal("abc", System.IO.File.ReadAllText(sourceName)); } // Rename to an existing name. sourceName = GetTestFilePath(); System.IO.File.WriteAllText(sourceName, "def"); destName = GetTestFilePath(); System.IO.File.WriteAllText(destName, "123"); if (PlatformDetection.IsWindows) { AssertThrows<System.IO.IOException>(() => FileSystem.Rename(sourceName, destName)); } else { AssertThrows<PlatformNotSupportedException>(() => FileSystem.Rename(sourceName, destName)); } Assert.True(System.IO.File.Exists(sourceName)); Assert.True(System.IO.File.Exists(destName)); Assert.Equal("def", System.IO.File.ReadAllText(sourceName)); Assert.Equal("123", System.IO.File.ReadAllText(destName)); } // Not tested: // public static void Reset() { } // public static void Seek(int FileNumber, long Position) { } // public static long Seek(int FileNumber) { throw null; } // public static void SetAttr(string PathName, FileAttribute Attributes) { } // public static SpcInfo SPC(short Count) { throw null; } // public static TabInfo TAB() { throw null; } // public static TabInfo TAB(short Column) { throw null; } // public static void WriteLine(int FileNumber, params object[] Output) { } [Fact] public void Write_ArgumentException() { int fileNumber = FileSystem.FreeFile(); var fileName = GetTestFilePath(); FileSystem.FileOpen(fileNumber, fileName, OpenMode.Output); AssertThrows<ArgumentException>(() => FileSystem.Write(fileNumber, new object())); FileSystem.FileClose(fileNumber); } // We cannot use XUnit.Assert.Throws<T>() for lambdas that rely on AssemblyData (such as // file numbers) because AssemblyData instances are associated with the calling assembly, and // in RELEASE builds, the calling assembly of a lambda invoked from XUnit.Assert.Throws<T>() // is corelib rather than this assembly, so file numbers created outside the lambda will be invalid. private static void AssertThrows<TException>(Action action) where TException : Exception { TException ex = null; try { action(); } catch (TException e) { ex = e; } if (ex == null) { throw new ThrowsException(typeof(TException)); } if (ex.GetType() != typeof(TException)) { throw new ThrowsException(typeof(TException), ex); } } } }
41.024291
170
0.568144
[ "MIT" ]
BreyerW/runtime
src/libraries/Microsoft.VisualBasic.Core/tests/FileSystemTests.cs
30,399
C#
// Project: Daggerfall Tools For Unity // Copyright: Copyright (C) 2009-2021 Daggerfall Workshop // Web Site: http://www.dfworkshop.net // License: MIT License (http://www.opensource.org/licenses/mit-license.php) // Source Code: https://github.com/Interkarma/daggerfall-unity // Original Author: Gavin Clayton (interkarma@dfworkshop.net) // Contributors: // // Notes: // using System; using System.Collections.Generic; using DaggerfallConnect; using DaggerfallConnect.Save; using DaggerfallConnect.FallExe; using DaggerfallWorkshop.Game.Serialization; using DaggerfallWorkshop.Game.Entity; using DaggerfallWorkshop.Game.Questing; using DaggerfallWorkshop.Game.Utility; using DaggerfallWorkshop.Game.MagicAndEffects; using DaggerfallWorkshop.Game.Formulas; using UnityEngine; namespace DaggerfallWorkshop.Game.Items { /// <summary> /// Parent class for any individual item in Daggerfall Unity. /// </summary> public partial class DaggerfallUnityItem { #region Fields // Public item values public string shortName; public int nativeMaterialValue; public DyeColors dyeColor; public float weightInKg; public int drawOrder; public int value; public ushort unknown; public ushort flags; public int currentCondition; public int maxCondition; public byte unknown2; public byte typeDependentData; public int enchantmentPoints; public int message; public DaggerfallEnchantment[] legacyMagic = null; public CustomEnchantment[] customMagic = null; public int stackCount = 1; public Poisons poisonType = Poisons.None; public uint timeHealthLeechLastUsed; public uint timeEffectsLastRerolled; // Private item fields int playerTextureArchive; int playerTextureRecord; int worldTextureArchive; int worldTextureRecord; ItemGroups itemGroup; int groupIndex; int currentVariant = 0; ulong uid; // Soul trapped MobileTypes trappedSoulType = MobileTypes.None; // Potion recipe int potionRecipeKey; // Time for magically-created item to disappear uint timeForItemToDisappear = 0; // Quest-related fields bool isQuestItem = false; ulong questUID = 0; Symbol questItemSymbol = null; // Item template is cached for faster checks // Does not need to be serialized ItemTemplate cachedItemTemplate; ItemGroups cachedItemGroup = ItemGroups.None; int cachedGroupIndex = -1; // References current slot if equipped EquipSlots equipSlot = EquipSlots.None; // Repair data, used when left for repair. ItemRepairData repairData = new ItemRepairData(); #endregion #region Item flag bitmasks const ushort identifiedMask = 0x20; const ushort artifactMask = 0x800; #endregion #region Properties /// <summary> /// Gets generated unique identifier. /// </summary> public ulong UID { get { return uid; } } /// <summary> /// Gets or sets player texture archive. /// Used during item creation to set correct body morphology. /// </summary> public int PlayerTextureArchive { get { return playerTextureArchive; } set { playerTextureArchive = value; } } /// <summary> /// Gets or sets world texture archive. /// This is the generic texture shown when item is used in world by itself, typically for quests. /// </summary> public int WorldTextureArchive { get { return worldTextureArchive; } set { worldTextureArchive = value; } } /// <summary> /// Gets or sets world texture record. /// This is the generic texture shown when item is used in world by itself, typically for quests. /// </summary> public int WorldTextureRecord { get { return worldTextureRecord; } set { worldTextureRecord = value; } } /// <summary> /// Gets inventory texture archive. /// </summary> public virtual int InventoryTextureArchive { get { return GetInventoryTextureArchive(); } } /// <summary> /// Gets inventory texture record. /// </summary> public virtual int InventoryTextureRecord { get { return GetInventoryTextureRecord(); } } /// <summary> /// Gets or sets item group. /// Setting will reset item data from new template. /// </summary> public ItemGroups ItemGroup { get { return itemGroup; } set { SetItem(value, groupIndex); } } /// <summary> /// Gets or sets item group index. /// Setting will reset item data from new template. /// </summary> public virtual int GroupIndex { get { return groupIndex; } set { SetItem(itemGroup, value); } } /// <summary> /// Get this item's template data. /// </summary> public ItemTemplate ItemTemplate { get { return GetCachedItemTemplate(); } } /// <summary> /// Get this item's template index. /// </summary> public int TemplateIndex { get { return ItemTemplate.index; } } /// <summary> /// Resolve this item's name. /// </summary> public virtual string ItemName { get { return DaggerfallUnity.Instance.ItemHelper.ResolveItemName(this); } } /// <summary> /// Resolve this item's full name (mainly for tooltips). /// </summary> public virtual string LongName { get { return DaggerfallUnity.Instance.ItemHelper.ResolveItemLongName(this); } } /// <summary> /// Gets temp equip slot. /// </summary> public EquipSlots EquipSlot { get { return equipSlot; } set { equipSlot = value; } } /// <summary> /// Gets total variants of this item. /// </summary> public int TotalVariants { get { return ItemTemplate.variants; } } /// <summary> /// Gets current variant of this item. /// </summary> public virtual int CurrentVariant { get { return currentVariant; } set { SetCurrentVariant(value); } } /// <summary> /// Checks if this is an ingredient. /// </summary> public bool IsIngredient { get { return ItemTemplate.isIngredient; } } /// <summary> /// Checks if this item is equipped. /// </summary> public bool IsEquipped { get { return equipSlot != EquipSlots.None; } } /// <summary> /// Checks if this item has magical properties. /// </summary> public virtual bool IsEnchanted { get { return HasLegacyEnchantments || HasCustomEnchantments; } } /// <summary> /// Gets legacy enchantments on this item. Can be null or empty. /// Legacy enchantments on items are stored and generated using the classic type/param enchantment format. /// </summary> public DaggerfallEnchantment[] LegacyEnchantments { get { return legacyMagic; } } /// <summary> /// True if item has any legacy enchantments. /// </summary> public bool HasLegacyEnchantments { get { return GetHasLegacyEnchantment(); } } /// <summary> /// Gets custom enchantments on this item. Can be null or empty. /// Custom enchantments on items are stored and generated using an effectKey/customParam pair. /// </summary> public CustomEnchantment[] CustomEnchantments { get { return customMagic; } } /// <summary> /// True is item has any custom enchantments. /// </summary> public bool HasCustomEnchantments { get { return customMagic != null && customMagic.Length > 0; } } /// <summary> /// Checks if this item is an artifact. /// </summary> public bool IsArtifact { get { return (flags & artifactMask) > 0; } } /// <summary> /// Checks if this item is light source. /// </summary> public bool IsLightSource { // Torch, Lantern, Candle, Holy Candle. get { return (itemGroup == ItemGroups.UselessItems2 && (TemplateIndex == (int)UselessItems2.Torch || TemplateIndex == (int)UselessItems2.Lantern || TemplateIndex == (int)UselessItems2.Candle)) || IsOfTemplate(ItemGroups.ReligiousItems, (int)ReligiousItems.Holy_candle); } } /// <summary> /// Checks if this item is of any shield type. /// </summary> public bool IsShield { get { return GetIsShield(); } } /// <summary> /// Checks if this item is identified. /// </summary> public bool IsIdentified { get { return GetIsIdentified(); } } /// <summary> /// Checks if this item is a potion recipe. /// </summary> public bool IsPotionRecipe { get { return ItemGroup == ItemGroups.MiscItems && TemplateIndex == (int)MiscItems.Potion_recipe; } } /// <summary> /// Checks if this item is a potion. /// </summary> public bool IsPotion { get { return ItemGroup == ItemGroups.UselessItems1 && TemplateIndex == (int)UselessItems1.Glass_Bottle; } } /// <summary> /// Checks if this item is a parchment. /// </summary> public bool IsParchment { get { return ItemGroup == ItemGroups.UselessItems2 && TemplateIndex == (int)UselessItems2.Parchment; } } /// <summary> /// Gets/sets the soul trapped in a soul trap. /// </summary> public MobileTypes TrappedSoulType { get { return trappedSoulType; } set { trappedSoulType = value; } } /// <summary> /// Gets/sets the key of the potion recipe allocated to this item. /// Has a side effect (ugh, sorry) of populating the item value from the recipe price. /// (due to value not being encapsulated) Also populates texture record for potions. /// </summary> public int PotionRecipeKey { get { return potionRecipeKey; } set { PotionRecipe potionRecipe = GameManager.Instance.EntityEffectBroker.GetPotionRecipe(value); if (potionRecipe != null) { potionRecipeKey = value; this.value = potionRecipe.Price; if (IsPotion) worldTextureRecord = potionRecipe.TextureRecord; } } } /// <summary> /// Gets/sets the time for this item to disappear. /// </summary> public uint TimeForItemToDisappear { get { return timeForItemToDisappear; } set { timeForItemToDisappear = value; } } /// <summary> /// Get flag checking if this is a summoned item. /// Summoned items have a specific future game time they expire. /// Non-summoned items have 0 in this field. /// </summary> public bool IsSummoned { get { return timeForItemToDisappear != 0; } } /// <summary> /// Check if this is a quest item. /// </summary> public bool IsQuestItem { get { return isQuestItem; } } /// <summary> /// Gets quest UID of quest owning this item. /// </summary> public ulong QuestUID { get { return questUID; } } /// <summary> /// Gets symbol of quest item inside quest. /// </summary> public Symbol QuestItemSymbol { get { return questItemSymbol; } } /// <summary> /// Gets native material value. /// </summary> public virtual int NativeMaterialValue { get { return nativeMaterialValue; } } /// <summary>Gets the repair data for this item.</summary> public ItemRepairData RepairData { get { return repairData; } } /// <summary>Gets current item condition as a percentage of max.</summary> public int ConditionPercentage { get { return 100 * currentCondition / maxCondition; } } #endregion #region Constructors /// <summary> /// Default constructor. /// Generates new UID. /// </summary> public DaggerfallUnityItem() { uid = DaggerfallUnity.NextUID; } /// <summary> /// Construct from item group and index. /// Generates new UID. /// </summary> public DaggerfallUnityItem(ItemGroups itemGroup, int groupIndex) { uid = DaggerfallUnity.NextUID; SetItem(itemGroup, groupIndex); } /// <summary> /// Construct from another item. /// Generates new UID. /// </summary> public DaggerfallUnityItem(DaggerfallUnityItem item) { uid = DaggerfallUnity.NextUID; FromItem(item); } /// <summary> /// Construct from legacy ItemRecord data. /// Generates new UID. /// </summary> public DaggerfallUnityItem(ItemRecord record) { uid = DaggerfallUnity.NextUID; FromItemRecord(record); } /// <summary> /// Construct item from serialized data. /// Used serialized UID. /// </summary> /// <param name="itemData">Item data to restore.</param> public DaggerfallUnityItem(ItemData_v1 itemData) { FromItemData(itemData); } #endregion #region Public Methods /// <summary> /// Creates a new copy of this item. /// </summary> /// <returns>Cloned item.</returns> public DaggerfallUnityItem Clone() { return new DaggerfallUnityItem(this); } /// <summary> /// Sets item from group and index. /// Resets item data from new template. /// Retains existing UID. /// </summary> /// <param name="itemGroup">Item group.</param> /// <param name="groupIndex">Item group index.</param> public void SetItem(ItemGroups itemGroup, int groupIndex) { // Hand off for artifacts if (itemGroup == ItemGroups.Artifacts) { SetArtifact(itemGroup, groupIndex); return; } // Get template data ItemTemplate itemTemplate = DaggerfallUnity.Instance.ItemHelper.GetItemTemplate(itemGroup, groupIndex); // Assign new data shortName = itemTemplate.name; // LOCALIZATION_TODO: Lookup item template name from localization this.itemGroup = itemGroup; this.groupIndex = groupIndex; playerTextureArchive = itemTemplate.playerTextureArchive; playerTextureRecord = itemTemplate.playerTextureRecord; worldTextureArchive = itemTemplate.worldTextureArchive; worldTextureRecord = itemTemplate.worldTextureRecord; nativeMaterialValue = 0; dyeColor = DyeColors.Unchanged; weightInKg = itemTemplate.baseWeight; drawOrder = itemTemplate.drawOrderOrEffect; currentVariant = 0; value = itemTemplate.basePrice; unknown = 0; flags = 0; currentCondition = itemTemplate.hitPoints; maxCondition = itemTemplate.hitPoints; unknown2 = 0; typeDependentData = 0; enchantmentPoints = itemTemplate.enchantmentPoints; message = (itemGroup == ItemGroups.Paintings) ? UnityEngine.Random.Range(0, 65536) : 0; stackCount = 1; } /// <summary> /// Sets item by merging item template and artifact template data. /// Result is a normal DaggerfallUnityItem with properties of both base template and magic item template. /// </summary> /// <param name="groupIndex">Artifact group index.</param> public void SetArtifact(ItemGroups itemGroup, int groupIndex) { // Must be an artifact type if (itemGroup != ItemGroups.Artifacts) throw new Exception("An attempt was made to SetArtifact() with non-artifact ItemGroups value."); // Get artifact template MagicItemTemplate magicItemTemplate = DaggerfallUnity.Instance.ItemHelper.GetArtifactTemplate(groupIndex); // Get base item template data, this is the fundamental item type being expanded ItemTemplate itemTemplate = DaggerfallUnity.Instance.ItemHelper.GetItemTemplate((ItemGroups)magicItemTemplate.group, magicItemTemplate.groupIndex); // Get artifact texture indices int archive, record; DaggerfallUnity.Instance.ItemHelper.GetArtifactTextureIndices((ArtifactsSubTypes)groupIndex, out archive, out record); // Correct material value for armor artifacts int materialValue = magicItemTemplate.material; if (magicItemTemplate.group == (int)ItemGroups.Armor) materialValue = 0x200 + materialValue; // Assign new data shortName = magicItemTemplate.name; // LOCALIZATION_TODO: Lookup magic item template name from localization this.itemGroup = (ItemGroups)magicItemTemplate.group; this.groupIndex = magicItemTemplate.groupIndex; playerTextureArchive = archive; playerTextureRecord = record; worldTextureArchive = archive; // Not sure about artifact world textures, just using player texture for now worldTextureRecord = record; nativeMaterialValue = materialValue; dyeColor = DyeColors.Unchanged; weightInKg = itemTemplate.baseWeight; drawOrder = itemTemplate.drawOrderOrEffect; currentVariant = 0; value = magicItemTemplate.value; unknown = 0; flags = artifactMask | identifiedMask; // Set as artifact & identified. currentCondition = magicItemTemplate.uses; maxCondition = magicItemTemplate.uses; unknown2 = 0; typeDependentData = 0; enchantmentPoints = 0; message = 0; stackCount = 1; // All artifacts have magical effects bool foundEnchantment = false; legacyMagic = new DaggerfallEnchantment[magicItemTemplate.enchantments.Length]; for (int i = 0; i < magicItemTemplate.enchantments.Length; i++) { legacyMagic[i] = magicItemTemplate.enchantments[i]; if (legacyMagic[i].type != EnchantmentTypes.None) foundEnchantment = true; } // Discard list if no enchantment found if (!foundEnchantment) legacyMagic = null; } /// <summary> /// Checks if item is of both group and template index. /// </summary> /// <param name="itemGroup">Item group to check.</param> /// <param name="templateIndex">Template index to check.</param> /// <returns>True if item matches both group and template index.</returns> public bool IsOfTemplate(ItemGroups itemGroup, int templateIndex) { if (ItemGroup == itemGroup && TemplateIndex == templateIndex) return true; else return false; } /// <summary> /// Checks if item is of template index. /// </summary> /// <param name="templateIndex">Template index to check.</param> /// <returns>True if item matches template index.</returns> public bool IsOfTemplate(int templateIndex) { return (TemplateIndex == templateIndex); } // Horses, carts, arrows and maps are not counted against encumbrance. public float EffectiveUnitWeightInKg() { if (ItemGroup == ItemGroups.Transportation || TemplateIndex == (int)Weapons.Arrow || IsOfTemplate(ItemGroups.MiscItems, (int)MiscItems.Map)) return 0f; return weightInKg; } /// <summary> /// Determines if item is stackable. /// Only ingredients, potions, gold pieces, oil and arrows are stackable, /// but equipped items, enchanted ingredients and quest items are never stackable. /// </summary> /// <returns>True if item stackable.</returns> public virtual bool IsStackable() { if (IsSummoned) { // Only allowing summoned arrows to stack at this time // But they should only stack with other summoned arrows if (!IsOfTemplate(ItemGroups.Weapons, (int)Weapons.Arrow)) return false; } // Equipped, quest and enchanted items cannot stack. if (IsEquipped || IsQuestItem || IsEnchanted) return false; return FormulaHelper.IsItemStackable(this); } /// <summary> /// Determines if item is a stack. /// </summary> /// <returns><c>true</c> if item is a stack, <c>false</c> otherwise.</returns> public bool IsAStack() { return stackCount > 1; } /// <summary> /// Allow use of item to be implemented by item object and overridden /// </summary> /// <returns><c>true</c>, if item use was handled, <c>false</c> otherwise.</returns> public virtual bool UseItem(ItemCollection collection) { return false; } /// <summary> /// Cycles through variants. /// </summary> public void NextVariant() { // Only certain items support user-initiated variants bool canChangeVariant = false; switch (TemplateIndex) { case (int)MensClothing.Casual_cloak: case (int)MensClothing.Formal_cloak: case (int)MensClothing.Reversible_tunic: case (int)MensClothing.Plain_robes: case (int)MensClothing.Short_shirt: case (int)MensClothing.Short_shirt_with_belt: case (int)MensClothing.Long_shirt: case (int)MensClothing.Long_shirt_with_belt: case (int)MensClothing.Short_shirt_closed_top: case (int)MensClothing.Short_shirt_closed_top2: case (int)MensClothing.Long_shirt_closed_top: case (int)MensClothing.Long_shirt_closed_top2: case (int)WomensClothing.Casual_cloak: case (int)WomensClothing.Formal_cloak: case (int)WomensClothing.Strapless_dress: case (int)WomensClothing.Plain_robes: case (int)WomensClothing.Short_shirt: case (int)WomensClothing.Short_shirt_belt: case (int)WomensClothing.Long_shirt: case (int)WomensClothing.Long_shirt_belt: case (int)WomensClothing.Short_shirt_closed: case (int)WomensClothing.Short_shirt_closed_belt: case (int)WomensClothing.Long_shirt_closed: case (int)WomensClothing.Long_shirt_closed_belt: canChangeVariant = true; break; } // Cycle through variants if (canChangeVariant) { int variant = CurrentVariant + 1; if (variant >= TotalVariants) variant = 0; currentVariant = variant; } } /// <summary> /// Gets item data for serialization. /// </summary> /// <returns>ItemData_v1.</returns> public virtual ItemData_v1 GetSaveData() { ItemData_v1 data = new ItemData_v1(); data.uid = uid; data.shortName = shortName; data.nativeMaterialValue = nativeMaterialValue; data.dyeColor = dyeColor; data.weightInKg = weightInKg; data.drawOrder = drawOrder; data.value1 = value; data.value2 = (unknown & 0xffff) | (flags << 16); data.hits1 = currentCondition; data.hits2 = maxCondition; data.hits3 = (unknown2 & 0xff) | (typeDependentData << 8); data.enchantmentPoints = enchantmentPoints; data.message = message; if (legacyMagic != null) { data.legacyMagic = new int[legacyMagic.Length * 2]; int j = 0; for (int i = 0; i < legacyMagic.Length; i++) { data.legacyMagic[j] = (short)(legacyMagic[i].type); j++; data.legacyMagic[j] = legacyMagic[i].param; j++; } } data.customMagic = customMagic; data.playerTextureArchive = playerTextureArchive; data.playerTextureRecord = playerTextureRecord; data.worldTextureArchive = worldTextureArchive; data.worldTextureRecord = worldTextureRecord; data.itemGroup = itemGroup; data.groupIndex = groupIndex; data.currentVariant = currentVariant; data.stackCount = stackCount; data.isQuestItem = isQuestItem; data.questUID = questUID; data.questItemSymbol = questItemSymbol; data.trappedSoulType = trappedSoulType; data.poisonType = poisonType; if ((int)poisonType < MagicAndEffects.MagicEffects.PoisonEffect.startValue) data.poisonType = Poisons.None; data.potionRecipe = potionRecipeKey; data.repairData = repairData.GetSaveData(); data.timeForItemToDisappear = timeForItemToDisappear; data.timeHealthLeechLastUsed = timeHealthLeechLastUsed; return data; } public virtual SoundClips GetEquipSound() { switch (itemGroup) { case ItemGroups.MensClothing: case ItemGroups.WomensClothing: return SoundClips.EquipClothing; case ItemGroups.Jewellery: case ItemGroups.Gems: return SoundClips.EquipJewellery; case ItemGroups.Armor: if (GetIsShield() || TemplateIndex == (int)Armor.Helm) return SoundClips.EquipPlate; else if (nativeMaterialValue == (int)ArmorMaterialTypes.Leather) return SoundClips.EquipLeather; else if (nativeMaterialValue == (int)ArmorMaterialTypes.Chain) return SoundClips.EquipChain; else return SoundClips.EquipPlate; case ItemGroups.Weapons: switch (TemplateIndex) { case (int)Weapons.Battle_Axe: case (int)Weapons.War_Axe: return SoundClips.EquipAxe; case (int)Weapons.Broadsword: case (int)Weapons.Longsword: case (int)Weapons.Saber: case (int)Weapons.Katana: return SoundClips.EquipLongBlade; case (int)Weapons.Claymore: case (int)Weapons.Dai_Katana: return SoundClips.EquipTwoHandedBlade; case (int)Weapons.Dagger: case (int)Weapons.Tanto: case (int)Weapons.Wakazashi: case (int)Weapons.Shortsword: return SoundClips.EquipShortBlade; case (int)Weapons.Flail: return SoundClips.EquipFlail; case (int)Weapons.Mace: case (int)Weapons.Warhammer: return SoundClips.EquipMaceOrHammer; case (int)Weapons.Staff: return SoundClips.EquipStaff; case (int)Weapons.Short_Bow: case (int)Weapons.Long_Bow: return SoundClips.EquipBow; default: return SoundClips.None; } default: return SoundClips.None; } } public virtual SoundClips GetSwingSound() { switch (TemplateIndex) { case (int)Weapons.Warhammer: case (int)Weapons.Battle_Axe: case (int)Weapons.Katana: case (int)Weapons.Claymore: case (int)Weapons.Dai_Katana: case (int)Weapons.Flail: return SoundClips.SwingLowPitch; case (int)Weapons.Broadsword: case (int)Weapons.Longsword: case (int)Weapons.Saber: case (int)Weapons.Wakazashi: case (int)Weapons.War_Axe: case (int)Weapons.Staff: case (int)Weapons.Mace: return SoundClips.SwingMediumPitch; case (int)Weapons.Dagger: case (int)Weapons.Tanto: case (int)Weapons.Shortsword: return SoundClips.SwingHighPitch; case (int)Weapons.Short_Bow: case (int)Weapons.Long_Bow: return SoundClips.ArrowShoot; default: return SoundClips.None; } } public virtual int GetWeaponSkillUsed() { switch (TemplateIndex) { case (int)Weapons.Dagger: case (int)Weapons.Tanto: case (int)Weapons.Wakazashi: case (int)Weapons.Shortsword: return (int)DaggerfallConnect.DFCareer.ProficiencyFlags.ShortBlades; case (int)Weapons.Broadsword: case (int)Weapons.Longsword: case (int)Weapons.Saber: case (int)Weapons.Katana: case (int)Weapons.Claymore: case (int)Weapons.Dai_Katana: return (int)DaggerfallConnect.DFCareer.ProficiencyFlags.LongBlades; case (int)Weapons.Battle_Axe: case (int)Weapons.War_Axe: return (int)DaggerfallConnect.DFCareer.ProficiencyFlags.Axes; case (int)Weapons.Flail: case (int)Weapons.Mace: case (int)Weapons.Warhammer: case (int)Weapons.Staff: return (int)DaggerfallConnect.DFCareer.ProficiencyFlags.BluntWeapons; case (int)Weapons.Short_Bow: case (int)Weapons.Long_Bow: return (int)DaggerfallConnect.DFCareer.ProficiencyFlags.MissileWeapons; default: return (int)Skills.None; } } public virtual short GetWeaponSkillIDAsShort() { int skill = GetWeaponSkillUsed(); switch (skill) { case (int)DFCareer.ProficiencyFlags.ShortBlades: return (int)Skills.ShortBlade; case (int)DFCareer.ProficiencyFlags.LongBlades: return (int)Skills.LongBlade; case (int)DFCareer.ProficiencyFlags.Axes: return (int)Skills.Axe; case (int)DFCareer.ProficiencyFlags.BluntWeapons: return (int)Skills.BluntWeapon; case (int)DFCareer.ProficiencyFlags.MissileWeapons: return (int)Skills.Archery; default: return (int)Skills.None; } } public DFCareer.Skills GetWeaponSkillID() { return (DFCareer.Skills)GetWeaponSkillIDAsShort(); } public virtual int GetBaseDamageMin() { return FormulaHelper.CalculateWeaponMinDamage((Weapons)TemplateIndex); } public virtual int GetBaseDamageMax() { return FormulaHelper.CalculateWeaponMaxDamage((Weapons)TemplateIndex); } public int GetWeaponMaterialModifier() { switch (nativeMaterialValue) { case (int)WeaponMaterialTypes.Iron: return -1; case (int)WeaponMaterialTypes.Steel: case (int)WeaponMaterialTypes.Silver: return 0; case (int)WeaponMaterialTypes.Elven: return 1; case (int)WeaponMaterialTypes.Dwarven: return 2; case (int)WeaponMaterialTypes.Mithril: case (int)WeaponMaterialTypes.Adamantium: return 3; case (int)WeaponMaterialTypes.Ebony: return 4; case (int)WeaponMaterialTypes.Orcish: return 5; case (int)WeaponMaterialTypes.Daedric: return 6; default: return 0; } } public virtual int GetMaterialArmorValue() { int result = 0; if (!IsShield) { switch (nativeMaterialValue) { case (int)ArmorMaterialTypes.Leather: result = 3; break; case (int)ArmorMaterialTypes.Chain: case (int)ArmorMaterialTypes.Chain2: result = 6; break; case (int)ArmorMaterialTypes.Iron: result = 7; break; case (int)ArmorMaterialTypes.Steel: case (int)ArmorMaterialTypes.Silver: result = 9; break; case (int)ArmorMaterialTypes.Elven: result = 11; break; case (int)ArmorMaterialTypes.Dwarven: result = 13; break; case (int)ArmorMaterialTypes.Mithril: case (int)ArmorMaterialTypes.Adamantium: result = 15; break; case (int)ArmorMaterialTypes.Ebony: result = 17; break; case (int)ArmorMaterialTypes.Orcish: result = 19; break; case (int)ArmorMaterialTypes.Daedric: result = 21; break; } } else { return GetShieldArmorValue(); } // Armor artifact appear to use armor rating divided by 2 rounded down if (IsArtifact && ItemGroup == ItemGroups.Armor) result /= 2; return result; } public virtual int GetShieldArmorValue() { switch (TemplateIndex) { case (int)Armor.Buckler: return 1; case (int)Armor.Round_Shield: return 2; case (int)Armor.Kite_Shield: return 3; case (int)Armor.Tower_Shield: return 4; default: return 0; } } /// <summary> /// Get body parts protected by a shield. /// </summary> public virtual BodyParts[] GetShieldProtectedBodyParts() { switch (TemplateIndex) { case (int)Armor.Buckler: return new BodyParts[] { BodyParts.LeftArm, BodyParts.Hands }; case (int)Armor.Round_Shield: case (int)Armor.Kite_Shield: return new BodyParts[] { BodyParts.LeftArm, BodyParts.Hands, BodyParts.Legs }; case (int)Armor.Tower_Shield: return new BodyParts[] { BodyParts.Head, BodyParts.LeftArm, BodyParts.Hands, BodyParts.Legs }; default: return new BodyParts[] { }; } } /// <summary> /// Get the equip slot that matches to a body part. /// Used in armor calculations. /// </summary> public static EquipSlots GetEquipSlotForBodyPart(BodyParts bodyPart) { switch (bodyPart) { case BodyParts.Head: return EquipSlots.Head; case BodyParts.RightArm: return EquipSlots.RightArm; case BodyParts.LeftArm: return EquipSlots.LeftArm; case BodyParts.Chest: return EquipSlots.ChestArmor; case BodyParts.Hands: return EquipSlots.Gloves; case BodyParts.Legs: return EquipSlots.LegsArmor; case BodyParts.Feet: return EquipSlots.Feet; default: return EquipSlots.None; } } /// <summary> /// Get the body part that matches to an equip slot. /// Used in armor calculations. /// </summary> public static BodyParts GetBodyPartForEquipSlot(EquipSlots equipSlot) { switch (equipSlot) { case EquipSlots.Head: return BodyParts.Head; case EquipSlots.RightArm: return BodyParts.RightArm; case EquipSlots.LeftArm: return BodyParts.LeftArm; case EquipSlots.ChestArmor: return BodyParts.Chest; case EquipSlots.Gloves: return BodyParts.Hands; case EquipSlots.LegsArmor: return BodyParts.Legs; case EquipSlots.Feet: return BodyParts.Feet; default: return BodyParts.None; } } public virtual EquipSlots GetEquipSlot() { return EquipSlots.None; } public virtual ItemHands GetItemHands() { return ItemHands.None; } public virtual WeaponTypes GetWeaponType() { return WeaponTypes.None; } public void LowerCondition(int amount, DaggerfallEntity unequipFromOwner = null, ItemCollection removeFromCollectionWhenBreaks = null) { currentCondition -= amount; if (currentCondition <= 0) { // Handle breaking - if AllowMagicRepairs enabled then item will not disappear currentCondition = 0; ItemBreaks(unequipFromOwner); if (removeFromCollectionWhenBreaks != null && !DaggerfallUnity.Settings.AllowMagicRepairs) removeFromCollectionWhenBreaks.RemoveItem(this); } } public void UnequipItem(DaggerfallEntity owner) { if (owner == null) return; foreach (EquipSlots slot in Enum.GetValues(typeof(EquipSlots))) { if (owner.ItemEquipTable.GetItem(slot) == this) { owner.ItemEquipTable.UnequipItem(slot); owner.UpdateEquippedArmorValues(this, false); } } } protected void ItemBreaks(DaggerfallEntity owner) { // Classic does not have the plural version of this string, and uses the short name rather than the long one. // Also the classic string says "is" instead of "has" string itemBroke = ""; if (TemplateIndex == (int)Armor.Boots || TemplateIndex == (int)Armor.Gauntlets || TemplateIndex == (int)Armor.Greaves) itemBroke = TextManager.Instance.GetLocalizedText("itemHasBrokenPlural"); else itemBroke = TextManager.Instance.GetLocalizedText("itemHasBroken"); itemBroke = itemBroke.Replace("%s", LongName); DaggerfallUI.Instance.PopupMessage(itemBroke); // Unequip item if owner specified if (owner != null) UnequipItem(owner); else return; // Breaks payload callback on owner effect manager if (owner.EntityBehaviour) { EntityEffectManager ownerEffectManager = owner.EntityBehaviour.GetComponent<EntityEffectManager>(); if (ownerEffectManager) ownerEffectManager.DoItemEnchantmentPayloads(EnchantmentPayloadFlags.Breaks, this, owner.Items, owner.EntityBehaviour); } } /// <summary> /// Link this DaggerfallUnityItem to a quest Item resource. /// </summary> /// <param name="questUID">UID of quest owning Item resource.</param> /// <param name="questItemSymbol">Symbol to locate Item resource in quest.</param> public void LinkQuestItem(ulong questUID, Symbol questItemSymbol) { this.isQuestItem = true; this.questUID = questUID; this.questItemSymbol = questItemSymbol; } /// <summary> /// Remove status as quest item so it becomes permanent and will not be removed at end of quest. /// </summary> public void MakePermanent() { if (isQuestItem) { questUID = 0; questItemSymbol = null; isQuestItem = false; } } /// <summary> /// Identifies the item. /// </summary> public void IdentifyItem() { flags = (ushort)(flags | identifiedMask); } /// <summary> /// Gets the enchantment points of this item. /// </summary> public virtual int GetEnchantmentPower() { return FormulaHelper.GetItemEnchantmentPower(this); } /// <summary> /// Set enchantments on this item. Any existing enchantments will be overwritten. /// </summary> /// <param name="enchantments">Array of enchantment settings. Maximum of 10 enchantments are applied.</param> /// <param name="owner">Owner of this item for unequip test.</param> public void SetEnchantments(EnchantmentSettings[] enchantments, DaggerfallEntity owner = null) { const int maxEnchantments = 10; // Validate list if (enchantments == null || enchantments.Length == 0) throw new Exception("SetEnchantments() enchantments cannot be null or empty."); // Build enchantment lists int count = 0; List<DaggerfallEnchantment> legacyEnchantments = new List<DaggerfallEnchantment>(); List<CustomEnchantment> customEnchantments = new List<CustomEnchantment>(); foreach (EnchantmentSettings settings in enchantments) { // Enchantment must have an effect key if (string.IsNullOrEmpty(settings.EffectKey)) throw new Exception(string.Format("SetEnchantments() effect key is null or empty at index {0}", count)); // Created payload callback IEntityEffect effectTemplate = GameManager.Instance.EntityEffectBroker.GetEffectTemplate(settings.EffectKey); if (effectTemplate != null) { EnchantmentParam param = new EnchantmentParam() { ClassicParam = settings.ClassicParam, CustomParam = settings.CustomParam, }; if (effectTemplate.HasEnchantmentPayloadFlags(EnchantmentPayloadFlags.Enchanted)) effectTemplate.EnchantmentPayloadCallback(EnchantmentPayloadFlags.Enchanted, param, null, null, this); } // Add custom or legacy enchantment if (!string.IsNullOrEmpty(settings.CustomParam)) { CustomEnchantment customEnchantment = new CustomEnchantment() { EffectKey = settings.EffectKey, CustomParam = settings.CustomParam, }; customEnchantments.Add(customEnchantment); } else { if (settings.ClassicType == EnchantmentTypes.None) throw new Exception(string.Format("SetEnchantments() not a valid enchantment type at index {0}", count)); DaggerfallEnchantment legacyEnchantment = new DaggerfallEnchantment() { type = settings.ClassicType, param = settings.ClassicParam, }; legacyEnchantments.Add(legacyEnchantment); } // Cap enchanting at limit if (++count > maxEnchantments) break; } // Do nothing if no enchantments found if (customEnchantments.Count == 0 && legacyEnchantments.Count == 0) throw new Exception("SetEnchantments() no enchantments provided"); // Unequip item - entity must equip again // This ensures "on equip" effect payloads execute correctly UnequipItem(owner); // Set new enchantments and identified flag legacyMagic = legacyEnchantments.ToArray(); customMagic = customEnchantments.ToArray(); IdentifyItem(); } /// <summary> /// Rename item. /// </summary> /// <param name="name">New name of item. Cannot be null or empty.</param> public void RenameItem(string name) { if (!string.IsNullOrEmpty(name)) { shortName = name; } } /// <summary> /// Check if item contains a specific legacy enchantment. /// </summary> /// <param name="type">Legacy type.</param> /// <param name="param">Legacy param.</param> /// <returns>True if item contains enchantment.</returns> public bool ContainsEnchantment(EnchantmentTypes type, short param) { if (legacyMagic == null || legacyMagic.Length == 0) return false; foreach (DaggerfallEnchantment enchantment in LegacyEnchantments) { if (enchantment.type == type && enchantment.param == param) return true; } return false; } /// <summary> /// Check if item contains a specific custom enchantment. /// </summary> /// <param name="key">Effect key.</param> /// <param name="param">Effect param.</param> /// <returns>True if item contains enchantment.</returns> public bool ContainsEnchantment(string key, string param) { if (customMagic == null || customMagic.Length == 0) return false; foreach (CustomEnchantment enchantment in CustomEnchantments) { if (enchantment.EffectKey == key && enchantment.CustomParam == param) return true; } return false; } /// <summary> /// Combines all legacy and custom enchantments into a single array. /// Using EnchantmentSettings to store relavent combined enchantment information. /// Not all properties of EnchantmentSettings are set here, just what is needed to identify enchantment. /// </summary> /// <returns>Array of enchantment settings, can be null or empty.</returns> public EnchantmentSettings[] GetCombinedEnchantmentSettings() { List<EnchantmentSettings> combinedEnchantments = new List<EnchantmentSettings>(); // Item must have enchancements if (!IsEnchanted) return null; // Legacy enchantments if (legacyMagic != null && legacyMagic.Length > 0) { foreach (DaggerfallEnchantment enchantment in legacyMagic) { // Ignore empty enchantment slots if (enchantment.type == EnchantmentTypes.None) continue; // Get classic effect key - enchantments use EnchantmentTypes string as key, artifacts use ArtifactsSubTypes string string effectKey; if (enchantment.type == EnchantmentTypes.SpecialArtifactEffect) effectKey = ((ArtifactsSubTypes)enchantment.param).ToString(); else effectKey = enchantment.type.ToString(); // Add enchantment settings combinedEnchantments.Add(new EnchantmentSettings() { EffectKey = effectKey, ClassicType = enchantment.type, ClassicParam = enchantment.param, }); } } // Custom enchantments if (customMagic != null && customMagic.Length > 0) { foreach (CustomEnchantment enchantment in customMagic) { // Ignore enchantment with null or empty key if (string.IsNullOrEmpty(enchantment.EffectKey)) continue; // Add enchantment settings combinedEnchantments.Add(new EnchantmentSettings() { EffectKey = enchantment.EffectKey, CustomParam = enchantment.CustomParam, ClassicType = EnchantmentTypes.None, }); } } return combinedEnchantments.ToArray(); } #endregion #region Static Methods /// <summary> /// Compares two items for equal UID. /// One or both items can be null. /// </summary> /// <param name="item1">First item.</param> /// <param name="item2">Second item.</param> /// <returns>True if items have same UID.</returns> public static bool CompareItems(DaggerfallUnityItem item1, DaggerfallUnityItem item2) { // Exclude null cases if (item1 == null && item2 == null) return true; else if (item1 == null || item2 == null) return false; // Compare UIDs if (item1.UID == item2.UID) return true; else return false; } #endregion #region Private Methods /// <summary> /// Creates from another item instance. /// </summary> void FromItem(DaggerfallUnityItem other) { shortName = other.shortName; itemGroup = other.itemGroup; groupIndex = other.groupIndex; playerTextureArchive = other.playerTextureArchive; playerTextureRecord = other.playerTextureRecord; worldTextureArchive = other.worldTextureArchive; worldTextureRecord = other.worldTextureRecord; nativeMaterialValue = other.nativeMaterialValue; dyeColor = other.dyeColor; weightInKg = other.weightInKg; drawOrder = other.drawOrder; currentVariant = other.currentVariant; value = other.value; unknown = other.unknown; flags = other.flags; currentCondition = other.currentCondition; maxCondition = other.maxCondition; unknown2 = other.unknown2; stackCount = other.stackCount; enchantmentPoints = other.enchantmentPoints; message = other.message; potionRecipeKey = other.potionRecipeKey; timeHealthLeechLastUsed = other.timeHealthLeechLastUsed; isQuestItem = other.isQuestItem; questUID = other.questUID; questItemSymbol = other.questItemSymbol; if (other.legacyMagic != null) legacyMagic = (DaggerfallEnchantment[])other.legacyMagic.Clone(); if (other.customMagic != null) customMagic = (CustomEnchantment[])other.customMagic.Clone(); } /// <summary> /// Create from native save ItemRecord data. /// </summary> void FromItemRecord(ItemRecord itemRecord) { // Get template data ItemGroups group = (ItemGroups)itemRecord.ParsedData.group; int index = itemRecord.ParsedData.index; ItemTemplate itemTemplate = DaggerfallUnity.Instance.ItemHelper.GetItemTemplate(group, index); // Get player image int playerBitfield = (int)itemRecord.ParsedData.image1; int playerArchive = playerBitfield >> 7; int playerRecord = (playerBitfield & 0x7f); // Get world image int worldBitfield = (int)itemRecord.ParsedData.image2; int worldArchive = worldBitfield >> 7; int worldRecord = (worldBitfield & 0x7f); // Assign new data shortName = itemRecord.ParsedData.name; // LOCALIZATION_TODO: Lookup item template name from localizations itemGroup = group; groupIndex = index; playerTextureArchive = playerArchive; playerTextureRecord = playerRecord; worldTextureArchive = worldArchive; worldTextureRecord = worldRecord; nativeMaterialValue = itemRecord.ParsedData.material; dyeColor = (DyeColors)itemRecord.ParsedData.color; weightInKg = (float)itemRecord.ParsedData.weight * 0.25f; drawOrder = itemTemplate.drawOrderOrEffect; value = (int)itemRecord.ParsedData.value; unknown = itemRecord.ParsedData.unknown; flags = itemRecord.ParsedData.flags; currentCondition = itemRecord.ParsedData.currentCondition; maxCondition = itemRecord.ParsedData.maxCondition; unknown2 = itemRecord.ParsedData.unknown2; typeDependentData = itemRecord.ParsedData.typeDependentData; // If item is an arrow, typeDependentData is the stack count if ((itemGroup == ItemGroups.Weapons) && (groupIndex == 18)) // index 18 is for arrows { stackCount = itemRecord.ParsedData.typeDependentData; } else { stackCount = 1; } // Convert classic recipes to DFU recipe key. if ((IsPotion || IsPotionRecipe) && typeDependentData < MagicAndEffects.PotionRecipe.classicRecipeKeys.Length) potionRecipeKey = MagicAndEffects.PotionRecipe.classicRecipeKeys[typeDependentData]; currentVariant = 0; enchantmentPoints = itemRecord.ParsedData.enchantmentPoints; message = (int)itemRecord.ParsedData.message; // Assign current variant if (itemTemplate.variants > 0) { if (IsCloak()) currentVariant = playerRecord - (itemTemplate.playerTextureRecord + 1); else currentVariant = playerRecord - itemTemplate.playerTextureRecord; } // Assign legacy magic effects array bool foundEnchantment = false; if (itemRecord.ParsedData.magic != null) { legacyMagic = new DaggerfallEnchantment[itemRecord.ParsedData.magic.Length]; for (int i = 0; i < itemRecord.ParsedData.magic.Length; i++) { legacyMagic[i] = itemRecord.ParsedData.magic[i]; if (legacyMagic[i].type != EnchantmentTypes.None) foundEnchantment = true; } } // Discard list if no enchantment found if (!foundEnchantment) legacyMagic = null; // TEST: Force dye color to match material of imported weapons & armor // This is to fix cases where dye colour may be set incorrectly on imported item dyeColor = DaggerfallUnity.Instance.ItemHelper.GetDyeColor(this); } /// <summary> /// Creates from a serialized item. /// </summary> internal void FromItemData(ItemData_v1 data) { uid = data.uid; shortName = data.shortName; nativeMaterialValue = data.nativeMaterialValue; dyeColor = data.dyeColor; weightInKg = data.weightInKg; drawOrder = data.drawOrder; value = data.value1; // These are being saved in DF Unity saves as one int32 value but are two 16-bit values in classic unknown = (ushort)(data.value2 & 0xffff); flags = (ushort)(data.value2 >> 16); currentCondition = data.hits1; maxCondition = data.hits2; // These are being saved in DF Unity saves as one int32 value but are two 8-bit values in classic unknown2 = (byte)(data.hits3 & 0xff); typeDependentData = (byte)(data.hits3 >> 8); enchantmentPoints = data.enchantmentPoints; message = data.message; // Convert magic data that was saved as int array if (data.legacyMagic != null) { legacyMagic = new DaggerfallEnchantment[data.legacyMagic.Length / 2]; int j = 0; for (int i = 0; i < legacyMagic.Length; i++) { legacyMagic[i].type = (EnchantmentTypes)(data.legacyMagic[j]); j++; legacyMagic[i].param = (short)(data.legacyMagic[j]); j++; } } customMagic = data.customMagic; playerTextureArchive = data.playerTextureArchive; playerTextureRecord = data.playerTextureRecord; worldTextureArchive = data.worldTextureArchive; worldTextureRecord = data.worldTextureRecord; itemGroup = data.itemGroup; groupIndex = data.groupIndex; currentVariant = data.currentVariant; stackCount = data.stackCount; isQuestItem = data.isQuestItem; questUID = data.questUID; questItemSymbol = data.questItemSymbol; trappedSoulType = data.trappedSoulType; poisonType = data.poisonType; if ((int)data.poisonType < MagicAndEffects.MagicEffects.PoisonEffect.startValue) poisonType = Poisons.None; potionRecipeKey = data.potionRecipe; timeHealthLeechLastUsed = data.timeHealthLeechLastUsed; // Convert any old classic recipe items in saves to DFU recipe key. if (potionRecipeKey == 0 && (IsPotion || IsPotionRecipe) && typeDependentData < MagicAndEffects.PotionRecipe.classicRecipeKeys.Length) potionRecipeKey = MagicAndEffects.PotionRecipe.classicRecipeKeys[typeDependentData]; repairData.RestoreRepairData(data.repairData); timeForItemToDisappear = data.timeForItemToDisappear; } /// <summary> /// Caches item template. /// </summary> ItemTemplate GetCachedItemTemplate() { if (itemGroup != cachedItemGroup || groupIndex != cachedGroupIndex) { cachedItemTemplate = DaggerfallUnity.Instance.ItemHelper.GetItemTemplate(itemGroup, groupIndex); cachedItemGroup = itemGroup; cachedGroupIndex = groupIndex; } return cachedItemTemplate; } /// <summary> /// Gets inventory texture archive based on certain properties. /// </summary> /// <returns></returns> int GetInventoryTextureArchive() { // Handle world texture if (UseWorldTexture()) return worldTextureArchive; return playerTextureArchive; } /// <summary> /// Gets inventory texture record based on variant and other properties. /// </summary> int GetInventoryTextureRecord() { // Handle world texture if (UseWorldTexture()) return worldTextureRecord; // Use texture record retrieved from MAGIC.DEF for artifacts. Otherwise the below code will give the Oghma Infinium record 2, from the "Book" template. if (IsArtifact) return playerTextureRecord; // Handle items with variants if (ItemTemplate.variants > 0) { // Get starting record from template int start = ItemTemplate.playerTextureRecord; // Cloaks have a special interior image, need to increment for first actual cloak image if (IsCloak()) start += 1; return start + currentVariant; } return playerTextureRecord; } bool IsCloak() { // Men's cloaks if (ItemGroup == ItemGroups.MensClothing && (TemplateIndex == (int)MensClothing.Casual_cloak || TemplateIndex == (int)MensClothing.Formal_cloak)) { return true; } // Women's cloaks if (ItemGroup == ItemGroups.WomensClothing && (TemplateIndex == (int)WomensClothing.Casual_cloak || TemplateIndex == (int)WomensClothing.Formal_cloak)) { return true; } return false; } // Check if item has any valid legacy enchantments bool GetHasLegacyEnchantment() { if (legacyMagic == null || legacyMagic.Length == 0) return false; // Check for legacy magic effects for (int i = 0; i < legacyMagic.Length; i++) { if (legacyMagic[i].type != EnchantmentTypes.None) return true; } return false; } // Check if this is a shield bool GetIsShield() { if (ItemGroup == ItemGroups.Armor) { if (TemplateIndex == (int)Armor.Kite_Shield || TemplateIndex == (int)Armor.Round_Shield || TemplateIndex == (int)Armor.Tower_Shield || TemplateIndex == (int)Armor.Buckler) { return true; } } return false; } // Check if this item is identified. (only relevant if item has some enchantments) bool GetIsIdentified() { if (!IsEnchanted) return true; return (flags & identifiedMask) > 0; } // Determines if world texture should be displayed in place of player texture // Many inventory item types have this setup and more may need to be added bool UseWorldTexture() { // Handle uselessitems1 if (itemGroup == ItemGroups.UselessItems1) return true; // Handle ingredients if (IsIngredient) return true; // Handle arrows if (IsOfTemplate(ItemGroups.Weapons, (int)Weapons.Arrow)) { return true; } // Handle religious items if (itemGroup == ItemGroups.ReligiousItems) return true; // Handle misc items if (itemGroup == ItemGroups.MiscItems) return true; return false; } /// <summary> /// Sets current variant and clamps within valid range. /// </summary> void SetCurrentVariant(int variant) { if (variant < 0) currentVariant = 0; else if (variant >= TotalVariants) currentVariant = TotalVariants - 1; else currentVariant = variant; } #endregion #region Events // OnWeaponStrike public delegate void OnWeaponStrikeEventHandler(DaggerfallUnityItem item, DaggerfallEntityBehaviour receiver, int damage); public event OnWeaponStrikeEventHandler OnWeaponStrike; public void RaiseOnWeaponStrikeEvent(DaggerfallEntityBehaviour receiver, int damage) { if (OnWeaponStrike != null) OnWeaponStrike(this, receiver, damage); } #endregion } }
36.74918
163
0.543159
[ "MIT" ]
deepfighter/daggerfall-unity
Assets/Scripts/Game/Items/DaggerfallUnityItem.cs
67,251
C#
using Api.Contract; using EmpleoDotNet.Core.Domain; using EmpleoDotNet.WebAPI.Helpers; namespace EmpleoDotNet.WebAPI.Services { public interface IJobOpportunityToMobileJobAdapter { JobCardDTO GetJobCard(JobOpportunity jobOpportunity); JobDetailResponse GetJobDetails(JobOpportunity jobOpportunity); } public class JobOpportunityToMobileJobAdapter : IJobOpportunityToMobileJobAdapter { public JobCardDTO GetJobCard(JobOpportunity jobOpportunity) { var jobCard = new JobCardDTO(); jobCard.CompanyLogoUrl = jobOpportunity.CompanyLogoUrl; jobCard.CompanyName = jobOpportunity.CompanyName; jobCard.Title = jobOpportunity.Title; // Maybe this should be left to the UI jobCard.PublishedDate = jobOpportunity.PublishedDate.GetValueOrDefault(); jobCard.IsRemote = jobOpportunity.IsRemote; jobCard.Description = jobOpportunity.Description; jobCard.HowToApply = jobOpportunity.HowToApply; jobCard.JobType = jobOpportunity.JobType.GetDisplayName(); jobCard.Link = jobOpportunity.Id.ToString(); jobCard.ViewCount = jobOpportunity.ViewCount; jobCard.Likes = jobOpportunity.Likes; jobCard.Location = jobOpportunity.JobOpportunityLocation != null ? jobOpportunity.JobOpportunityLocation.Name : "N/A"; return jobCard; } public JobDetailResponse GetJobDetails(JobOpportunity j) { var jd = new JobDetailResponse(); jd.IsRemote = j.IsRemote; jd.JobDescription = j.Description; jd.JobTitle = j.Title; jd.JobType = j.JobType.GetDisplayName(); jd.Link = j.Id.ToString(); jd.Location = j.JobOpportunityLocation != null ? j.JobOpportunityLocation.Name: "N/A"; jd.Visits = j.ViewCount; jd.HowToApply = j.HowToApply; jd.Company = new JobDetailResponse.JobDetailCompany() { Name = j.CompanyName, Email = j.CompanyEmail, LogoUrl = j.CompanyLogoUrl, Url = j.CompanyUrl }; return jd; } } }
38.627119
130
0.628346
[ "Unlicense" ]
ArielVillalona/empleo-dot-net
EmpleoDotNet.WebApi/Services/IJobOpportunityToMobileJobAdapter.cs
2,283
C#
using Netnr.Core; using Netnr.SharedFast; namespace Netnr.Guff.Application { public class BuildService { /// <summary> /// 链接 /// </summary> /// <param name="path"></param> /// <returns></returns> public static string AutoLink(string path = "") { var isbh = CacheTo.Get(GlobalTo.GetValue("Common:BuildHtmlKey")) as bool? ?? false; var hp = isbh ? "" : "/home"; return hp + path; } } }
23.761905
95
0.51503
[ "MIT" ]
Rabbit2108/np
src/Netnr.P/Netnr.Guff/Application/BuildService.cs
505
C#
using System; using System.ComponentModel; using EfsTools.Attributes; using EfsTools.Utils; using Newtonsoft.Json; namespace EfsTools.Items.Nv { [Serializable] [NvItemId(4512)] [Attributes(9)] public class C1WcdmaBc4LnaOffsetVsFreq4 { [ElementsCount(16)] [ElementType("int8")] [Description("")] public sbyte[] Value { get; set; } } }
20
44
0.607143
[ "MIT" ]
HomerSp/EfsTools
EfsTools/Items/Nv/C1WcdmaBc4LnaOffsetVsFreq4I.cs
420
C#
namespace BizHawk.Client.EmuHawk { partial class CGBColorChooserForm { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.groupBox1 = new System.Windows.Forms.GroupBox(); this.radioButton6 = new System.Windows.Forms.RadioButton(); this.radioButton5 = new System.Windows.Forms.RadioButton(); this.radioButton3 = new System.Windows.Forms.RadioButton(); this.radioButton4 = new System.Windows.Forms.RadioButton(); this.radioButton2 = new System.Windows.Forms.RadioButton(); this.radioButton1 = new System.Windows.Forms.RadioButton(); this.groupBox2 = new System.Windows.Forms.GroupBox(); this.bmpView1 = new BizHawk.Client.EmuHawk.BmpView(); this.buttonOK = new System.Windows.Forms.Button(); this.buttonCancel = new System.Windows.Forms.Button(); this.radioButton7 = new System.Windows.Forms.RadioButton(); this.groupBox1.SuspendLayout(); this.groupBox2.SuspendLayout(); this.SuspendLayout(); // // groupBox1 // this.groupBox1.Controls.Add(this.radioButton7); this.groupBox1.Controls.Add(this.radioButton6); this.groupBox1.Controls.Add(this.radioButton5); this.groupBox1.Controls.Add(this.radioButton3); this.groupBox1.Controls.Add(this.radioButton4); this.groupBox1.Controls.Add(this.radioButton2); this.groupBox1.Controls.Add(this.radioButton1); this.groupBox1.Location = new System.Drawing.Point(12, 12); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size(132, 182); this.groupBox1.TabIndex = 0; this.groupBox1.TabStop = false; this.groupBox1.Text = "Preset Select"; // // radioButton6 // this.radioButton6.AutoSize = true; this.radioButton6.Location = new System.Drawing.Point(6, 134); this.radioButton6.Name = "radioButton6"; this.radioButton6.Size = new System.Drawing.Size(47, 17); this.radioButton6.TabIndex = 3; this.radioButton6.TabStop = true; this.radioButton6.Text = "GBA"; this.radioButton6.UseVisualStyleBackColor = true; this.radioButton6.CheckedChanged += new System.EventHandler(this.RadioButton1_CheckedChanged); // // radioButton5 // this.radioButton5.AutoSize = true; this.radioButton5.Location = new System.Drawing.Point(6, 111); this.radioButton5.Name = "radioButton5"; this.radioButton5.Size = new System.Drawing.Size(117, 17); this.radioButton5.TabIndex = 2; this.radioButton5.TabStop = true; this.radioButton5.Text = "VBA Accurate (Old)"; this.radioButton5.UseVisualStyleBackColor = true; this.radioButton5.CheckedChanged += new System.EventHandler(this.RadioButton1_CheckedChanged); // // radioButton3 // this.radioButton3.AutoSize = true; this.radioButton3.Location = new System.Drawing.Point(6, 65); this.radioButton3.Name = "radioButton3"; this.radioButton3.Size = new System.Drawing.Size(72, 17); this.radioButton3.TabIndex = 2; this.radioButton3.TabStop = true; this.radioButton3.Text = "VBA Vivid"; this.radioButton3.UseVisualStyleBackColor = true; this.radioButton3.CheckedChanged += new System.EventHandler(this.RadioButton1_CheckedChanged); // // radioButton4 // this.radioButton4.AutoSize = true; this.radioButton4.Location = new System.Drawing.Point(6, 88); this.radioButton4.Name = "radioButton4"; this.radioButton4.Size = new System.Drawing.Size(92, 17); this.radioButton4.TabIndex = 1; this.radioButton4.TabStop = true; this.radioButton4.Text = "VBA Accurate"; this.radioButton4.UseVisualStyleBackColor = true; this.radioButton4.CheckedChanged += new System.EventHandler(this.RadioButton1_CheckedChanged); // // radioButton2 // this.radioButton2.AutoSize = true; this.radioButton2.Location = new System.Drawing.Point(6, 42); this.radioButton2.Name = "radioButton2"; this.radioButton2.Size = new System.Drawing.Size(48, 17); this.radioButton2.TabIndex = 1; this.radioButton2.TabStop = true; this.radioButton2.Text = "Vivid"; this.radioButton2.UseVisualStyleBackColor = true; this.radioButton2.CheckedChanged += new System.EventHandler(this.RadioButton1_CheckedChanged); // // radioButton1 // this.radioButton1.AutoSize = true; this.radioButton1.Location = new System.Drawing.Point(6, 19); this.radioButton1.Name = "radioButton1"; this.radioButton1.Size = new System.Drawing.Size(71, 17); this.radioButton1.TabIndex = 0; this.radioButton1.TabStop = true; this.radioButton1.Text = "Gambatte"; this.radioButton1.UseVisualStyleBackColor = true; this.radioButton1.CheckedChanged += new System.EventHandler(this.RadioButton1_CheckedChanged); // // groupBox2 // this.groupBox2.Controls.Add(this.bmpView1); this.groupBox2.Location = new System.Drawing.Point(150, 12); this.groupBox2.Name = "groupBox2"; this.groupBox2.Size = new System.Drawing.Size(268, 153); this.groupBox2.TabIndex = 2; this.groupBox2.TabStop = false; this.groupBox2.Text = "Preview"; // // bmpView1 // this.bmpView1.Location = new System.Drawing.Point(6, 19); this.bmpView1.Name = "bmpView1"; this.bmpView1.Size = new System.Drawing.Size(256, 128); this.bmpView1.TabIndex = 3; this.bmpView1.Text = "bmpView1"; // // buttonOK // this.buttonOK.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.buttonOK.DialogResult = System.Windows.Forms.DialogResult.OK; this.buttonOK.Location = new System.Drawing.Point(263, 171); this.buttonOK.Name = "buttonOK"; this.buttonOK.Size = new System.Drawing.Size(75, 23); this.buttonOK.TabIndex = 3; this.buttonOK.Text = "OK"; this.buttonOK.UseVisualStyleBackColor = true; // // buttonCancel // this.buttonCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.buttonCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.buttonCancel.Location = new System.Drawing.Point(344, 171); this.buttonCancel.Name = "buttonCancel"; this.buttonCancel.Size = new System.Drawing.Size(75, 23); this.buttonCancel.TabIndex = 4; this.buttonCancel.Text = "Cancel"; this.buttonCancel.UseVisualStyleBackColor = true; // // radioButton7 // this.radioButton7.AutoSize = true; this.radioButton7.Location = new System.Drawing.Point(6, 157); this.radioButton7.Name = "radioButton7"; this.radioButton7.Size = new System.Drawing.Size(85, 17); this.radioButton7.TabIndex = 4; this.radioButton7.TabStop = true; this.radioButton7.Text = "Libretro GBC"; this.radioButton7.UseVisualStyleBackColor = true; this.radioButton7.CheckedChanged += new System.EventHandler(this.RadioButton1_CheckedChanged); // // CGBColorChooserForm // this.AcceptButton = this.buttonOK; this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.CancelButton = this.buttonCancel; this.ClientSize = new System.Drawing.Size(431, 206); this.Controls.Add(this.buttonCancel); this.Controls.Add(this.buttonOK); this.Controls.Add(this.groupBox2); this.Controls.Add(this.groupBox1); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle; this.Icon = global::BizHawk.Client.EmuHawk.Properties.Resources.gambatte_MultiSize; this.Name = "CGBColorChooserForm"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.Text = "Game Boy Color Palette Config"; this.groupBox1.ResumeLayout(false); this.groupBox1.PerformLayout(); this.groupBox2.ResumeLayout(false); this.ResumeLayout(false); } #endregion private System.Windows.Forms.GroupBox groupBox1; private System.Windows.Forms.RadioButton radioButton2; private System.Windows.Forms.RadioButton radioButton1; private System.Windows.Forms.RadioButton radioButton5; private System.Windows.Forms.RadioButton radioButton3; private System.Windows.Forms.RadioButton radioButton4; private System.Windows.Forms.GroupBox groupBox2; private BmpView bmpView1; private System.Windows.Forms.Button buttonOK; private System.Windows.Forms.Button buttonCancel; private System.Windows.Forms.RadioButton radioButton6; private System.Windows.Forms.RadioButton radioButton7; } }
41.253333
155
0.71504
[ "MIT" ]
diddily/BizHawk
src/BizHawk.Client.EmuHawk/config/GB/CGBColorChooserForm.Designer.cs
9,284
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Remote { /// <summary> /// Abstract the name of a remote service. /// </summary> /// <remarks> /// Allows partner teams to specify bitness-specific service name, while we can use bitness agnostic id for well-known services. /// TODO: Update LUT and SBD to use well-known ids and remove this abstraction (https://github.com/dotnet/roslyn/issues/44327). /// </remarks> internal readonly struct RemoteServiceName : IEquatable<RemoteServiceName> { internal const string Prefix = "roslyn"; internal const string Suffix64 = "64"; internal const string SuffixServerGC = "S"; internal const string IntelliCodeServiceName = "pythia"; internal const string RazorServiceName = "razorLanguageService"; internal const string UnitTestingAnalysisServiceName = "UnitTestingAnalysis"; internal const string LiveUnitTestingBuildServiceName = "LiveUnitTestingBuild"; internal const string UnitTestingSourceLookupServiceName = "UnitTestingSourceLookup"; public readonly WellKnownServiceHubService WellKnownService; public readonly string? CustomServiceName; public RemoteServiceName(WellKnownServiceHubService wellKnownService) { WellKnownService = wellKnownService; CustomServiceName = null; } /// <summary> /// Exact service name - must be reflect the bitness of the ServiceHub process. /// </summary> public RemoteServiceName(string customServiceName) { WellKnownService = WellKnownServiceHubService.None; CustomServiceName = customServiceName; } public string ToString(bool isRemoteHost64Bit, bool isRemoteHostServerGC) { return CustomServiceName ?? (WellKnownService, isRemoteHost64Bit, isRemoteHostServerGC) switch { (WellKnownServiceHubService.RemoteHost, false, _) => Prefix + nameof(WellKnownServiceHubService.RemoteHost), (WellKnownServiceHubService.RemoteHost, true, false) => Prefix + nameof(WellKnownServiceHubService.RemoteHost) + Suffix64, (WellKnownServiceHubService.RemoteHost, true, true) => Prefix + nameof(WellKnownServiceHubService.RemoteHost) + Suffix64 + SuffixServerGC, (WellKnownServiceHubService.IntelliCode, false, _) => IntelliCodeServiceName, (WellKnownServiceHubService.IntelliCode, true, false) => IntelliCodeServiceName + Suffix64, (WellKnownServiceHubService.IntelliCode, true, true) => IntelliCodeServiceName + Suffix64 + SuffixServerGC, (WellKnownServiceHubService.Razor, false, _) => RazorServiceName, (WellKnownServiceHubService.Razor, true, false) => RazorServiceName + Suffix64, (WellKnownServiceHubService.Razor, true, true) => RazorServiceName + Suffix64 + SuffixServerGC, (WellKnownServiceHubService.UnitTestingAnalysisService, false, _) => UnitTestingAnalysisServiceName, (WellKnownServiceHubService.UnitTestingAnalysisService, true, false) => UnitTestingAnalysisServiceName + Suffix64, (WellKnownServiceHubService.UnitTestingAnalysisService, true, true) => UnitTestingAnalysisServiceName + Suffix64 + SuffixServerGC, (WellKnownServiceHubService.LiveUnitTestingBuildService, false, _) => LiveUnitTestingBuildServiceName, (WellKnownServiceHubService.LiveUnitTestingBuildService, true, false) => LiveUnitTestingBuildServiceName + Suffix64, (WellKnownServiceHubService.LiveUnitTestingBuildService, true, true) => LiveUnitTestingBuildServiceName + Suffix64 + SuffixServerGC, (WellKnownServiceHubService.UnitTestingSourceLookupService, false, _) => UnitTestingSourceLookupServiceName, (WellKnownServiceHubService.UnitTestingSourceLookupService, true, false) => UnitTestingSourceLookupServiceName + Suffix64, (WellKnownServiceHubService.UnitTestingSourceLookupService, true, true) => UnitTestingSourceLookupServiceName + Suffix64 + SuffixServerGC, _ => throw ExceptionUtilities.UnexpectedValue(WellKnownService), }; } public override bool Equals(object? obj) => obj is RemoteServiceName name && Equals(name); public override int GetHashCode() => Hash.Combine(CustomServiceName, (int)WellKnownService); public bool Equals(RemoteServiceName other) => CustomServiceName == other.CustomServiceName && WellKnownService == other.WellKnownService; public static bool operator ==(RemoteServiceName left, RemoteServiceName right) => left.Equals(right); public static bool operator !=(RemoteServiceName left, RemoteServiceName right) => !(left == right); public static implicit operator RemoteServiceName( WellKnownServiceHubService wellKnownService ) => new(wellKnownService); } }
52.763636
132
0.646106
[ "MIT" ]
belav/roslyn
src/Workspaces/Core/Portable/Remote/RemoteServiceName.cs
5,806
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics; using System.Reflection.Metadata.Ecma335; using System.Runtime.CompilerServices; namespace System.Reflection.Metadata { public partial class MetadataReader { internal const string ClrPrefix = "<CLR>"; internal static readonly byte[] WinRTPrefix = new[] { (byte)'<', (byte)'W', (byte)'i', (byte)'n', (byte)'R', (byte)'T', (byte)'>' }; #region Projection Tables // Maps names of projected types to projection information for each type. // Both arrays are of the same length and sorted by the type name. private static string[]? s_projectedTypeNames; private static ProjectionInfo[]? s_projectionInfos; private readonly struct ProjectionInfo { public readonly string WinRTNamespace; public readonly StringHandle.VirtualIndex ClrNamespace; public readonly StringHandle.VirtualIndex ClrName; public readonly AssemblyReferenceHandle.VirtualIndex AssemblyRef; public readonly TypeDefTreatment Treatment; public readonly TypeRefSignatureTreatment SignatureTreatment; public readonly bool IsIDisposable; public ProjectionInfo( string winRtNamespace, StringHandle.VirtualIndex clrNamespace, StringHandle.VirtualIndex clrName, AssemblyReferenceHandle.VirtualIndex clrAssembly, TypeDefTreatment treatment = TypeDefTreatment.RedirectedToClrType, TypeRefSignatureTreatment signatureTreatment = TypeRefSignatureTreatment.None, bool isIDisposable = false) { this.WinRTNamespace = winRtNamespace; this.ClrNamespace = clrNamespace; this.ClrName = clrName; this.AssemblyRef = clrAssembly; this.Treatment = treatment; this.SignatureTreatment = signatureTreatment; this.IsIDisposable = isIDisposable; } } private TypeDefTreatment GetWellKnownTypeDefinitionTreatment(TypeDefinitionHandle typeDef) { InitializeProjectedTypes(); StringHandle name = TypeDefTable.GetName(typeDef); int index = StringHeap.BinarySearchRaw(s_projectedTypeNames!, name); if (index < 0) { return TypeDefTreatment.None; } StringHandle namespaceName = TypeDefTable.GetNamespace(typeDef); if (StringHeap.EqualsRaw(namespaceName, StringHeap.GetVirtualString(s_projectionInfos![index].ClrNamespace))) { return s_projectionInfos[index].Treatment; } // TODO: we can avoid this comparison if info.DotNetNamespace == info.WinRtNamespace if (StringHeap.EqualsRaw(namespaceName, s_projectionInfos[index].WinRTNamespace)) { return s_projectionInfos[index].Treatment | TypeDefTreatment.MarkInternalFlag; } return TypeDefTreatment.None; } private int GetProjectionIndexForTypeReference(TypeReferenceHandle typeRef, out bool isIDisposable) { InitializeProjectedTypes(); int index = StringHeap.BinarySearchRaw(s_projectedTypeNames!, TypeRefTable.GetName(typeRef)); if (index >= 0 && StringHeap.EqualsRaw(TypeRefTable.GetNamespace(typeRef), s_projectionInfos![index].WinRTNamespace)) { isIDisposable = s_projectionInfos[index].IsIDisposable; return index; } isIDisposable = false; return -1; } internal static AssemblyReferenceHandle GetProjectedAssemblyRef(int projectionIndex) { Debug.Assert(s_projectionInfos != null && projectionIndex >= 0 && projectionIndex < s_projectionInfos.Length); return AssemblyReferenceHandle.FromVirtualIndex(s_projectionInfos[projectionIndex].AssemblyRef); } internal static StringHandle GetProjectedName(int projectionIndex) { Debug.Assert(s_projectionInfos != null && projectionIndex >= 0 && projectionIndex < s_projectionInfos.Length); return StringHandle.FromVirtualIndex(s_projectionInfos[projectionIndex].ClrName); } internal static StringHandle GetProjectedNamespace(int projectionIndex) { Debug.Assert(s_projectionInfos != null && projectionIndex >= 0 && projectionIndex < s_projectionInfos.Length); return StringHandle.FromVirtualIndex(s_projectionInfos[projectionIndex].ClrNamespace); } internal static TypeRefSignatureTreatment GetProjectedSignatureTreatment(int projectionIndex) { Debug.Assert(s_projectionInfos != null && projectionIndex >= 0 && projectionIndex < s_projectionInfos.Length); return s_projectionInfos[projectionIndex].SignatureTreatment; } private static void InitializeProjectedTypes() { if (s_projectedTypeNames == null || s_projectionInfos == null) { var systemRuntimeWindowsRuntime = AssemblyReferenceHandle.VirtualIndex.System_Runtime_WindowsRuntime; var systemRuntime = AssemblyReferenceHandle.VirtualIndex.System_Runtime; var systemObjectModel = AssemblyReferenceHandle.VirtualIndex.System_ObjectModel; var systemRuntimeWindowsUiXaml = AssemblyReferenceHandle.VirtualIndex.System_Runtime_WindowsRuntime_UI_Xaml; var systemRuntimeInterop = AssemblyReferenceHandle.VirtualIndex.System_Runtime_InteropServices_WindowsRuntime; var systemNumericsVectors = AssemblyReferenceHandle.VirtualIndex.System_Numerics_Vectors; // sorted by name var keys = new string[50]; var values = new ProjectionInfo[50]; int k = 0, v = 0; // WARNING: Keys must be sorted by name and must only contain ASCII characters. WinRTNamespace must also be ASCII only. keys[k++] = "AttributeTargets"; values[v++] = new ProjectionInfo("Windows.Foundation.Metadata", StringHandle.VirtualIndex.System, StringHandle.VirtualIndex.AttributeTargets, systemRuntime); keys[k++] = "AttributeUsageAttribute"; values[v++] = new ProjectionInfo("Windows.Foundation.Metadata", StringHandle.VirtualIndex.System, StringHandle.VirtualIndex.AttributeUsageAttribute, systemRuntime, treatment: TypeDefTreatment.RedirectedToClrAttribute); keys[k++] = "Color"; values[v++] = new ProjectionInfo("Windows.UI", StringHandle.VirtualIndex.Windows_UI, StringHandle.VirtualIndex.Color, systemRuntimeWindowsRuntime); keys[k++] = "CornerRadius"; values[v++] = new ProjectionInfo("Windows.UI.Xaml", StringHandle.VirtualIndex.Windows_UI_Xaml, StringHandle.VirtualIndex.CornerRadius, systemRuntimeWindowsUiXaml); keys[k++] = "DateTime"; values[v++] = new ProjectionInfo("Windows.Foundation", StringHandle.VirtualIndex.System, StringHandle.VirtualIndex.DateTimeOffset, systemRuntime); keys[k++] = "Duration"; values[v++] = new ProjectionInfo("Windows.UI.Xaml", StringHandle.VirtualIndex.Windows_UI_Xaml, StringHandle.VirtualIndex.Duration, systemRuntimeWindowsUiXaml); keys[k++] = "DurationType"; values[v++] = new ProjectionInfo("Windows.UI.Xaml", StringHandle.VirtualIndex.Windows_UI_Xaml, StringHandle.VirtualIndex.DurationType, systemRuntimeWindowsUiXaml); keys[k++] = "EventHandler`1"; values[v++] = new ProjectionInfo("Windows.Foundation", StringHandle.VirtualIndex.System, StringHandle.VirtualIndex.EventHandler1, systemRuntime); keys[k++] = "EventRegistrationToken"; values[v++] = new ProjectionInfo("Windows.Foundation", StringHandle.VirtualIndex.System_Runtime_InteropServices_WindowsRuntime, StringHandle.VirtualIndex.EventRegistrationToken, systemRuntimeInterop); keys[k++] = "GeneratorPosition"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Controls.Primitives", StringHandle.VirtualIndex.Windows_UI_Xaml_Controls_Primitives, StringHandle.VirtualIndex.GeneratorPosition, systemRuntimeWindowsUiXaml); keys[k++] = "GridLength"; values[v++] = new ProjectionInfo("Windows.UI.Xaml", StringHandle.VirtualIndex.Windows_UI_Xaml, StringHandle.VirtualIndex.GridLength, systemRuntimeWindowsUiXaml); keys[k++] = "GridUnitType"; values[v++] = new ProjectionInfo("Windows.UI.Xaml", StringHandle.VirtualIndex.Windows_UI_Xaml, StringHandle.VirtualIndex.GridUnitType, systemRuntimeWindowsUiXaml); keys[k++] = "HResult"; values[v++] = new ProjectionInfo("Windows.Foundation", StringHandle.VirtualIndex.System, StringHandle.VirtualIndex.Exception, systemRuntime, signatureTreatment: TypeRefSignatureTreatment.ProjectedToClass); keys[k++] = "IBindableIterable"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Interop", StringHandle.VirtualIndex.System_Collections, StringHandle.VirtualIndex.IEnumerable, systemRuntime); keys[k++] = "IBindableVector"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Interop", StringHandle.VirtualIndex.System_Collections, StringHandle.VirtualIndex.IList, systemRuntime); keys[k++] = "IClosable"; values[v++] = new ProjectionInfo("Windows.Foundation", StringHandle.VirtualIndex.System, StringHandle.VirtualIndex.IDisposable, systemRuntime, isIDisposable: true); keys[k++] = "ICommand"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Input", StringHandle.VirtualIndex.System_Windows_Input, StringHandle.VirtualIndex.ICommand, systemObjectModel); keys[k++] = "IIterable`1"; values[v++] = new ProjectionInfo("Windows.Foundation.Collections", StringHandle.VirtualIndex.System_Collections_Generic, StringHandle.VirtualIndex.IEnumerable1, systemRuntime); keys[k++] = "IKeyValuePair`2"; values[v++] = new ProjectionInfo("Windows.Foundation.Collections", StringHandle.VirtualIndex.System_Collections_Generic, StringHandle.VirtualIndex.KeyValuePair2, systemRuntime, signatureTreatment: TypeRefSignatureTreatment.ProjectedToValueType); keys[k++] = "IMapView`2"; values[v++] = new ProjectionInfo("Windows.Foundation.Collections", StringHandle.VirtualIndex.System_Collections_Generic, StringHandle.VirtualIndex.IReadOnlyDictionary2, systemRuntime); keys[k++] = "IMap`2"; values[v++] = new ProjectionInfo("Windows.Foundation.Collections", StringHandle.VirtualIndex.System_Collections_Generic, StringHandle.VirtualIndex.IDictionary2, systemRuntime); keys[k++] = "INotifyCollectionChanged"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Interop", StringHandle.VirtualIndex.System_Collections_Specialized, StringHandle.VirtualIndex.INotifyCollectionChanged, systemObjectModel); keys[k++] = "INotifyPropertyChanged"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Data", StringHandle.VirtualIndex.System_ComponentModel, StringHandle.VirtualIndex.INotifyPropertyChanged, systemObjectModel); keys[k++] = "IReference`1"; values[v++] = new ProjectionInfo("Windows.Foundation", StringHandle.VirtualIndex.System, StringHandle.VirtualIndex.Nullable1, systemRuntime, signatureTreatment: TypeRefSignatureTreatment.ProjectedToValueType); keys[k++] = "IVectorView`1"; values[v++] = new ProjectionInfo("Windows.Foundation.Collections", StringHandle.VirtualIndex.System_Collections_Generic, StringHandle.VirtualIndex.IReadOnlyList1, systemRuntime); keys[k++] = "IVector`1"; values[v++] = new ProjectionInfo("Windows.Foundation.Collections", StringHandle.VirtualIndex.System_Collections_Generic, StringHandle.VirtualIndex.IList1, systemRuntime); keys[k++] = "KeyTime"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Media.Animation", StringHandle.VirtualIndex.Windows_UI_Xaml_Media_Animation, StringHandle.VirtualIndex.KeyTime, systemRuntimeWindowsUiXaml); keys[k++] = "Matrix"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Media", StringHandle.VirtualIndex.Windows_UI_Xaml_Media, StringHandle.VirtualIndex.Matrix, systemRuntimeWindowsUiXaml); keys[k++] = "Matrix3D"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Media.Media3D", StringHandle.VirtualIndex.Windows_UI_Xaml_Media_Media3D, StringHandle.VirtualIndex.Matrix3D, systemRuntimeWindowsUiXaml); keys[k++] = "Matrix3x2"; values[v++] = new ProjectionInfo("Windows.Foundation.Numerics", StringHandle.VirtualIndex.System_Numerics, StringHandle.VirtualIndex.Matrix3x2, systemNumericsVectors); keys[k++] = "Matrix4x4"; values[v++] = new ProjectionInfo("Windows.Foundation.Numerics", StringHandle.VirtualIndex.System_Numerics, StringHandle.VirtualIndex.Matrix4x4, systemNumericsVectors); keys[k++] = "NotifyCollectionChangedAction"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Interop", StringHandle.VirtualIndex.System_Collections_Specialized, StringHandle.VirtualIndex.NotifyCollectionChangedAction, systemObjectModel); keys[k++] = "NotifyCollectionChangedEventArgs"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Interop", StringHandle.VirtualIndex.System_Collections_Specialized, StringHandle.VirtualIndex.NotifyCollectionChangedEventArgs, systemObjectModel); keys[k++] = "NotifyCollectionChangedEventHandler"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Interop", StringHandle.VirtualIndex.System_Collections_Specialized, StringHandle.VirtualIndex.NotifyCollectionChangedEventHandler, systemObjectModel); keys[k++] = "Plane"; values[v++] = new ProjectionInfo("Windows.Foundation.Numerics", StringHandle.VirtualIndex.System_Numerics, StringHandle.VirtualIndex.Plane, systemNumericsVectors); keys[k++] = "Point"; values[v++] = new ProjectionInfo("Windows.Foundation", StringHandle.VirtualIndex.Windows_Foundation, StringHandle.VirtualIndex.Point, systemRuntimeWindowsRuntime); keys[k++] = "PropertyChangedEventArgs"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Data", StringHandle.VirtualIndex.System_ComponentModel, StringHandle.VirtualIndex.PropertyChangedEventArgs, systemObjectModel); keys[k++] = "PropertyChangedEventHandler"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Data", StringHandle.VirtualIndex.System_ComponentModel, StringHandle.VirtualIndex.PropertyChangedEventHandler, systemObjectModel); keys[k++] = "Quaternion"; values[v++] = new ProjectionInfo("Windows.Foundation.Numerics", StringHandle.VirtualIndex.System_Numerics, StringHandle.VirtualIndex.Quaternion, systemNumericsVectors); keys[k++] = "Rect"; values[v++] = new ProjectionInfo("Windows.Foundation", StringHandle.VirtualIndex.Windows_Foundation, StringHandle.VirtualIndex.Rect, systemRuntimeWindowsRuntime); keys[k++] = "RepeatBehavior"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Media.Animation", StringHandle.VirtualIndex.Windows_UI_Xaml_Media_Animation, StringHandle.VirtualIndex.RepeatBehavior, systemRuntimeWindowsUiXaml); keys[k++] = "RepeatBehaviorType"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Media.Animation", StringHandle.VirtualIndex.Windows_UI_Xaml_Media_Animation, StringHandle.VirtualIndex.RepeatBehaviorType, systemRuntimeWindowsUiXaml); keys[k++] = "Size"; values[v++] = new ProjectionInfo("Windows.Foundation", StringHandle.VirtualIndex.Windows_Foundation, StringHandle.VirtualIndex.Size, systemRuntimeWindowsRuntime); keys[k++] = "Thickness"; values[v++] = new ProjectionInfo("Windows.UI.Xaml", StringHandle.VirtualIndex.Windows_UI_Xaml, StringHandle.VirtualIndex.Thickness, systemRuntimeWindowsUiXaml); keys[k++] = "TimeSpan"; values[v++] = new ProjectionInfo("Windows.Foundation", StringHandle.VirtualIndex.System, StringHandle.VirtualIndex.TimeSpan, systemRuntime); keys[k++] = "TypeName"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Interop", StringHandle.VirtualIndex.System, StringHandle.VirtualIndex.Type, systemRuntime, signatureTreatment: TypeRefSignatureTreatment.ProjectedToClass); keys[k++] = "Uri"; values[v++] = new ProjectionInfo("Windows.Foundation", StringHandle.VirtualIndex.System, StringHandle.VirtualIndex.Uri, systemRuntime); keys[k++] = "Vector2"; values[v++] = new ProjectionInfo("Windows.Foundation.Numerics", StringHandle.VirtualIndex.System_Numerics, StringHandle.VirtualIndex.Vector2, systemNumericsVectors); keys[k++] = "Vector3"; values[v++] = new ProjectionInfo("Windows.Foundation.Numerics", StringHandle.VirtualIndex.System_Numerics, StringHandle.VirtualIndex.Vector3, systemNumericsVectors); keys[k++] = "Vector4"; values[v++] = new ProjectionInfo("Windows.Foundation.Numerics", StringHandle.VirtualIndex.System_Numerics, StringHandle.VirtualIndex.Vector4, systemNumericsVectors); Debug.Assert(k == keys.Length && v == keys.Length && k == v); AssertSorted(keys); s_projectedTypeNames = keys; s_projectionInfos = values; } } [Conditional("DEBUG")] private static void AssertSorted(string[] keys) { for (int i = 0; i < keys.Length - 1; i++) { Debug.Assert(string.CompareOrdinal(keys[i], keys[i + 1]) < 0); } } // test only internal static string[] GetProjectedTypeNames() { InitializeProjectedTypes(); return s_projectedTypeNames!; } #endregion private static uint TreatmentAndRowId(byte treatment, int rowId) { return ((uint)treatment << TokenTypeIds.RowIdBitCount) | (uint)rowId; } #region TypeDef [MethodImpl(MethodImplOptions.NoInlining)] internal uint CalculateTypeDefTreatmentAndRowId(TypeDefinitionHandle handle) { Debug.Assert(_metadataKind != MetadataKind.Ecma335); TypeDefTreatment treatment; TypeAttributes flags = TypeDefTable.GetFlags(handle); EntityHandle extends = TypeDefTable.GetExtends(handle); if ((flags & TypeAttributes.WindowsRuntime) != 0) { if (_metadataKind == MetadataKind.WindowsMetadata) { treatment = GetWellKnownTypeDefinitionTreatment(handle); if (treatment != TypeDefTreatment.None) { return TreatmentAndRowId((byte)treatment, handle.RowId); } // Is this an attribute? if (extends.Kind == HandleKind.TypeReference && IsSystemAttribute((TypeReferenceHandle)extends)) { treatment = TypeDefTreatment.NormalAttribute; } else { treatment = TypeDefTreatment.NormalNonAttribute; } } else if (_metadataKind == MetadataKind.ManagedWindowsMetadata && NeedsWinRTPrefix(flags, extends)) { // WinMDExp emits two versions of RuntimeClasses and Enums: // // public class Foo {} // the WinRT reference class // internal class <CLR>Foo {} // the implementation class that we want WinRT consumers to ignore // // The adapter's job is to undo WinMDExp's transformations. I.e. turn the above into: // // internal class <WinRT>Foo {} // the WinRT reference class that we want CLR consumers to ignore // public class Foo {} // the implementation class // // We only add the <WinRT> prefix here since the WinRT view is the only view that is marked WindowsRuntime // De-mangling the CLR name is done below. // tomat: The CLR adapter implements a back-compat quirk: Enums exported with an older WinMDExp have only one version // not marked with tdSpecialName. These enums should *not* be mangled and flipped to private. // We don't implement this flag since the WinMDs produced by the older WinMDExp are not used in the wild. treatment = TypeDefTreatment.PrefixWinRTName; } else { treatment = TypeDefTreatment.None; } // Scan through Custom Attributes on type, looking for interesting bits. We only // need to do this for RuntimeClasses if ((treatment == TypeDefTreatment.PrefixWinRTName || treatment == TypeDefTreatment.NormalNonAttribute)) { if ((flags & TypeAttributes.Interface) == 0 && HasAttribute(handle, "Windows.UI.Xaml", "TreatAsAbstractComposableClassAttribute")) { treatment |= TypeDefTreatment.MarkAbstractFlag; } } } else if (_metadataKind == MetadataKind.ManagedWindowsMetadata && IsClrImplementationType(handle)) { // <CLR> implementation classes are not marked WindowsRuntime, but still need to be modified // by the adapter. treatment = TypeDefTreatment.UnmangleWinRTName; } else { treatment = TypeDefTreatment.None; } return TreatmentAndRowId((byte)treatment, handle.RowId); } private bool IsClrImplementationType(TypeDefinitionHandle typeDef) { var attrs = TypeDefTable.GetFlags(typeDef); if ((attrs & (TypeAttributes.VisibilityMask | TypeAttributes.SpecialName)) != TypeAttributes.SpecialName) { return false; } return StringHeap.StartsWithRaw(TypeDefTable.GetName(typeDef), ClrPrefix); } #endregion #region TypeRef internal uint CalculateTypeRefTreatmentAndRowId(TypeReferenceHandle handle) { Debug.Assert(_metadataKind != MetadataKind.Ecma335); bool isIDisposable; int projectionIndex = GetProjectionIndexForTypeReference(handle, out isIDisposable); if (projectionIndex >= 0) { return TreatmentAndRowId((byte)TypeRefTreatment.UseProjectionInfo, projectionIndex); } else { return TreatmentAndRowId((byte)GetSpecialTypeRefTreatment(handle), handle.RowId); } } private TypeRefTreatment GetSpecialTypeRefTreatment(TypeReferenceHandle handle) { if (StringHeap.EqualsRaw(TypeRefTable.GetNamespace(handle), "System")) { StringHandle name = TypeRefTable.GetName(handle); if (StringHeap.EqualsRaw(name, "MulticastDelegate")) { return TypeRefTreatment.SystemDelegate; } if (StringHeap.EqualsRaw(name, "Attribute")) { return TypeRefTreatment.SystemAttribute; } } return TypeRefTreatment.None; } private bool IsSystemAttribute(TypeReferenceHandle handle) { return StringHeap.EqualsRaw(TypeRefTable.GetNamespace(handle), "System") && StringHeap.EqualsRaw(TypeRefTable.GetName(handle), "Attribute"); } private bool NeedsWinRTPrefix(TypeAttributes flags, EntityHandle extends) { if ((flags & (TypeAttributes.VisibilityMask | TypeAttributes.Interface)) != TypeAttributes.Public) { return false; } if (extends.Kind != HandleKind.TypeReference) { return false; } // Check if the type is a delegate, struct, or attribute TypeReferenceHandle extendsRefHandle = (TypeReferenceHandle)extends; if (StringHeap.EqualsRaw(TypeRefTable.GetNamespace(extendsRefHandle), "System")) { StringHandle nameHandle = TypeRefTable.GetName(extendsRefHandle); if (StringHeap.EqualsRaw(nameHandle, "MulticastDelegate") || StringHeap.EqualsRaw(nameHandle, "ValueType") || StringHeap.EqualsRaw(nameHandle, "Attribute")) { return false; } } return true; } #endregion #region MethodDef private uint CalculateMethodDefTreatmentAndRowId(MethodDefinitionHandle methodDef) { MethodDefTreatment treatment = MethodDefTreatment.Implementation; TypeDefinitionHandle parentTypeDef = GetDeclaringType(methodDef); TypeAttributes parentFlags = TypeDefTable.GetFlags(parentTypeDef); if ((parentFlags & TypeAttributes.WindowsRuntime) != 0) { if (IsClrImplementationType(parentTypeDef)) { treatment = MethodDefTreatment.Implementation; } else if (parentFlags.IsNested()) { treatment = MethodDefTreatment.Implementation; } else if ((parentFlags & TypeAttributes.Interface) != 0) { treatment = MethodDefTreatment.InterfaceMethod; } else if (_metadataKind == MetadataKind.ManagedWindowsMetadata && (parentFlags & TypeAttributes.Public) == 0) { treatment = MethodDefTreatment.Implementation; } else { treatment = MethodDefTreatment.Other; var parentBaseType = TypeDefTable.GetExtends(parentTypeDef); if (parentBaseType.Kind == HandleKind.TypeReference) { switch (GetSpecialTypeRefTreatment((TypeReferenceHandle)parentBaseType)) { case TypeRefTreatment.SystemAttribute: treatment = MethodDefTreatment.AttributeMethod; break; case TypeRefTreatment.SystemDelegate: treatment = MethodDefTreatment.DelegateMethod | MethodDefTreatment.MarkPublicFlag; break; } } } } if (treatment == MethodDefTreatment.Other) { // we want to hide the method if it implements // only redirected interfaces // We also want to check if the methodImpl is IClosable.Close, // so we can change the name bool seenRedirectedInterfaces = false; bool seenNonRedirectedInterfaces = false; bool isIClosableClose = false; foreach (var methodImplHandle in new MethodImplementationHandleCollection(this, parentTypeDef)) { MethodImplementation methodImpl = GetMethodImplementation(methodImplHandle); if (methodImpl.MethodBody == methodDef) { EntityHandle declaration = methodImpl.MethodDeclaration; // See if this MethodImpl implements a redirected interface // In WinMD, MethodImpl will always use MemberRef and TypeRefs to refer to redirected interfaces, // even if they are in the same module. if (declaration.Kind == HandleKind.MemberReference && ImplementsRedirectedInterface((MemberReferenceHandle)declaration, out isIClosableClose)) { seenRedirectedInterfaces = true; if (isIClosableClose) { // This method implements IClosable.Close // Let's rename to IDisposable later // Once we know this implements IClosable.Close, we are done // looking break; } } else { // Now we know this implements a non-redirected interface // But we need to keep looking, just in case we got a methodimpl that // implements the IClosable.Close method and needs to be renamed seenNonRedirectedInterfaces = true; } } } if (isIClosableClose) { treatment = MethodDefTreatment.DisposeMethod; } else if (seenRedirectedInterfaces && !seenNonRedirectedInterfaces) { // Only hide if all the interfaces implemented are redirected treatment = MethodDefTreatment.HiddenInterfaceImplementation; } } // If treatment is other, then this is a non-managed WinRT runtime class definition // Find out about various bits that we apply via attributes and name parsing if (treatment == MethodDefTreatment.Other) { treatment |= GetMethodTreatmentFromCustomAttributes(methodDef); } return TreatmentAndRowId((byte)treatment, methodDef.RowId); } private MethodDefTreatment GetMethodTreatmentFromCustomAttributes(MethodDefinitionHandle methodDef) { MethodDefTreatment treatment = 0; foreach (var caHandle in GetCustomAttributes(methodDef)) { StringHandle namespaceHandle, nameHandle; if (!GetAttributeTypeNameRaw(caHandle, out namespaceHandle, out nameHandle)) { continue; } Debug.Assert(!namespaceHandle.IsVirtual && !nameHandle.IsVirtual); if (StringHeap.EqualsRaw(namespaceHandle, "Windows.UI.Xaml")) { if (StringHeap.EqualsRaw(nameHandle, "TreatAsPublicMethodAttribute")) { treatment |= MethodDefTreatment.MarkPublicFlag; } if (StringHeap.EqualsRaw(nameHandle, "TreatAsAbstractMethodAttribute")) { treatment |= MethodDefTreatment.MarkAbstractFlag; } } } return treatment; } #endregion #region FieldDef /// <summary> /// The backing field of a WinRT enumeration type is not public although the backing fields /// of managed enumerations are. To allow managed languages to directly access this field, /// it is made public by the metadata adapter. /// </summary> private uint CalculateFieldDefTreatmentAndRowId(FieldDefinitionHandle handle) { var flags = FieldTable.GetFlags(handle); FieldDefTreatment treatment = FieldDefTreatment.None; if ((flags & FieldAttributes.RTSpecialName) != 0 && StringHeap.EqualsRaw(FieldTable.GetName(handle), "value__")) { TypeDefinitionHandle typeDef = GetDeclaringType(handle); EntityHandle baseTypeHandle = TypeDefTable.GetExtends(typeDef); if (baseTypeHandle.Kind == HandleKind.TypeReference) { var typeRef = (TypeReferenceHandle)baseTypeHandle; if (StringHeap.EqualsRaw(TypeRefTable.GetName(typeRef), "Enum") && StringHeap.EqualsRaw(TypeRefTable.GetNamespace(typeRef), "System")) { treatment = FieldDefTreatment.EnumValue; } } } return TreatmentAndRowId((byte)treatment, handle.RowId); } #endregion #region MemberRef private uint CalculateMemberRefTreatmentAndRowId(MemberReferenceHandle handle) { MemberRefTreatment treatment; // We need to rename the MemberRef for IClosable.Close as well // so that the MethodImpl for the Dispose method can be correctly shown // as IDisposable.Dispose instead of IDisposable.Close bool isIDisposable; if (ImplementsRedirectedInterface(handle, out isIDisposable) && isIDisposable) { treatment = MemberRefTreatment.Dispose; } else { treatment = MemberRefTreatment.None; } return TreatmentAndRowId((byte)treatment, handle.RowId); } /// <summary> /// We want to know if a given method implements a redirected interface. /// For example, if we are given the method RemoveAt on a class "A" /// which implements the IVector interface (which is redirected /// to IList in .NET) then this method would return true. The most /// likely reason why we would want to know this is that we wish to hide /// (mark private) all methods which implement methods on a redirected /// interface. /// </summary> /// <param name="memberRef">The declaration token for the method</param> /// <param name="isIDisposable"> /// Returns true if the redirected interface is <see cref="IDisposable"/>. /// </param> /// <returns>True if the method implements a method on a redirected interface. /// False otherwise.</returns> private bool ImplementsRedirectedInterface(MemberReferenceHandle memberRef, out bool isIDisposable) { isIDisposable = false; EntityHandle parent = MemberRefTable.GetClass(memberRef); TypeReferenceHandle typeRef; if (parent.Kind == HandleKind.TypeReference) { typeRef = (TypeReferenceHandle)parent; } else if (parent.Kind == HandleKind.TypeSpecification) { BlobHandle blob = TypeSpecTable.GetSignature((TypeSpecificationHandle)parent); BlobReader sig = new BlobReader(BlobHeap.GetMemoryBlock(blob)); if (sig.Length < 2 || sig.ReadByte() != (byte)CorElementType.ELEMENT_TYPE_GENERICINST || sig.ReadByte() != (byte)CorElementType.ELEMENT_TYPE_CLASS) { return false; } EntityHandle token = sig.ReadTypeHandle(); if (token.Kind != HandleKind.TypeReference) { return false; } typeRef = (TypeReferenceHandle)token; } else { return false; } return GetProjectionIndexForTypeReference(typeRef, out isIDisposable) >= 0; } #endregion #region AssemblyRef private int FindMscorlibAssemblyRefNoProjection() { for (int i = 1; i <= AssemblyRefTable.NumberOfNonVirtualRows; i++) { if (StringHeap.EqualsRaw(AssemblyRefTable.GetName(i), "mscorlib")) { return i; } } throw new BadImageFormatException(SR.WinMDMissingMscorlibRef); } #endregion #region CustomAttribute internal CustomAttributeValueTreatment CalculateCustomAttributeValueTreatment(CustomAttributeHandle handle) { Debug.Assert(_metadataKind != MetadataKind.Ecma335); var parent = CustomAttributeTable.GetParent(handle); // Check for Windows.Foundation.Metadata.AttributeUsageAttribute. // WinMD rules: // - The attribute is only applicable on TypeDefs. // - Constructor must be a MemberRef with TypeRef. if (!IsWindowsAttributeUsageAttribute(parent, handle)) { return CustomAttributeValueTreatment.None; } var targetTypeDef = (TypeDefinitionHandle)parent; if (StringHeap.EqualsRaw(TypeDefTable.GetNamespace(targetTypeDef), "Windows.Foundation.Metadata")) { if (StringHeap.EqualsRaw(TypeDefTable.GetName(targetTypeDef), "VersionAttribute")) { return CustomAttributeValueTreatment.AttributeUsageVersionAttribute; } if (StringHeap.EqualsRaw(TypeDefTable.GetName(targetTypeDef), "DeprecatedAttribute")) { return CustomAttributeValueTreatment.AttributeUsageDeprecatedAttribute; } } bool allowMultiple = HasAttribute(targetTypeDef, "Windows.Foundation.Metadata", "AllowMultipleAttribute"); return allowMultiple ? CustomAttributeValueTreatment.AttributeUsageAllowMultiple : CustomAttributeValueTreatment.AttributeUsageAllowSingle; } private bool IsWindowsAttributeUsageAttribute(EntityHandle targetType, CustomAttributeHandle attributeHandle) { // Check for Windows.Foundation.Metadata.AttributeUsageAttribute. // WinMD rules: // - The attribute is only applicable on TypeDefs. // - Constructor must be a MemberRef with TypeRef. if (targetType.Kind != HandleKind.TypeDefinition) { return false; } var attributeCtor = CustomAttributeTable.GetConstructor(attributeHandle); if (attributeCtor.Kind != HandleKind.MemberReference) { return false; } var attributeType = MemberRefTable.GetClass((MemberReferenceHandle)attributeCtor); if (attributeType.Kind != HandleKind.TypeReference) { return false; } var attributeTypeRef = (TypeReferenceHandle)attributeType; return StringHeap.EqualsRaw(TypeRefTable.GetName(attributeTypeRef), "AttributeUsageAttribute") && StringHeap.EqualsRaw(TypeRefTable.GetNamespace(attributeTypeRef), "Windows.Foundation.Metadata"); } private bool HasAttribute(EntityHandle token, string asciiNamespaceName, string asciiTypeName) { foreach (var caHandle in GetCustomAttributes(token)) { StringHandle namespaceName, typeName; if (GetAttributeTypeNameRaw(caHandle, out namespaceName, out typeName) && StringHeap.EqualsRaw(typeName, asciiTypeName) && StringHeap.EqualsRaw(namespaceName, asciiNamespaceName)) { return true; } } return false; } private bool GetAttributeTypeNameRaw(CustomAttributeHandle caHandle, out StringHandle namespaceName, out StringHandle typeName) { namespaceName = typeName = default(StringHandle); EntityHandle typeDefOrRef = GetAttributeTypeRaw(caHandle); if (typeDefOrRef.IsNil) { return false; } if (typeDefOrRef.Kind == HandleKind.TypeReference) { TypeReferenceHandle typeRef = (TypeReferenceHandle)typeDefOrRef; var resolutionScope = TypeRefTable.GetResolutionScope(typeRef); if (!resolutionScope.IsNil && resolutionScope.Kind == HandleKind.TypeReference) { // we don't need to handle nested types return false; } // other resolution scopes don't affect full name typeName = TypeRefTable.GetName(typeRef); namespaceName = TypeRefTable.GetNamespace(typeRef); } else if (typeDefOrRef.Kind == HandleKind.TypeDefinition) { TypeDefinitionHandle typeDef = (TypeDefinitionHandle)typeDefOrRef; if (TypeDefTable.GetFlags(typeDef).IsNested()) { // we don't need to handle nested types return false; } typeName = TypeDefTable.GetName(typeDef); namespaceName = TypeDefTable.GetNamespace(typeDef); } else { // invalid metadata return false; } return true; } /// <summary> /// Returns the type definition or reference handle of the attribute type. /// </summary> /// <returns><see cref="TypeDefinitionHandle"/> or <see cref="TypeReferenceHandle"/> or nil token if the metadata is invalid and the type can't be determined.</returns> private EntityHandle GetAttributeTypeRaw(CustomAttributeHandle handle) { var ctor = CustomAttributeTable.GetConstructor(handle); if (ctor.Kind == HandleKind.MethodDefinition) { return GetDeclaringType((MethodDefinitionHandle)ctor); } if (ctor.Kind == HandleKind.MemberReference) { // In general the parent can be MethodDef, ModuleRef, TypeDef, TypeRef, or TypeSpec. // For attributes only TypeDef and TypeRef are applicable. EntityHandle typeDefOrRef = MemberRefTable.GetClass((MemberReferenceHandle)ctor); HandleKind handleType = typeDefOrRef.Kind; if (handleType == HandleKind.TypeReference || handleType == HandleKind.TypeDefinition) { return typeDefOrRef; } } return default(EntityHandle); } #endregion } }
51.861613
292
0.619904
[ "MIT" ]
2m0nd/runtime
src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/MetadataReader.WinMD.cs
43,097
C#
using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Linq; using System.Net; using System.Web; using System.Web.Mvc; using WebAppBusStation.Models; namespace WebAppBusStation.Controllers { public class flightsController : Controller { private bus_stationEntities db = new bus_stationEntities(); // GET: flights public ActionResult Index() { var flight = db.flight.Include(f => f.bus).Include(f => f.route); return View(flight.ToList()); } // GET: flights/Details/5 public ActionResult Details(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } flight flight = db.flight.Find(id); if (flight == null) { return HttpNotFound(); } return View(flight); } // GET: flights/Create public ActionResult Create() { ViewBag.ID_bus = new SelectList(db.bus, "ID_bus", "regist_number"); ViewBag.ID_route = new SelectList(db.route, "ID_route", "destination"); return View(); } // POST: flights/Create // Чтобы защититься от атак чрезмерной передачи данных, включите определенные свойства, для которых следует установить привязку. Дополнительные // сведения см. в статье https://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public ActionResult Create([Bind(Include = "ID_flight,driver,ID_bus,ID_route")] flight flight) { if (ModelState.IsValid) { db.flight.Add(flight); db.SaveChanges(); return RedirectToAction("Index"); } ViewBag.ID_bus = new SelectList(db.bus, "ID_bus", "regist_number", flight.ID_bus); ViewBag.ID_route = new SelectList(db.route, "ID_route", "destination", flight.ID_route); return View(flight); } // GET: flights/Edit/5 public ActionResult Edit(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } flight flight = db.flight.Find(id); if (flight == null) { return HttpNotFound(); } ViewBag.ID_bus = new SelectList(db.bus, "ID_bus", "regist_number", flight.ID_bus); ViewBag.ID_route = new SelectList(db.route, "ID_route", "destination", flight.ID_route); return View(flight); } // POST: flights/Edit/5 // Чтобы защититься от атак чрезмерной передачи данных, включите определенные свойства, для которых следует установить привязку. Дополнительные // сведения см. в статье https://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public ActionResult Edit([Bind(Include = "ID_flight,driver,ID_bus,ID_route")] flight flight) { if (ModelState.IsValid) { db.Entry(flight).State = EntityState.Modified; db.SaveChanges(); return RedirectToAction("Index"); } ViewBag.ID_bus = new SelectList(db.bus, "ID_bus", "regist_number", flight.ID_bus); ViewBag.ID_route = new SelectList(db.route, "ID_route", "destination", flight.ID_route); return View(flight); } // GET: flights/Delete/5 public ActionResult Delete(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } flight flight = db.flight.Find(id); if (flight == null) { return HttpNotFound(); } return View(flight); } // POST: flights/Delete/5 [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public ActionResult DeleteConfirmed(int id) { flight flight = db.flight.Find(id); db.flight.Remove(flight); db.SaveChanges(); return RedirectToAction("Index"); } protected override void Dispose(bool disposing) { if (disposing) { db.Dispose(); } base.Dispose(disposing); } } }
33.328467
152
0.555848
[ "MIT" ]
MegaRoks/BusStationApp
WebAppBusStation/Controllers/flightsController.cs
4,846
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("TheVinniPooh")] [assembly: AssemblyProduct("TheVinniPooh")] [assembly: AssemblyDescription("")] [assembly: AssemblyCompany("")] [assembly: AssemblyCopyright("Copyright © 2011")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. Only Windows // assemblies support COM. [assembly: ComVisible(false)] // On Windows, the following GUID is for the ID of the typelib if this // project is exposed to COM. On other platforms, it unique identifies the // title storage container when deploying this assembly to the device. [assembly: Guid("6cec6cbe-a40d-42a8-94f8-622dcd92c594")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // [assembly: AssemblyVersion("1.0.0.0")]
37.914286
77
0.755087
[ "MIT" ]
lionell/winnie_the_pooh_game
TheVinniPooh/TheVinniPooh/TheVinniPooh/Properties/AssemblyInfo.cs
1,330
C#
#region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; namespace LC.Newtonsoft.Json.Converters { /// <summary> /// Provides a base class for converting a <see cref="DateTime"/> to and from JSON. /// </summary> public abstract class DateTimeConverterBase : JsonConverter { /// <summary> /// Determines whether this instance can convert the specified object type. /// </summary> /// <param name="objectType">Type of the object.</param> /// <returns> /// <c>true</c> if this instance can convert the specified object type; otherwise, <c>false</c>. /// </returns> public override bool CanConvert(Type objectType) { if (objectType == typeof(DateTime) || objectType == typeof(DateTime?)) { return true; } #if HAVE_DATE_TIME_OFFSET if (objectType == typeof(DateTimeOffset) || objectType == typeof(DateTimeOffset?)) { return true; } #endif return false; } } }
37.689655
105
0.667429
[ "MIT" ]
leancloud/csharp-sdk
Libs/Newtonsoft.Json.AOT/Converters/DateTimeConverterBase.cs
2,188
C#
using EPiServer.Framework.Localization; using System; using EPiServer.Commerce.Order; namespace EPiServer.Reference.Commerce.Site.Features.Payment.PaymentMethods { public abstract class PaymentMethodBase { protected readonly LocalizationService _localizationService; protected PaymentMethodBase(LocalizationService localizationService) { _localizationService = localizationService; } public Guid PaymentMethodId { get; set; } public abstract IPayment CreatePayment(IOrderGroup orderGroup, decimal amount); public abstract void PostProcess(IPayment payment); public abstract bool ValidateData(); } }
28.875
87
0.735931
[ "Apache-2.0" ]
danghung1202/MyQuicksilverB2B
Sources/EPiServer.Reference.Commerce.Site/Features/Payment/PaymentMethods/PaymentMethodBase.cs
695
C#
/* * Copyright (c) 2015-2022 GraphDefined GmbH * This file is part of WWCP OCPI <https://github.com/OpenChargingCloud/WWCP_OCPI> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #region Usings using System; using org.GraphDefined.Vanaheimr.Illias; #endregion namespace cloud.charging.open.protocols.OCPIv2_1_1 { /// <summary> /// The unique identification of a country code. /// </summary> public struct CountryCode : IId<CountryCode> { #region Data // CiString(2) /// <summary> /// The internal identification. /// </summary> private readonly String InternalId; #endregion #region Properties /// <summary> /// Indicates whether this identification is null or empty. /// </summary> public Boolean IsNullOrEmpty => InternalId.IsNullOrEmpty(); /// <summary> /// The length of the country code identification. /// </summary> public UInt64 Length => (UInt64) (InternalId?.Length ?? 0); #endregion #region Constructor(s) /// <summary> /// Create a new country code identification based on the given string. /// </summary> /// <param name="String">The string representation of the country code identification.</param> private CountryCode(String String) { this.InternalId = String; } #endregion #region (static) Parse (Text) /// <summary> /// Parse the given string as a country code identification. /// </summary> /// <param name="Text">A text representation of a country code identification.</param> public static CountryCode Parse(String Text) { if (TryParse(Text, out CountryCode locationId)) return locationId; if (Text.IsNullOrEmpty()) throw new ArgumentNullException(nameof(Text), "The given text representation of a country code identification must not be null or empty!"); throw new ArgumentException("The given text representation of a country code identification is invalid!", nameof(Text)); } #endregion #region (static) TryParse(Text) /// <summary> /// Try to parse the given text as a country code identification. /// </summary> /// <param name="Text">A text representation of a country code identification.</param> public static CountryCode? TryParse(String Text) { if (TryParse(Text, out CountryCode locationId)) return locationId; return null; } #endregion #region (static) TryParse(Text, out LocationId) /// <summary> /// Try to parse the given text as a country code identification. /// </summary> /// <param name="Text">A text representation of a country code identification.</param> /// <param name="LocationId">The parsed country code identification.</param> public static Boolean TryParse(String Text, out CountryCode LocationId) { if (Text.IsNotNullOrEmpty()) { try { LocationId = new CountryCode(Text.Trim()); return true; } catch (Exception) { } } LocationId = default; return false; } #endregion #region Clone /// <summary> /// Clone this country code identification. /// </summary> public CountryCode Clone => new CountryCode( new String(InternalId?.ToCharArray()) ); #endregion #region Operator overloading #region Operator == (LocationId1, LocationId2) /// <summary> /// Compares two instances of this object. /// </summary> /// <param name="LocationId1">A country code identification.</param> /// <param name="LocationId2">Another country code identification.</param> /// <returns>true|false</returns> public static Boolean operator == (CountryCode LocationId1, CountryCode LocationId2) => LocationId1.Equals(LocationId2); #endregion #region Operator != (LocationId1, LocationId2) /// <summary> /// Compares two instances of this object. /// </summary> /// <param name="LocationId1">A country code identification.</param> /// <param name="LocationId2">Another country code identification.</param> /// <returns>true|false</returns> public static Boolean operator != (CountryCode LocationId1, CountryCode LocationId2) => !(LocationId1 == LocationId2); #endregion #region Operator < (LocationId1, LocationId2) /// <summary> /// Compares two instances of this object. /// </summary> /// <param name="LocationId1">A country code identification.</param> /// <param name="LocationId2">Another country code identification.</param> /// <returns>true|false</returns> public static Boolean operator < (CountryCode LocationId1, CountryCode LocationId2) => LocationId1.CompareTo(LocationId2) < 0; #endregion #region Operator <= (LocationId1, LocationId2) /// <summary> /// Compares two instances of this object. /// </summary> /// <param name="LocationId1">A country code identification.</param> /// <param name="LocationId2">Another country code identification.</param> /// <returns>true|false</returns> public static Boolean operator <= (CountryCode LocationId1, CountryCode LocationId2) => !(LocationId1 > LocationId2); #endregion #region Operator > (LocationId1, LocationId2) /// <summary> /// Compares two instances of this object. /// </summary> /// <param name="LocationId1">A country code identification.</param> /// <param name="LocationId2">Another country code identification.</param> /// <returns>true|false</returns> public static Boolean operator > (CountryCode LocationId1, CountryCode LocationId2) => LocationId1.CompareTo(LocationId2) > 0; #endregion #region Operator >= (LocationId1, LocationId2) /// <summary> /// Compares two instances of this object. /// </summary> /// <param name="LocationId1">A country code identification.</param> /// <param name="LocationId2">Another country code identification.</param> /// <returns>true|false</returns> public static Boolean operator >= (CountryCode LocationId1, CountryCode LocationId2) => !(LocationId1 < LocationId2); #endregion #endregion #region IComparable<LocationId> Members #region CompareTo(Object) /// <summary> /// Compares two instances of this object. /// </summary> /// <param name="Object">An object to compare with.</param> public Int32 CompareTo(Object Object) => Object is CountryCode locationId ? CompareTo(locationId) : throw new ArgumentException("The given object is not a country code identification!", nameof(Object)); #endregion #region CompareTo(LocationId) /// <summary> /// Compares two instances of this object. /// </summary> /// <param name="LocationId">An object to compare with.</param> public Int32 CompareTo(CountryCode LocationId) => String.Compare(InternalId, LocationId.InternalId, StringComparison.OrdinalIgnoreCase); #endregion #endregion #region IEquatable<LocationId> Members #region Equals(Object) /// <summary> /// Compares two instances of this object. /// </summary> /// <param name="Object">An object to compare with.</param> /// <returns>true|false</returns> public override Boolean Equals(Object Object) => Object is CountryCode locationId && Equals(locationId); #endregion #region Equals(LocationId) /// <summary> /// Compares two country code identifications for equality. /// </summary> /// <param name="LocationId">An country code identification to compare with.</param> /// <returns>True if both match; False otherwise.</returns> public Boolean Equals(CountryCode LocationId) => String.Equals(InternalId, LocationId.InternalId, StringComparison.OrdinalIgnoreCase); #endregion #endregion #region GetHashCode() /// <summary> /// Return the hash code of this object. /// </summary> /// <returns>The hash code of this object.</returns> public override Int32 GetHashCode() => InternalId?.ToLower().GetHashCode() ?? 0; #endregion #region (override) ToString() /// <summary> /// Return a text representation of this object. /// </summary> public override String ToString() => InternalId ?? ""; #endregion } }
30.066667
155
0.570712
[ "Apache-2.0" ]
GraphDefined/WWCP_OCPI
NET6/WWCP_OCPIv2.1.1/DataTypes/Simple/CountryCode.cs
10,375
C#
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="Extensions.cs" company="CatenaLogic"> // Copyright (c) 2014 - 2014 CatenaLogic. All rights reserved. // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace LoadAssembliesOnStartup.Fody { using System.Collections.Generic; using System.Linq; public static class StringExtensions { public static IEnumerable<string> NonEmpty(this IEnumerable<string> list) { return list.Select(x => x.Trim()).Where(x => x != string.Empty); } } }
35.9
120
0.435933
[ "MIT" ]
Fody/LoadAssembliesOnStartup
src/LoadAssembliesOnStartup.Fody/Extensions/StringExtensions.cs
720
C#
using System; using System.Collections.Generic; using System.Linq; using UnityEditor; using UnityEngine; namespace SuperUnityBuild.BuildTool { [Serializable] public class BuildPlatform { public bool enabled = false; public BuildDistributionList distributionList = new BuildDistributionList(); public BuildArchitecture[] architectures = new BuildArchitecture[0]; public BuildVariant[] variants = new BuildVariant[0]; public string platformName; public string dataDirNameFormat; public BuildTargetGroup targetGroup; public virtual void Init() { } public virtual void ApplyVariant() { } #region Public Properties public bool atLeastOneArch { get { bool atLeastOneArch = false; for (int i = 0; i < architectures.Length && !atLeastOneArch; i++) { atLeastOneArch |= architectures[i].enabled; } return atLeastOneArch; } } public bool atLeastOneDistribution { get { bool atLeastOneDist = false; for (int i = 0; i < distributionList.distributions.Length && !atLeastOneDist; i++) { atLeastOneDist |= distributionList.distributions[i].enabled; } return atLeastOneDist; } } public string variantKey { get { string retVal = ""; // Build key string. if (variants != null && variants.Length > 0) { foreach (var variant in variants) retVal += variant.variantKey + ","; } // Remove trailing delimiter. if (retVal.Length > 0) retVal = retVal.Substring(0, retVal.Length - 1); return retVal; } } #endregion protected static T EnumValueFromKey<T>(string label) { return (T)Enum.Parse(typeof(T), label.Replace(" ", "")); } public static string[] EnumNamesToArray<T>(bool toWords = false) { return Enum.GetNames(typeof(T)) .Select(item => toWords ? UnityBuildGUIUtility.ToWords(item) : item) .ToArray(); } } }
26.484211
98
0.507154
[ "MIT" ]
CollegiumXR/unity-build
Editor/Build/Platform/BuildPlatform.cs
2,518
C#
using System; namespace WIM.Extensions { //Extension methods must be defined in a static class public static class StringExtensions { // This is the extension method. // The first parameter takes the "this" modifier // and specifies the type for which the method is defined. public static string TrimToUpper(this string str) { return str.ToUpper().Trim(); } public static string TrimToLower(this string str) { return str.ToLower().Trim(); } public static bool IgnoreCaseEquals(this string str, string str2) { return String.Equals(str.TrimToUpper(), str2.TrimToUpper()); } } }
28.035714
76
0.561783
[ "CC0-1.0", "MIT" ]
jknewson/WiM.Standard
Extensions/StringExtensions.cs
787
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Linq; using System.Security.Cryptography.X509Certificates; using Test.Cryptography; using Xunit; namespace System.Security.Cryptography.Pkcs.Tests { public static class TimestampTokenTests { [Theory] [InlineData(nameof(TimestampTokenTestData.FreeTsaDotOrg1))] [InlineData(nameof(TimestampTokenTestData.Symantec1))] public static void ParseDocument(string testDataName) { TimestampTokenTestData testData = TimestampTokenTestData.GetTestData(testDataName); TestParseDocument(testData.FullTokenBytes, testData, testData.FullTokenBytes.Length); } [Theory] [InlineData(nameof(TimestampTokenTestData.FreeTsaDotOrg1))] [InlineData(nameof(TimestampTokenTestData.Symantec1))] public static void ParseDocument_ExcessData(string testDataName) { TimestampTokenTestData testData = TimestampTokenTestData.GetTestData(testDataName); int baseLen = testData.FullTokenBytes.Length; byte[] tooMuchData = new byte[baseLen + 30]; testData.FullTokenBytes.CopyTo(tooMuchData); // Look like an octet string of the remainder of the payload. Should be ignored. tooMuchData[baseLen] = 0x04; tooMuchData[baseLen + 1] = 28; TestParseDocument(tooMuchData, testData, baseLen); } private static void TestParseDocument( ReadOnlyMemory<byte> tokenBytes, TimestampTokenTestData testData, int? expectedBytesRead) { int bytesRead; Rfc3161TimestampToken token; Assert.True( Rfc3161TimestampToken.TryDecode(tokenBytes, out token, out bytesRead), "Rfc3161TimestampToken.TryDecode"); if (expectedBytesRead != null) { Assert.Equal(expectedBytesRead.Value, bytesRead); } Assert.NotNull(token); TimestampTokenInfoTests.AssertEqual(testData, token.TokenInfo); SignedCms signedCms = token.AsSignedCms(); Assert.NotNull(signedCms); Assert.Equal(Oids.TstInfo, signedCms.ContentInfo.ContentType.Value); Assert.Equal( testData.TokenInfoBytes.ByteArrayToHex(), signedCms.ContentInfo.Content.ByteArrayToHex()); if (testData.EmbeddedSigningCertificate != null) { Assert.NotNull(signedCms.SignerInfos[0].Certificate); Assert.Equal( testData.EmbeddedSigningCertificate.Value.ByteArrayToHex(), signedCms.SignerInfos[0].Certificate.RawData.ByteArrayToHex()); // Assert.NoThrow signedCms.CheckSignature(true); } else { Assert.Null(signedCms.SignerInfos[0].Certificate); using (var signerCert = new X509Certificate2(testData.ExternalCertificateBytes)) { // Assert.NoThrow signedCms.CheckSignature( new X509Certificate2Collection(signerCert), true); } } X509Certificate2 returnedCert; ReadOnlySpan<byte> messageContentSpan = testData.MessageContent.Span; X509Certificate2Collection candidates = null; if (testData.EmbeddedSigningCertificate != null) { Assert.True( token.VerifySignatureForData(messageContentSpan, out returnedCert), "token.VerifySignatureForData(correct)"); Assert.NotNull(returnedCert); Assert.Equal(signedCms.SignerInfos[0].Certificate, returnedCert); } else { candidates = new X509Certificate2Collection { new X509Certificate2(testData.ExternalCertificateBytes), }; Assert.False( token.VerifySignatureForData(messageContentSpan, out returnedCert), "token.VerifySignatureForData(correct, no cert)"); Assert.Null(returnedCert); Assert.True( token.VerifySignatureForData(messageContentSpan, out returnedCert, candidates), "token.VerifySignatureForData(correct, certs)"); Assert.NotNull(returnedCert); Assert.Equal(candidates[0], returnedCert); } X509Certificate2 previousCert = returnedCert; Assert.False( token.VerifySignatureForData(messageContentSpan.Slice(1), out returnedCert, candidates), "token.VerifySignatureForData(incorrect)"); Assert.Null(returnedCert); byte[] messageHash = testData.HashBytes.ToArray(); Assert.False( token.VerifySignatureForHash(messageHash, HashAlgorithmName.MD5, out returnedCert, candidates), "token.VerifyHash(correct, MD5)"); Assert.Null(returnedCert); Assert.False( token.VerifySignatureForHash(messageHash, new Oid(Oids.Md5), out returnedCert, candidates), "token.VerifyHash(correct, Oid(MD5))"); Assert.Null(returnedCert); Assert.True( token.VerifySignatureForHash(messageHash, new Oid(testData.HashAlgorithmId), out returnedCert, candidates), "token.VerifyHash(correct, Oid(algId))"); Assert.NotNull(returnedCert); Assert.Equal(previousCert, returnedCert); messageHash[0] ^= 0xFF; Assert.False( token.VerifySignatureForHash(messageHash, new Oid(testData.HashAlgorithmId), out returnedCert, candidates), "token.VerifyHash(incorrect, Oid(algId))"); Assert.Null(returnedCert); } [Fact] public static void TryDecode_Fails_SignedCmsOfData() { Assert.False( Rfc3161TimestampToken.TryDecode( SignedDocuments.RsaPkcs1OneSignerIssuerAndSerialNumber, out Rfc3161TimestampToken token, out int bytesRead), "Rfc3161TimestampToken.TryDecode"); Assert.Equal(0, bytesRead); Assert.Null(token); } [Fact] public static void TryDecode_Fails_Empty() { Assert.False( Rfc3161TimestampToken.TryDecode( ReadOnlyMemory<byte>.Empty, out Rfc3161TimestampToken token, out int bytesRead), "Rfc3161TimestampToken.TryDecode"); Assert.Equal(0, bytesRead); Assert.Null(token); } [Fact] public static void TryDecode_Fails_EnvelopedCms() { byte[] encodedMessage = ("3082010c06092a864886f70d010703a081fe3081fb0201003181c83081c5020100302e301a311830160603550403130f5253" + "414b65795472616e7366657231021031d935fb63e8cfab48a0bf7b397b67c0300d06092a864886f70d010101050004818013" + "dc0eb2984a445d04a1f6246b8fe41f1d24507548d449d454d5bb5e0638d75ed101bf78c0155a5d208eb746755fbccbc86923" + "8443760a9ae94770d6373e0197be23a6a891f0c522ca96b3e8008bf23547474b7e24e7f32e8134df3862d84f4dea2470548e" + "c774dd74f149a56cdd966e141122900d00ad9d10ea1848541294a1302b06092a864886f70d010701301406082a864886f70d" + "030704089c8119f6cf6b174c8008bcea3a10d0737eb9").HexToByteArray(); Assert.False( Rfc3161TimestampToken.TryDecode( encodedMessage, out Rfc3161TimestampToken token, out int bytesRead), "Rfc3161TimestampToken.TryDecode"); Assert.Equal(0, bytesRead); Assert.Null(token); } [Fact] public static void TryDecode_Fails_MalformedToken() { ContentInfo contentInfo = new ContentInfo( new Oid(Oids.TstInfo, Oids.TstInfo), new byte[] { 1 }); SignedCms cms = new SignedCms(contentInfo); using (X509Certificate2 cert = Certificates.RSAKeyTransferCapi1.TryGetCertificateWithPrivateKey()) { cms.ComputeSignature(new CmsSigner(SubjectIdentifierType.IssuerAndSerialNumber, cert)); } Assert.False( Rfc3161TimestampToken.TryDecode( cms.Encode(), out Rfc3161TimestampToken token, out int bytesRead), "Rfc3161TimestampToken.TryDecode"); Assert.Equal(0, bytesRead); Assert.Null(token); } [Theory] [InlineData(X509IncludeOption.WholeChain, SigningCertificateOption.ValidHashNoName)] [InlineData(X509IncludeOption.None, SigningCertificateOption.ValidHashNoName)] [InlineData(X509IncludeOption.WholeChain, SigningCertificateOption.ValidHashWithName)] [InlineData(X509IncludeOption.None, SigningCertificateOption.ValidHashWithName)] public static void MatchV1(X509IncludeOption includeOption, SigningCertificateOption v1Option) { CustomBuild_CertMatch( Certificates.ValidLookingTsaCert, new DateTimeOffset(2018, 1, 10, 17, 21, 11, 802, TimeSpan.Zero), v1Option, SigningCertificateOption.Omit, includeOption: includeOption); } [Theory] [InlineData(X509IncludeOption.WholeChain)] [InlineData(X509IncludeOption.None)] public static void CertHashMismatchV1(X509IncludeOption includeOption) { CustomBuild_CertMismatch( Certificates.ValidLookingTsaCert, new DateTimeOffset(2018, 1, 10, 17, 21, 11, 802, TimeSpan.Zero), SigningCertificateOption.InvalidHashNoName, SigningCertificateOption.Omit, includeOption: includeOption); } [Theory] [InlineData( X509IncludeOption.WholeChain, SigningCertificateOption.ValidHashWithInvalidName, SubjectIdentifierType.SubjectKeyIdentifier)] [InlineData( X509IncludeOption.None, SigningCertificateOption.ValidHashWithInvalidName, SubjectIdentifierType.SubjectKeyIdentifier)] [InlineData( X509IncludeOption.WholeChain, SigningCertificateOption.ValidHashWithInvalidName, SubjectIdentifierType.IssuerAndSerialNumber)] [InlineData( X509IncludeOption.None, SigningCertificateOption.ValidHashWithInvalidName, SubjectIdentifierType.IssuerAndSerialNumber)] public static void CertMismatchIssuerAndSerialV1( X509IncludeOption includeOption, SigningCertificateOption v1Option, SubjectIdentifierType identifierType) { CustomBuild_CertMismatch( Certificates.ValidLookingTsaCert, new DateTimeOffset(2018, 1, 10, 17, 21, 11, 802, TimeSpan.Zero), v1Option, SigningCertificateOption.Omit, includeOption: includeOption, identifierType: identifierType); } [Theory] [InlineData( X509IncludeOption.WholeChain, SigningCertificateOption.ValidHashNoName, null)] [InlineData( X509IncludeOption.None, SigningCertificateOption.ValidHashNoName, null)] [InlineData( X509IncludeOption.WholeChain, SigningCertificateOption.ValidHashWithName, "MD5")] [InlineData( X509IncludeOption.None, SigningCertificateOption.ValidHashWithName, "MD5")] [InlineData( X509IncludeOption.WholeChain, SigningCertificateOption.ValidHashWithName, "SHA1")] [InlineData( X509IncludeOption.None, SigningCertificateOption.ValidHashWithName, "SHA1")] [InlineData( X509IncludeOption.WholeChain, SigningCertificateOption.ValidHashWithName, "SHA384")] [InlineData( X509IncludeOption.None, SigningCertificateOption.ValidHashWithName, "SHA384")] public static void MatchV2( X509IncludeOption includeOption, SigningCertificateOption v2Option, string hashAlgName) { CustomBuild_CertMatch( Certificates.ValidLookingTsaCert, new DateTimeOffset(2018, 1, 10, 17, 21, 11, 802, TimeSpan.Zero), SigningCertificateOption.Omit, v2Option, hashAlgName == null ? default(HashAlgorithmName) : new HashAlgorithmName(hashAlgName), includeOption); } [Theory] [InlineData(X509IncludeOption.WholeChain, null)] [InlineData(X509IncludeOption.None, null)] [InlineData(X509IncludeOption.WholeChain, "MD5")] [InlineData(X509IncludeOption.None, "MD5")] [InlineData(X509IncludeOption.WholeChain, "SHA1")] [InlineData(X509IncludeOption.None, "SHA1")] [InlineData(X509IncludeOption.WholeChain, "SHA384")] [InlineData(X509IncludeOption.None, "SHA384")] public static void CertHashMismatchV2(X509IncludeOption includeOption, string hashAlgName) { CustomBuild_CertMismatch( Certificates.ValidLookingTsaCert, new DateTimeOffset(2018, 1, 10, 17, 21, 11, 802, TimeSpan.Zero), SigningCertificateOption.Omit, SigningCertificateOption.InvalidHashNoName, hashAlgName == null ? default(HashAlgorithmName) : new HashAlgorithmName(hashAlgName), includeOption: includeOption); } [Theory] [InlineData( X509IncludeOption.WholeChain, SigningCertificateOption.ValidHashWithInvalidName, SubjectIdentifierType.SubjectKeyIdentifier, null)] [InlineData( X509IncludeOption.None, SigningCertificateOption.ValidHashWithInvalidName, SubjectIdentifierType.SubjectKeyIdentifier, null)] [InlineData( X509IncludeOption.WholeChain, SigningCertificateOption.ValidHashWithInvalidName, SubjectIdentifierType.SubjectKeyIdentifier, "SHA384")] [InlineData( X509IncludeOption.None, SigningCertificateOption.ValidHashWithInvalidName, SubjectIdentifierType.SubjectKeyIdentifier, "SHA384")] [InlineData( X509IncludeOption.WholeChain, SigningCertificateOption.ValidHashWithInvalidName, SubjectIdentifierType.IssuerAndSerialNumber, null)] [InlineData( X509IncludeOption.None, SigningCertificateOption.ValidHashWithInvalidName, SubjectIdentifierType.IssuerAndSerialNumber, null)] [InlineData( X509IncludeOption.WholeChain, SigningCertificateOption.ValidHashWithInvalidName, SubjectIdentifierType.IssuerAndSerialNumber, "SHA384")] [InlineData( X509IncludeOption.None, SigningCertificateOption.ValidHashWithInvalidName, SubjectIdentifierType.IssuerAndSerialNumber, "SHA384")] public static void CertMismatchIssuerAndSerialV2( X509IncludeOption includeOption, SigningCertificateOption v2Option, SubjectIdentifierType identifierType, string hashAlgName) { CustomBuild_CertMismatch( Certificates.ValidLookingTsaCert, new DateTimeOffset(2018, 1, 10, 17, 21, 11, 802, TimeSpan.Zero), SigningCertificateOption.Omit, v2Option, hashAlgName == null ? default(HashAlgorithmName) : new HashAlgorithmName(hashAlgName), includeOption: includeOption, identifierType: identifierType); } [Theory] [InlineData( X509IncludeOption.WholeChain, SigningCertificateOption.ValidHashNoName, SigningCertificateOption.ValidHashNoName, null)] [InlineData( X509IncludeOption.WholeChain, SigningCertificateOption.ValidHashNoName, SigningCertificateOption.ValidHashNoName, "SHA512")] [InlineData( X509IncludeOption.None, SigningCertificateOption.ValidHashNoName, SigningCertificateOption.ValidHashNoName, null)] [InlineData( X509IncludeOption.None, SigningCertificateOption.ValidHashNoName, SigningCertificateOption.ValidHashNoName, "SHA512")] [InlineData( X509IncludeOption.WholeChain, SigningCertificateOption.ValidHashNoName, SigningCertificateOption.ValidHashWithName, null)] [InlineData( X509IncludeOption.WholeChain, SigningCertificateOption.ValidHashNoName, SigningCertificateOption.ValidHashWithName, "SHA384")] [InlineData( X509IncludeOption.None, SigningCertificateOption.ValidHashNoName, SigningCertificateOption.ValidHashWithName, null)] [InlineData( X509IncludeOption.None, SigningCertificateOption.ValidHashNoName, SigningCertificateOption.ValidHashWithName, "SHA384")] [InlineData( X509IncludeOption.WholeChain, SigningCertificateOption.ValidHashWithName, SigningCertificateOption.ValidHashNoName, null)] [InlineData( X509IncludeOption.WholeChain, SigningCertificateOption.ValidHashWithName, SigningCertificateOption.ValidHashNoName, "SHA512")] [InlineData( X509IncludeOption.None, SigningCertificateOption.ValidHashWithName, SigningCertificateOption.ValidHashNoName, null)] [InlineData( X509IncludeOption.None, SigningCertificateOption.ValidHashWithName, SigningCertificateOption.ValidHashNoName, "SHA512")] [InlineData( X509IncludeOption.WholeChain, SigningCertificateOption.ValidHashWithName, SigningCertificateOption.ValidHashWithName, null)] [InlineData( X509IncludeOption.WholeChain, SigningCertificateOption.ValidHashWithName, SigningCertificateOption.ValidHashWithName, "SHA384")] [InlineData( X509IncludeOption.None, SigningCertificateOption.ValidHashWithName, SigningCertificateOption.ValidHashWithName, null)] [InlineData( X509IncludeOption.None, SigningCertificateOption.ValidHashWithName, SigningCertificateOption.ValidHashWithName, "SHA384")] public static void CertMatchV1AndV2( X509IncludeOption includeOption, SigningCertificateOption v1Option, SigningCertificateOption v2Option, string hashAlgName) { CustomBuild_CertMatch( Certificates.ValidLookingTsaCert, new DateTimeOffset(2018, 1, 10, 17, 21, 11, 802, TimeSpan.Zero), v1Option, v2Option, hashAlgName == null ? default(HashAlgorithmName) : new HashAlgorithmName(hashAlgName), includeOption); } [Theory] [InlineData( X509IncludeOption.None, SigningCertificateOption.InvalidHashNoName, SigningCertificateOption.ValidHashWithName, SubjectIdentifierType.IssuerAndSerialNumber, null)] [InlineData( X509IncludeOption.WholeChain, SigningCertificateOption.ValidHashWithInvalidSerial, SigningCertificateOption.ValidHashWithName, SubjectIdentifierType.IssuerAndSerialNumber, "SHA384")] [InlineData( X509IncludeOption.WholeChain, SigningCertificateOption.ValidHashWithInvalidName, SigningCertificateOption.InvalidHashNoName, SubjectIdentifierType.SubjectKeyIdentifier, null)] [InlineData( X509IncludeOption.None, SigningCertificateOption.ValidHashWithName, SigningCertificateOption.InvalidHashNoName, SubjectIdentifierType.SubjectKeyIdentifier, "SHA512")] [InlineData( X509IncludeOption.WholeChain, SigningCertificateOption.InvalidHashWithInvalidSerial, SigningCertificateOption.ValidHashNoName, SubjectIdentifierType.IssuerAndSerialNumber, null)] public static void CertMismatchV1OrV2( X509IncludeOption includeOption, SigningCertificateOption v1Option, SigningCertificateOption v2Option, SubjectIdentifierType identifierType, string hashAlgName) { CustomBuild_CertMismatch( Certificates.ValidLookingTsaCert, new DateTimeOffset(2018, 1, 10, 17, 21, 11, 802, TimeSpan.Zero), v1Option, v2Option, hashAlgName == null ? default(HashAlgorithmName) : new HashAlgorithmName(hashAlgName), includeOption: includeOption, identifierType: identifierType); } [Theory] [InlineData(X509IncludeOption.WholeChain)] [InlineData(X509IncludeOption.None)] public static void TimestampTooOld(X509IncludeOption includeOption) { CertLoader loader = Certificates.ValidLookingTsaCert; DateTimeOffset referenceTime; using (X509Certificate2 cert = loader.GetCertificate()) { referenceTime = cert.NotBefore.AddSeconds(-1); } CustomBuild_CertMismatch( loader, referenceTime, SigningCertificateOption.ValidHashNoName, SigningCertificateOption.Omit, includeOption: includeOption); } [Theory] [InlineData(X509IncludeOption.WholeChain)] [InlineData(X509IncludeOption.None)] public static void TimestampTooNew(X509IncludeOption includeOption) { CertLoader loader = Certificates.ValidLookingTsaCert; DateTimeOffset referenceTime; using (X509Certificate2 cert = loader.GetCertificate()) { referenceTime = cert.NotAfter.AddSeconds(1); } CustomBuild_CertMismatch( loader, referenceTime, SigningCertificateOption.ValidHashNoName, SigningCertificateOption.Omit, includeOption: includeOption); } [Theory] [InlineData(X509IncludeOption.WholeChain)] [InlineData(X509IncludeOption.None)] public static void NoEkuExtension(X509IncludeOption includeOption) { CertLoader loader = Certificates.RSA2048SignatureOnly; DateTimeOffset referenceTime; using (X509Certificate2 cert = loader.GetCertificate()) { referenceTime = cert.NotAfter.AddDays(-1); Assert.Equal(0, cert.Extensions.OfType<X509EnhancedKeyUsageExtension>().Count()); } CustomBuild_CertMismatch( loader, referenceTime, SigningCertificateOption.ValidHashNoName, SigningCertificateOption.Omit, includeOption: includeOption); } [Theory] [InlineData(X509IncludeOption.WholeChain)] [InlineData(X509IncludeOption.None)] public static void TwoEkuExtensions(X509IncludeOption includeOption) { CertLoader loader = Certificates.TwoEkuTsaCert; DateTimeOffset referenceTime; using (X509Certificate2 cert = loader.GetCertificate()) { referenceTime = cert.NotAfter.AddDays(-1); var ekuExts = cert.Extensions.OfType<X509EnhancedKeyUsageExtension>().ToList(); Assert.Equal(2, ekuExts.Count); // Make sure we're validating that "early success" doesn't happen. Assert.Contains( Oids.TimeStampingPurpose, ekuExts[0].EnhancedKeyUsages.OfType<Oid>().Select(o => o.Value)); } CustomBuild_CertMismatch( loader, referenceTime, SigningCertificateOption.ValidHashNoName, SigningCertificateOption.Omit, includeOption: includeOption); } [Theory] [InlineData(X509IncludeOption.WholeChain)] [InlineData(X509IncludeOption.None)] public static void NonCriticalEkuExtension(X509IncludeOption includeOption) { CertLoader loader = Certificates.NonCriticalTsaEku; DateTimeOffset referenceTime; using (X509Certificate2 cert = loader.GetCertificate()) { referenceTime = cert.NotAfter.AddDays(-1); var ekuExts = cert.Extensions.OfType<X509EnhancedKeyUsageExtension>().ToList(); Assert.Equal(1, ekuExts.Count); Assert.False(ekuExts[0].Critical, "ekuExts[0].Critical"); } CustomBuild_CertMismatch( loader, referenceTime, SigningCertificateOption.ValidHashNoName, SigningCertificateOption.Omit, includeOption: includeOption); } [Theory] [InlineData(X509IncludeOption.WholeChain)] [InlineData(X509IncludeOption.None)] public static void NoTsaEku(X509IncludeOption includeOption) { CertLoader loader = Certificates.TlsClientServerCert; DateTimeOffset referenceTime; using (X509Certificate2 cert = loader.GetCertificate()) { referenceTime = cert.NotAfter.AddDays(-1); } CustomBuild_CertMismatch( loader, referenceTime, SigningCertificateOption.ValidHashNoName, SigningCertificateOption.Omit, includeOption: includeOption); } private static void CustomBuild_CertMatch( CertLoader loader, DateTimeOffset referenceTime, SigningCertificateOption v1Option, SigningCertificateOption v2Option, HashAlgorithmName v2AlgorithmName = default, X509IncludeOption includeOption = default, SubjectIdentifierType identifierType = SubjectIdentifierType.IssuerAndSerialNumber) { byte[] tokenBytes = BuildCustomToken( loader, referenceTime, v1Option, v2Option, v2AlgorithmName, includeOption, identifierType); Rfc3161TimestampToken token; Assert.True(Rfc3161TimestampToken.TryDecode(tokenBytes, out token, out int bytesRead)); Assert.Equal(tokenBytes.Length, bytesRead); Assert.NotNull(token); Assert.Equal(referenceTime, token.TokenInfo.Timestamp); using (X509Certificate2 cert = Certificates.ValidLookingTsaCert.GetCertificate()) { Assert.True( token.VerifySignatureForHash( token.TokenInfo.GetMessageHash().Span, token.TokenInfo.HashAlgorithmId, out X509Certificate2 signer, new X509Certificate2Collection(cert))); Assert.Equal(cert, signer); } } private static void CustomBuild_CertMismatch( CertLoader loader, DateTimeOffset referenceTime, SigningCertificateOption v1Option, SigningCertificateOption v2Option, HashAlgorithmName v2AlgorithmName = default, X509IncludeOption includeOption = default, SubjectIdentifierType identifierType = SubjectIdentifierType.IssuerAndSerialNumber) { byte[] tokenBytes = BuildCustomToken( loader, referenceTime, v1Option, v2Option, v2AlgorithmName, includeOption, identifierType); Rfc3161TimestampToken token; bool willParse = includeOption == X509IncludeOption.None; if (willParse && identifierType == SubjectIdentifierType.IssuerAndSerialNumber) { // Because IASN matches against the ESSCertId(V2) directly it will reject the token. switch (v1Option) { case SigningCertificateOption.ValidHashWithInvalidName: case SigningCertificateOption.ValidHashWithInvalidSerial: case SigningCertificateOption.InvalidHashWithInvalidName: case SigningCertificateOption.InvalidHashWithInvalidSerial: willParse = false; break; } switch (v2Option) { case SigningCertificateOption.ValidHashWithInvalidName: case SigningCertificateOption.ValidHashWithInvalidSerial: case SigningCertificateOption.InvalidHashWithInvalidName: case SigningCertificateOption.InvalidHashWithInvalidSerial: willParse = false; break; } } if (willParse) { Assert.True(Rfc3161TimestampToken.TryDecode(tokenBytes, out token, out int bytesRead)); Assert.NotNull(token); Assert.Equal(tokenBytes.Length, bytesRead); using (X509Certificate2 cert = loader.GetCertificate()) { Assert.False( token.VerifySignatureForHash( token.TokenInfo.GetMessageHash().Span, token.TokenInfo.HashAlgorithmId, out X509Certificate2 signer, new X509Certificate2Collection(cert))); Assert.Null(signer); } } else { Assert.False(Rfc3161TimestampToken.TryDecode(tokenBytes, out token, out int bytesRead)); Assert.Null(token); Assert.Equal(0, bytesRead); } } private static byte[] BuildCustomToken( CertLoader cert, DateTimeOffset timestamp, SigningCertificateOption v1Option, SigningCertificateOption v2Option, HashAlgorithmName v2DigestAlg=default, X509IncludeOption includeOption=X509IncludeOption.ExcludeRoot, SubjectIdentifierType identifierType=SubjectIdentifierType.IssuerAndSerialNumber) { long accuracyMicroSeconds = (long)(TimeSpan.FromMinutes(1).TotalMilliseconds * 1000); byte[] serialNumber = BitConverter.GetBytes(DateTimeOffset.UtcNow.Ticks); Array.Reverse(serialNumber); Rfc3161TimestampTokenInfo info = new Rfc3161TimestampTokenInfo( new Oid("0.0", "0.0"), new Oid(Oids.Sha384), new byte[384 / 8], serialNumber, timestamp, accuracyMicroSeconds, isOrdering: true); ContentInfo contentInfo = new ContentInfo(new Oid(Oids.TstInfo, Oids.TstInfo), info.Encode()); SignedCms cms = new SignedCms(contentInfo); using (X509Certificate2 tsaCert = cert.TryGetCertificateWithPrivateKey()) { CmsSigner signer = new CmsSigner(identifierType, tsaCert) { IncludeOption = includeOption }; if (v1Option != SigningCertificateOption.Omit) { ExpandOption(v1Option, out bool validHash, out bool skipIssuerSerial, out bool validName, out bool validSerial); // simple SigningCertificate byte[] signingCertificateV1Bytes = "301A3018301604140000000000000000000000000000000000000000".HexToByteArray(); if (validHash) { using (SHA1 hasher = SHA1.Create()) { byte[] hash = hasher.ComputeHash(tsaCert.RawData); Buffer.BlockCopy( hash, 0, signingCertificateV1Bytes, signingCertificateV1Bytes.Length - hash.Length, hash.Length); } } if (!skipIssuerSerial) { byte[] footer = BuildIssuerAndSerialNumber(tsaCert, validName, validSerial); signingCertificateV1Bytes[1] += (byte)footer.Length; signingCertificateV1Bytes[3] += (byte)footer.Length; signingCertificateV1Bytes[5] += (byte)footer.Length; Assert.InRange(signingCertificateV1Bytes[1], 0, 127); signingCertificateV1Bytes = signingCertificateV1Bytes.Concat(footer).ToArray(); } signer.SignedAttributes.Add( new AsnEncodedData("1.2.840.113549.1.9.16.2.12", signingCertificateV1Bytes)); } if (v2Option != SigningCertificateOption.Omit) { byte[] attrBytes; byte[] algBytes = Array.Empty<byte>(); byte[] hashBytes; byte[] issuerNameBytes = Array.Empty<byte>(); if (v2DigestAlg != default) { switch (v2DigestAlg.Name) { case "MD5": algBytes = "300C06082A864886F70D02050500".HexToByteArray(); break; case "SHA1": algBytes = "300906052B0E03021A0500".HexToByteArray(); break; case "SHA256": // Invalid under DER, because it's the default. algBytes = "300D06096086480165030402010500".HexToByteArray(); break; case "SHA384": algBytes = "300D06096086480165030402020500".HexToByteArray(); break; case "SHA512": algBytes = "300D06096086480165030402030500".HexToByteArray(); break; default: throw new NotSupportedException(v2DigestAlg.Name); } } else { v2DigestAlg = HashAlgorithmName.SHA256; } hashBytes = tsaCert.GetCertHash(v2DigestAlg); ExpandOption(v2Option, out bool validHash, out bool skipIssuerSerial, out bool validName, out bool validSerial); if (!validHash) { hashBytes[0] ^= 0xFF; } if (!skipIssuerSerial) { issuerNameBytes = BuildIssuerAndSerialNumber(tsaCert, validName, validSerial); } // hashBytes hasn't been wrapped in an OCTET STRING yet, so add 2 more. int payloadSize = algBytes.Length + hashBytes.Length + issuerNameBytes.Length + 2; Assert.InRange(payloadSize, 0, 123); attrBytes = new byte[payloadSize + 6]; int index = 0; // SEQUENCE (SigningCertificateV2) attrBytes[index++] = 0x30; attrBytes[index++] = (byte)(payloadSize + 4); // SEQUENCE OF => certs attrBytes[index++] = 0x30; attrBytes[index++] = (byte)(payloadSize + 2); // SEQUENCE (ESSCertIdV2) attrBytes[index++] = 0x30; attrBytes[index++] = (byte)payloadSize; Buffer.BlockCopy(algBytes, 0, attrBytes, index, algBytes.Length); index += algBytes.Length; // OCTET STRING (Hash) attrBytes[index++] = 0x04; attrBytes[index++] = (byte)hashBytes.Length; Buffer.BlockCopy(hashBytes, 0, attrBytes, index, hashBytes.Length); index += hashBytes.Length; Buffer.BlockCopy(issuerNameBytes, 0, attrBytes, index, issuerNameBytes.Length); signer.SignedAttributes.Add( new AsnEncodedData("1.2.840.113549.1.9.16.2.47", attrBytes)); } cms.ComputeSignature(signer); } return cms.Encode(); } private static byte[] BuildIssuerAndSerialNumber(X509Certificate2 tsaCert, bool validName, bool validSerial) { byte[] issuerNameBytes; if (validName) { issuerNameBytes = tsaCert.IssuerName.RawData; } else { issuerNameBytes = new X500DistinguishedName("CN=No Match").RawData; } byte[] serialBytes = tsaCert.GetSerialNumber(); if (validSerial) { Array.Reverse(serialBytes); } else { // If the byte sequence was a palindrome it's still a match, // so flip some bits. serialBytes[0] ^= 0x7F; } if (issuerNameBytes.Length + serialBytes.Length > 80) { throw new NotSupportedException( "Issuer name and serial length are bigger than this code can handle"); } // SEQUENCE // SEQUENCE // CONTEXT-SPECIFIC 4 // [IssuerName] // INTEGER // [SerialNumber, big endian] byte[] issuerAndSerialNumber = new byte[issuerNameBytes.Length + serialBytes.Length + 8]; issuerAndSerialNumber[0] = 0x30; issuerAndSerialNumber[1] = (byte)(issuerAndSerialNumber.Length - 2); issuerAndSerialNumber[2] = 0x30; issuerAndSerialNumber[3] = (byte)(issuerNameBytes.Length + 2); issuerAndSerialNumber[4] = 0xA4; issuerAndSerialNumber[5] = (byte)(issuerNameBytes.Length); Buffer.BlockCopy(issuerNameBytes, 0, issuerAndSerialNumber, 6, issuerNameBytes.Length); issuerAndSerialNumber[issuerNameBytes.Length + 6] = 0x02; issuerAndSerialNumber[issuerNameBytes.Length + 7] = (byte)serialBytes.Length; Buffer.BlockCopy(serialBytes, 0, issuerAndSerialNumber, issuerNameBytes.Length + 8, serialBytes.Length); return issuerAndSerialNumber; } private static void ExpandOption( SigningCertificateOption option, out bool validHash, out bool skipIssuerSerial, out bool validName, out bool validSerial) { Assert.NotEqual(SigningCertificateOption.Omit, option); validHash = option < SigningCertificateOption.InvalidHashNoName; skipIssuerSerial = option == SigningCertificateOption.ValidHashNoName || option == SigningCertificateOption.InvalidHashNoName; if (skipIssuerSerial) { validName = validSerial = false; } else { validName = option == SigningCertificateOption.ValidHashWithName || option == SigningCertificateOption.InvalidHashWithName || option == SigningCertificateOption.ValidHashWithInvalidSerial || option == SigningCertificateOption.InvalidHashWithInvalidSerial; validSerial = option == SigningCertificateOption.ValidHashWithName || option == SigningCertificateOption.InvalidHashWithName || option == SigningCertificateOption.ValidHashWithInvalidName || option == SigningCertificateOption.InvalidHashWithInvalidName; } } public enum SigningCertificateOption { Omit, ValidHashNoName, ValidHashWithName, ValidHashWithInvalidName, ValidHashWithInvalidSerial, InvalidHashNoName, InvalidHashWithName, InvalidHashWithInvalidName, InvalidHashWithInvalidSerial, } } }
39.272978
132
0.578343
[ "MIT" ]
BigBadBleuCheese/corefx
src/System.Security.Cryptography.Pkcs/tests/Rfc3161/TimestampTokenTests.cs
42,729
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Atlass.Framework.Common.Log; using Atlass.Framework.ViewModels; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Newtonsoft.Json; namespace Atlass.Framework.Core.Middleware { /// <summary> /// 异常处理中间件 /// app.UseMiddleware(typeof(AltasExceptionMiddlerware)); /// app.UseMvc(); /// </summary> public class AtlassExceptionMiddlerware { private readonly RequestDelegate _next; private readonly CustomExceptionHandlerOptions _options; private readonly ILogger<AtlassExceptionMiddlerware> _logger; public AtlassExceptionMiddlerware(RequestDelegate next, IOptions<CustomExceptionHandlerOptions> options, ILogger<AtlassExceptionMiddlerware> logger) { _next = next; _logger = logger; } /// <summary> /// 异常分为两类 一类是客户端主动取消请求的错误,一类是系统异常错误 /// </summary> /// <param name="context"></param> /// <returns></returns> public async Task InvokeAsync(HttpContext context) { try { await _next(context); } catch (System.Exception ex) { if (context.RequestAborted.IsCancellationRequested && (ex is TaskCanceledException || ex is OperationCanceledException)) { _options.OnRequestAborted?.Invoke(context, _logger); } else { _options.OnException?.Invoke(context, _logger, ex); await HandleExceptionAsync(context, ex); } } } /// <summary> ///异常处理 /// </summary> /// <param name="context"></param> /// <param name="exception"></param> /// <returns></returns> private static async Task HandleExceptionAsync(HttpContext context, System.Exception exception) { if (exception == null) { return; } LoggerHelper.Exception(exception); await WriteExceptionAsync(context, exception).ConfigureAwait(false); } /// <summary> /// 写异常日志 /// </summary> /// <param name="context"></param> /// <param name="exception"></param> /// <returns></returns> private static async Task WriteExceptionAsync(HttpContext context, System.Exception exception) { //返回友好的提示 HttpResponse response = context.Response; response.ContentType = context.Request.Headers["Accept"]; response.StatusCode = 500; //ResultAdaptDto result = new ResultAdaptDto(); //result.status = false; //result.statusCode = 500; // response.ContentType = "application/json"; await response.WriteAsync(exception.Message).ConfigureAwait(false); } } public class MiddleExcpetionRespone { public int StatusCode { get; set; } public string Message { get; set; } } public class CustomExceptionHandlerOptions { public Func<HttpContext, ILogger, System.Exception, Task> OnException { get; set; } = async (context, logger, exception) =>logger.LogError(exception, $"Request exception, requestId: {context.TraceIdentifier}"); public Func<HttpContext, ILogger, Task> OnRequestAborted { get; set; } = async (context, logger) => logger.LogInformation($"Request aborted, requestId: {context.TraceIdentifier}"); } }
33.166667
136
0.596403
[ "MIT" ]
aprilyush/EasyCMS
Atlass.Framework.Core/Middleware/AtlassExceptionMiddlerware.cs
3,891
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Frapper.API.Filters; using Frapper.Common; using Frapper.Entities.Movies; using Frapper.Repository; using Frapper.Repository.Movies.Queries; using Frapper.ViewModel.Movies.Request; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Newtonsoft.Json; namespace Frapper.API.Controllers.V1 { [Authorize(Roles = "User")] [Route("api/movies")] [ApiVersion("1.0")] [ApiController] public class MoviesController : ControllerBase { private readonly IUnitOfWorkEntityFramework _unitOfWorkEntityFramework; private readonly IMoviesQueries _iMoviesQueries; public MoviesController(IUnitOfWorkEntityFramework unitOfWorkEntityFramework, IMoviesQueries moviesQueries) { _unitOfWorkEntityFramework = unitOfWorkEntityFramework; _iMoviesQueries = moviesQueries; } [Route("CreateMovies")] [HttpPost] [MapToApiVersion("1.0")] [ValidateModel] [ProducesResponseType(StatusCodes.Status201Created)] [ProducesResponseType(StatusCodes.Status500InternalServerError)] public IActionResult CreateMovies(MoviesCreateRequest moviesRequest) { Movies movies = new Movies() { MoviesID = 0, Name = moviesRequest.Name, Director = moviesRequest.Director, Genre = moviesRequest.Genre, MovieLength = moviesRequest.MovieLength, Rating = moviesRequest.Rating, ReleaseYear = moviesRequest.ReleaseYear, Title = moviesRequest.Title }; _unitOfWorkEntityFramework.MoviesCommand.Add(movies); var result = _unitOfWorkEntityFramework.Commit(); if (result) { return Ok(new OkResponse("Movies Added Successfully !")); } else { return StatusCode(StatusCodes.Status500InternalServerError, "Something Went Wrong"); } } [HttpGet] [Route("GetMovie")] [MapToApiVersion("1.0")] public IActionResult GetMovie(int? id) { if (id == null) { return NotFound(new NotFoundResponse("Movie Not Found")); } var movieTb = _iMoviesQueries.GetMoviesbyId(id); if (movieTb == null) { return NotFound(); } return Ok(movieTb); } [HttpDelete] [Route("DeleteMovie")] [MapToApiVersion("1.0")] [ProducesResponseType(StatusCodes.Status201Created)] [ProducesResponseType(StatusCodes.Status500InternalServerError)] public IActionResult DeleteMovie(int? id) { if (id == null) { return NotFound(); } var movie = _iMoviesQueries.GetMoviesbyId(id); if (movie == null) { return NotFound(); } _unitOfWorkEntityFramework.MoviesCommand.Delete(movie); var result = _unitOfWorkEntityFramework.Commit(); if (result) { return Ok(new OkResponse("Movies Deleted Successfully !")); } else { return StatusCode(StatusCodes.Status500InternalServerError, "Something Went Wrong"); } } [HttpPut] [Route("UpdateMovie")] [MapToApiVersion("1.0")] [ValidateModel] [ProducesResponseType(StatusCodes.Status201Created)] [ProducesResponseType(StatusCodes.Status500InternalServerError)] public IActionResult UpdateMovie(MoviesCreateRequest moviesRequest, int? id) { var movie = _iMoviesQueries.GetMoviesbyId(id); movie.Director = moviesRequest.Director; movie.Genre = moviesRequest.Genre; movie.MovieLength = moviesRequest.MovieLength; movie.Rating = moviesRequest.Rating; movie.ReleaseYear = moviesRequest.ReleaseYear; movie.Title = moviesRequest.Title; _unitOfWorkEntityFramework.MoviesCommand.Update(movie); var result = _unitOfWorkEntityFramework.Commit(); if (result) { return Ok(new OkResponse("Movies Updated Successfully !")); } else { return StatusCode(StatusCodes.Status500InternalServerError, "Something Went Wrong"); } } [HttpGet] [Route("GetAllMovie")] [MapToApiVersion("1.0")] public IEnumerable<Entities.Movies.Movies> GetAllMovies([FromQuery]PagingParameter pagingParameter) { var source = _iMoviesQueries.GetMovies(); // Get's No of Rows Count int count = source.Count(); // Parameter is passed from Query string if it is null then it default Value will be pageNumber:1 int currentPage = pagingParameter.PageNumber; // Parameter is passed from Query string if it is null then it default Value will be pageSize:20 int pageSize = pagingParameter.PageSize; // Display TotalCount to Records to User int totalCount = count; // Calculating Totalpage by Dividing (No of Records / Pagesize) int totalPages = (int)Math.Ceiling(count / (double)pageSize); // Returns List of Customer after applying Paging var items = source.Skip((currentPage - 1) * pageSize).Take(pageSize).ToList(); // if CurrentPage is greater than 1 means it has previousPage var previousPage = currentPage > 1 ? "Yes" : "No"; // if TotalPages is greater than CurrentPage means it has nextPage var nextPage = currentPage < totalPages ? "Yes" : "No"; // Object which we are going to send in header var paginationMetadata = new PaginationMetadata { TotalCount = totalCount, PageSize = pageSize, CurrentPage = currentPage, TotalPages = totalPages, PreviousPage = previousPage, NextPage = nextPage }; HttpContext.Response.Headers.Add("Paging-Headers", JsonConvert.SerializeObject(paginationMetadata)); // Returing List of Customers Collections return items; } } }
34.34359
115
0.593549
[ "MIT" ]
Ramasagar/Frapper.API
Frapper.API/Frapper.API/Controllers/V1/MoviesController.cs
6,699
C#
using Blog.Core.Common; using Blog.Core.Controllers; using Blog.Core.IRepository; using Blog.Core.IServices; using Blog.Core.Model.Models; using Moq; using Xunit; using System; using Autofac; namespace Blog.Core.Tests { public class Redis_Should { private IRedisCacheManager _redisCacheManager; DI_Test dI_Test = new DI_Test(); public Redis_Should() { //var container = dI_Test.DICollections(); //_redisCacheManager = container.Resolve<IRedisCacheManager>(); } [Fact] public void Connect_Redis_Test() { //var redisBlogCache = _redisCacheManager.Get<object>("Redis.Blog"); //Assert.Null(redisBlogCache); } } }
20.777778
80
0.637701
[ "MIT" ]
F1333502/Blog.Core
Blog.Core.Tests/Redis_Test/Redis_Should.cs
748
C#
using System; using System.CodeDom; using System.Collections.Generic; using System.Linq; using TechTalk.SpecFlow.Utils; namespace TechTalk.SpecFlow.Generator.UnitTestProvider { public class XUnit2TestGeneratorProvider : XUnitTestGeneratorProvider { private const string FEATURE_TITLE_PROPERTY_NAME = "FeatureTitle"; private const string FACT_ATTRIBUTE = "Xunit.FactAttribute"; private const string FACT_ATTRIBUTE_SKIP_PROPERTY_NAME = "Skip"; private const string THEORY_ATTRIBUTE = "Xunit.TheoryAttribute"; private const string THEORY_ATTRIBUTE_SKIP_PROPERTY_NAME = "Skip"; private const string INLINEDATA_ATTRIBUTE = "Xunit.InlineDataAttribute"; private const string SKIP_REASON = "Ignored"; private const string ICLASSFIXTURE_INTERFACE = "Xunit.IClassFixture"; private const string COLLECTION_ATTRIBUTE = "Xunit.CollectionAttribute"; private const string OUTPUT_INTERFACE = "Xunit.Abstractions.ITestOutputHelper"; private const string OUTPUT_INTERFACE_PARAMETER_NAME = "testOutputHelper"; private const string OUTPUT_INTERFACE_FIELD_NAME = "_testOutputHelper"; private const string FIXTUREDATA_PARAMETER_NAME = "fixtureData"; public XUnit2TestGeneratorProvider(CodeDomHelper codeDomHelper) :base(codeDomHelper) { CodeDomHelper = codeDomHelper; } public override UnitTestGeneratorTraits GetTraits() { return UnitTestGeneratorTraits.RowTests | UnitTestGeneratorTraits.ParallelExecution; } protected override CodeTypeReference CreateFixtureInterface(TestClassGenerationContext generationContext, CodeTypeReference fixtureDataType) { // Add a field for the ITestOutputHelper generationContext.TestClass.Members.Add(new CodeMemberField(OUTPUT_INTERFACE, OUTPUT_INTERFACE_FIELD_NAME)); // Store the fixture data type for later use in constructor generationContext.CustomData.Add(FIXTUREDATA_PARAMETER_NAME, fixtureDataType); return new CodeTypeReference(ICLASSFIXTURE_INTERFACE, fixtureDataType); } public override bool ImplmentInterfaceExplicit => false; public override void SetRowTest(TestClassGenerationContext generationContext, CodeMemberMethod testMethod, string scenarioTitle) { CodeDomHelper.AddAttribute(testMethod, THEORY_ATTRIBUTE, new CodeAttributeArgument("DisplayName", new CodePrimitiveExpression(scenarioTitle))); SetProperty(testMethod, FEATURE_TITLE_PROPERTY_NAME, generationContext.Feature.Name); SetDescription(testMethod, scenarioTitle); } public override void SetRow(TestClassGenerationContext generationContext, CodeMemberMethod testMethod, IEnumerable<string> arguments, IEnumerable<string> tags, bool isIgnored) { //TODO: better handle "ignored" if (isIgnored) return; var args = arguments.Select( arg => new CodeAttributeArgument(new CodePrimitiveExpression(arg))).ToList(); args.Add( new CodeAttributeArgument( new CodeArrayCreateExpression(typeof(string[]), tags.Select(t => new CodePrimitiveExpression(t)).ToArray()))); CodeDomHelper.AddAttribute(testMethod, INLINEDATA_ATTRIBUTE, args.ToArray()); } protected override void SetTestConstructor(TestClassGenerationContext generationContext, CodeConstructor ctorMethod) { ctorMethod.Parameters.Add( new CodeParameterDeclarationExpression((CodeTypeReference)generationContext.CustomData[FIXTUREDATA_PARAMETER_NAME], FIXTUREDATA_PARAMETER_NAME)); ctorMethod.Parameters.Add( new CodeParameterDeclarationExpression(OUTPUT_INTERFACE, OUTPUT_INTERFACE_PARAMETER_NAME)); ctorMethod.Statements.Add( new CodeAssignStatement( new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), OUTPUT_INTERFACE_FIELD_NAME), new CodeVariableReferenceExpression(OUTPUT_INTERFACE_PARAMETER_NAME))); base.SetTestConstructor(generationContext, ctorMethod); } public override void SetTestMethodIgnore(TestClassGenerationContext generationContext, CodeMemberMethod testMethod) { var factAttr = testMethod.CustomAttributes.OfType<CodeAttributeDeclaration>() .FirstOrDefault(codeAttributeDeclaration => codeAttributeDeclaration.Name == FACT_ATTRIBUTE); if (factAttr != null) { // set [FactAttribute(Skip="reason")] factAttr.Arguments.Add ( new CodeAttributeArgument(FACT_ATTRIBUTE_SKIP_PROPERTY_NAME, new CodePrimitiveExpression(SKIP_REASON)) ); } var theoryAttr = testMethod.CustomAttributes.OfType<CodeAttributeDeclaration>() .FirstOrDefault(codeAttributeDeclaration => codeAttributeDeclaration.Name == THEORY_ATTRIBUTE); if (theoryAttr != null) { // set [TheoryAttribute(Skip="reason")] theoryAttr.Arguments.Add ( new CodeAttributeArgument(THEORY_ATTRIBUTE_SKIP_PROPERTY_NAME, new CodePrimitiveExpression(SKIP_REASON)) ); } } public override void SetTestClassParallelize(TestClassGenerationContext generationContext) { CodeDomHelper.AddAttribute(generationContext.TestClass, COLLECTION_ATTRIBUTE, new CodeAttributeArgument(new CodePrimitiveExpression(Guid.NewGuid()))); } public override void FinalizeTestClass(TestClassGenerationContext generationContext) { IgnoreFeature(generationContext); // testRunner.ScenarioContext.ScenarioContainer.RegisterInstanceAs<ITestOutputHelper>(_testOutputHelper); generationContext.ScenarioInitializeMethod.Statements.Add( new CodeMethodInvokeExpression( new CodeMethodReferenceExpression( new CodePropertyReferenceExpression( new CodePropertyReferenceExpression( new CodeFieldReferenceExpression(null, generationContext.TestRunnerField.Name), "ScenarioContext"), "ScenarioContainer"), "RegisterInstanceAs", new CodeTypeReference(OUTPUT_INTERFACE)), new CodeVariableReferenceExpression(OUTPUT_INTERFACE_FIELD_NAME))); } protected override bool IsTestMethodAlreadyIgnored(CodeMemberMethod testMethod) { return IsTestMethodAlreadyIgnored(testMethod, FACT_ATTRIBUTE, THEORY_ATTRIBUTE); } } }
48.909091
162
0.684015
[ "Apache-2.0", "MIT" ]
ImanMesgaran/SpecFlow
TechTalk.SpecFlow.Generator/UnitTestProvider/XUnit2TestGeneratorProvider.cs
6,994
C#
//--------------------------------------------------------------------- // <copyright file="EdmNavigationProperty.cs" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information. // </copyright> //--------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Diagnostics; namespace ODataToolkit { /// <summary> /// Represents an EDM navigation property. /// </summary> public sealed class EdmNavigationProperty : EdmProperty, IEdmNavigationProperty { private readonly IEdmReferentialConstraint referentialConstraint; private readonly bool containsTarget; private readonly EdmOnDeleteAction onDelete; private IEdmNavigationProperty partner; private EdmNavigationProperty( IEdmStructuredType declaringType, string name, IEdmTypeReference type, IEnumerable<IEdmStructuralProperty> dependentProperties, IEnumerable<IEdmStructuralProperty> principalProperties, bool containsTarget, EdmOnDeleteAction onDelete) : base(declaringType, name, type) { this.containsTarget = containsTarget; this.onDelete = onDelete; if (dependentProperties != null) { this.referentialConstraint = EdmReferentialConstraint.Create(dependentProperties, principalProperties); } } /// <summary> /// Gets the kind of this property. /// </summary> public override EdmPropertyKind PropertyKind { get { return EdmPropertyKind.Navigation; } } /// <summary> /// Gets a value indicating whether the navigation target is contained inside the navigation source. /// </summary> public bool ContainsTarget { get { return this.containsTarget; } } /// <summary> /// Gets the referential constraint for this navigation, returning null if this is the principal end or if there is no referential constraint. /// </summary> public IEdmReferentialConstraint ReferentialConstraint { get { return this.referentialConstraint; } } /// <summary> /// Gets the action to take when an instance of the declaring type is deleted. /// </summary> public EdmOnDeleteAction OnDelete { get { return this.onDelete; } } /// <summary> /// Gets the partner of this navigation property. /// </summary> public IEdmNavigationProperty Partner { get { return this.partner; } } /// <summary> /// Gets the path to the partner in the related entity type. /// </summary> /// <remarks> /// Is null if the containing type is a complex type. /// </remarks> internal IEdmPathExpression PartnerPath { get; private set; } /// <summary> /// Creates a navigation property from the given information. /// </summary> /// <param name="declaringType">The type that declares this property.</param> /// <param name="propertyInfo">Information to create the navigation property.</param> /// <returns>Created navigation property.</returns> public static EdmNavigationProperty CreateNavigationProperty(IEdmStructuredType declaringType, EdmNavigationPropertyInfo propertyInfo) { EdmUtil.CheckArgumentNull(propertyInfo, "propertyInfo"); EdmUtil.CheckArgumentNull(propertyInfo.Name, "propertyInfo.Name"); EdmUtil.CheckArgumentNull(propertyInfo.Target, "propertyInfo.Target"); return new EdmNavigationProperty( declaringType, propertyInfo.Name, CreateNavigationPropertyType(propertyInfo.Target, propertyInfo.TargetMultiplicity, "propertyInfo.TargetMultiplicity"), propertyInfo.DependentProperties, propertyInfo.PrincipalProperties, propertyInfo.ContainsTarget, propertyInfo.OnDelete); } /// <summary> /// Creates two navigation properties representing an association between two entity types. /// </summary> /// <param name="propertyInfo">Information to create the navigation property.</param> /// <param name="partnerInfo">Information to create the partner navigation property.</param> /// <returns>Created navigation property.</returns> public static EdmNavigationProperty CreateNavigationPropertyWithPartner(EdmNavigationPropertyInfo propertyInfo, EdmNavigationPropertyInfo partnerInfo) { EdmUtil.CheckArgumentNull(propertyInfo, "propertyInfo"); EdmUtil.CheckArgumentNull(propertyInfo.Name, "propertyInfo.Name"); EdmUtil.CheckArgumentNull(propertyInfo.Target, "propertyInfo.Target"); EdmUtil.CheckArgumentNull(partnerInfo, "partnerInfo"); EdmUtil.CheckArgumentNull(partnerInfo.Name, "partnerInfo.Name"); EdmUtil.CheckArgumentNull(partnerInfo.Target, "partnerInfo.Target"); EdmNavigationProperty end1 = new EdmNavigationProperty( partnerInfo.Target, propertyInfo.Name, CreateNavigationPropertyType(propertyInfo.Target, propertyInfo.TargetMultiplicity, "propertyInfo.TargetMultiplicity"), propertyInfo.DependentProperties, propertyInfo.PrincipalProperties, propertyInfo.ContainsTarget, propertyInfo.OnDelete); EdmNavigationProperty end2 = new EdmNavigationProperty( propertyInfo.Target, partnerInfo.Name, CreateNavigationPropertyType(partnerInfo.Target, partnerInfo.TargetMultiplicity, "partnerInfo.TargetMultiplicity"), partnerInfo.DependentProperties, partnerInfo.PrincipalProperties, partnerInfo.ContainsTarget, partnerInfo.OnDelete); end1.SetPartner(end2, new EdmPathExpression(end2.Name)); end2.SetPartner(end1, new EdmPathExpression(end1.Name)); return end1; } /// <summary> /// Creates two navigation properties representing an association between two entity types. /// </summary> /// <param name="propertyName">Navigation property name.</param> /// <param name="propertyType">Type of the navigation property.</param> /// <param name="dependentProperties">Dependent properties of the navigation source.</param> /// <param name="principalProperties">Principal properties of the navigation source.</param> /// <param name="containsTarget">A value indicating whether the navigation source logically contains the navigation target.</param> /// <param name="onDelete">Action to take upon deletion of an instance of the navigation source.</param> /// <param name="partnerPropertyName">Navigation partner property name.</param> /// <param name="partnerPropertyType">Type of the navigation partner property.</param> /// <param name="partnerDependentProperties">Dependent properties of the navigation target.</param> /// <param name="partnerPrincipalProperties">Principal properties of the navigation target.</param> /// <param name="partnerContainsTarget">A value indicating whether the navigation target logically contains the navigation source.</param> /// <param name="partnerOnDelete">Action to take upon deletion of an instance of the navigation target.</param> /// <returns>Navigation property.</returns> public static EdmNavigationProperty CreateNavigationPropertyWithPartner( string propertyName, IEdmTypeReference propertyType, IEnumerable<IEdmStructuralProperty> dependentProperties, IEnumerable<IEdmStructuralProperty> principalProperties, bool containsTarget, EdmOnDeleteAction onDelete, string partnerPropertyName, IEdmTypeReference partnerPropertyType, IEnumerable<IEdmStructuralProperty> partnerDependentProperties, IEnumerable<IEdmStructuralProperty> partnerPrincipalProperties, bool partnerContainsTarget, EdmOnDeleteAction partnerOnDelete) { EdmUtil.CheckArgumentNull(propertyName, "propertyName"); EdmUtil.CheckArgumentNull(propertyType, "propertyType"); EdmUtil.CheckArgumentNull(partnerPropertyName, "partnerPropertyName"); EdmUtil.CheckArgumentNull(partnerPropertyType, "partnerPropertyType"); IEdmEntityType declaringType = GetEntityType(partnerPropertyType); if (declaringType == null) { throw new ArgumentException(Strings.Constructable_EntityTypeOrCollectionOfEntityTypeExpected, "partnerPropertyType"); } IEdmEntityType partnerDeclaringType = GetEntityType(propertyType); if (partnerDeclaringType == null) { throw new ArgumentException(Strings.Constructable_EntityTypeOrCollectionOfEntityTypeExpected, "propertyType"); } EdmNavigationProperty end1 = new EdmNavigationProperty( declaringType, propertyName, propertyType, dependentProperties, principalProperties, containsTarget, onDelete); EdmNavigationProperty end2 = new EdmNavigationProperty( partnerDeclaringType, partnerPropertyName, partnerPropertyType, partnerDependentProperties, partnerPrincipalProperties, partnerContainsTarget, partnerOnDelete); end1.SetPartner(end2, new EdmPathExpression(end2.Name)); end2.SetPartner(end1, new EdmPathExpression(end1.Name)); return end1; } /// <summary> /// Sets the partner information. /// </summary> /// <param name="navigationProperty">The partner navigation property.</param> /// <param name="navigationPropertyPath">Path to the partner navigation property in the related entity type.</param> internal void SetPartner(IEdmNavigationProperty navigationProperty, IEdmPathExpression navigationPropertyPath) { Debug.Assert( DeclaringType is IEdmEntityType, "Partner info cannot be set for nav. property on a non-entity type."); partner = navigationProperty; PartnerPath = navigationPropertyPath; } private static IEdmEntityType GetEntityType(IEdmTypeReference type) { IEdmEntityType entityType = null; if (type.IsEntity()) { entityType = (IEdmEntityType)type.Definition; } else if (type.IsCollection()) { type = ((IEdmCollectionType)type.Definition).ElementType; if (type.IsEntity()) { entityType = (IEdmEntityType)type.Definition; } } return entityType; } private static IEdmTypeReference CreateNavigationPropertyType(IEdmEntityType entityType, EdmMultiplicity multiplicity, string multiplicityParameterName) { switch (multiplicity) { case EdmMultiplicity.ZeroOrOne: return new EdmEntityTypeReference(entityType, true); case EdmMultiplicity.One: return new EdmEntityTypeReference(entityType, false); case EdmMultiplicity.Many: return EdmCoreModel.GetCollection(new EdmEntityTypeReference(entityType, false)); default: throw new ArgumentOutOfRangeException(multiplicityParameterName, Strings.UnknownEnumVal_Multiplicity(multiplicity)); } } } }
45.334559
160
0.635553
[ "MIT" ]
GCAE/ODataToolkit
ODataToolkit/Edm/Schema/EdmNavigationProperty.cs
12,331
C#
using System; using System.ComponentModel; using JetBrains.Annotations; using Lykke.Bil2.SharedDomain.TypeConverters; namespace Lykke.Bil2.SharedDomain { [PublicAPI] [Serializable] [TypeConverter(typeof(BlockIdTypeConverter))] public sealed class BlockId : BaseStringValueType<BlockId> { public BlockId(string value) : base(value) { } public static implicit operator BlockId(string value) { return value != null ? new BlockId(value) : null; } public static implicit operator string(BlockId value) { return value?.Value; } } }
22.931034
62
0.625564
[ "MIT" ]
LykkeCity/Lykke.Bil2.SharedDomain
src/Lykke.Bil2.SharedDomain/BlockId.cs
667
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Server_nw.MusicApplication.Entities { public class Performer : User { public List<Song> Songs { get; set; } public List<Album> Albums { get; set; } public Performer() { Songs = new List<Song>(); Albums = new List<Album>(); } } }
19.809524
47
0.59375
[ "MIT" ]
Andrewst-commits/MyMusicServer
Server_nw/Server_nw/MusicService/Entities/Performer.cs
418
C#
// Copyright 2017-2021 Elringus (Artyom Sovetnikov). All rights reserved. using System.Collections.Generic; using Naninovel.Commands; using System.Linq; using UnityEngine; namespace Naninovel.FX { public class DepthOfField : MonoBehaviour, Spawn.IParameterized, Spawn.IAwaitable, DestroySpawned.IParameterized, DestroySpawned.IAwaitable { protected float FocusDistance { get; private set; } protected float FocalLength { get; private set; } protected float Duration { get; private set; } protected float StopDuration { get; private set; } [SerializeField] private float defaultFocusDistance = 10f; [SerializeField] private float defaultFocalLength = 3.75f; [SerializeField] private float defaultDuration = 1f; private static readonly int blurTexId = Shader.PropertyToID("_BlurTex"); private static readonly int distanceId = Shader.PropertyToID("_Distance"); private static readonly int lensCoeffId = Shader.PropertyToID("_LensCoeff"); private static readonly int maxCoCId = Shader.PropertyToID("_MaxCoC"); private static readonly int rcpMaxCoCId = Shader.PropertyToID("_RcpMaxCoC"); private static readonly int rcpAspectId = Shader.PropertyToID("_RcpAspect"); private readonly Tweener<FloatTween> focusDistanceTweener = new Tweener<FloatTween>(); private readonly Tweener<FloatTween> focalLengthTweener = new Tweener<FloatTween>(); private CameraComponent cameraComponent; public virtual void SetSpawnParameters (IReadOnlyList<string> parameters) { if (cameraComponent is null) { var cameraManager = Engine.GetService<ICameraManager>().Camera; cameraComponent = cameraManager.gameObject.AddComponent<CameraComponent>(); cameraComponent.UseCameraFov = false; } if (cameraComponent.PointOfFocus != null) { cameraComponent.FocusDistance = Vector3.Dot(cameraComponent.PointOfFocus.position - cameraComponent.transform.position, cameraComponent.transform.forward); cameraComponent.PointOfFocus = null; } var focusObjectName = parameters?.ElementAtOrDefault(0); if (string.IsNullOrEmpty(focusObjectName)) FocusDistance = Mathf.Max(0.01f, parameters?.ElementAtOrDefault(1)?.AsInvariantFloat() ?? defaultFocusDistance); else { var obj = GameObject.Find(focusObjectName); if (ObjectUtils.IsValid(obj)) cameraComponent.PointOfFocus = obj.transform; else { Debug.LogWarning($"Failed to find game object with name `{focusObjectName}`; depth of field effect will use a default focus distance."); FocusDistance = defaultFocusDistance; } } FocalLength = Mathf.Abs(parameters?.ElementAtOrDefault(2)?.AsInvariantFloat() ?? defaultFocalLength); Duration = Mathf.Abs(parameters?.ElementAtOrDefault(3)?.AsInvariantFloat() ?? defaultDuration); } public async UniTask AwaitSpawnAsync (AsyncToken asyncToken = default) { if (focusDistanceTweener.Running) focusDistanceTweener.CompleteInstantly(); if (focalLengthTweener.Running) focalLengthTweener.CompleteInstantly(); var duration = asyncToken.Completed ? 0 : Duration; var focusDistanceTween = new FloatTween(cameraComponent.FocusDistance, FocusDistance, duration, ApplyFocusDistance); var focalLengthTween = new FloatTween(cameraComponent.FocalLength, FocalLength, duration, ApplyFocalLength); await UniTask.WhenAll(focusDistanceTweener.RunAsync(focusDistanceTween, asyncToken, cameraComponent), focalLengthTweener.RunAsync(focalLengthTween, asyncToken, cameraComponent)); } public void SetDestroyParameters (IReadOnlyList<string> parameters) { StopDuration = Mathf.Abs(parameters?.ElementAtOrDefault(0)?.AsInvariantFloat() ?? defaultDuration); } public async UniTask AwaitDestroyAsync (AsyncToken asyncToken = default) { if (focusDistanceTweener.Running) focusDistanceTweener.CompleteInstantly(); if (focalLengthTweener.Running) focalLengthTweener.CompleteInstantly(); var duration = asyncToken.Completed ? 0 : StopDuration; var focalLengthTween = new FloatTween(cameraComponent.FocalLength, 0, duration, ApplyFocalLength); await focalLengthTweener.RunAsync(focalLengthTween, asyncToken); } private void ApplyFocusDistance (float value) { cameraComponent.FocusDistance = value; } private void ApplyFocalLength (float value) { cameraComponent.FocalLength = value; } private void OnDestroy () // Required to disable the effect on rollback. { if (cameraComponent) Destroy(cameraComponent); } private class CameraComponent : MonoBehaviour { private enum KernelSizeType { Small, Medium, Large, VeryLarge } public Transform PointOfFocus { get; set; } = null; public float FocusDistance { get; set; } = 0f; public bool UseCameraFov { get; set; } = true; public float FocalLength { get; set; } = 0f; private const KernelSizeType kernelSize = KernelSizeType.Medium; private const float fNumber = 1.4f; private const float filmHeight = 0.024f; private Camera targetCamera; private Material material; private void OnEnable () { targetCamera = GetComponent<Camera>(); var shader = Shader.Find("Naninovel/FX/DepthOfField"); if (!shader.isSupported || !SystemInfo.SupportsRenderTextureFormat(RenderTextureFormat.ARGBHalf)) { Debug.LogWarning("Naninovel's Depth Of Field is not supported on the current platform."); return; } if (material is null) { material = new Material(shader); material.hideFlags = HideFlags.HideAndDontSave; } targetCamera.depthTextureMode |= DepthTextureMode.Depth; } private void OnDestroy () { ObjectUtils.DestroyOrImmediate(material); } private void OnRenderImage (RenderTexture source, RenderTexture destination) { // If the material hasn't been initialized because of system // incompatibility, just blit and return. if (material == null) { Graphics.Blit(source, destination); // Try to disable itself if it's Player. if (Application.isPlaying) enabled = false; return; } var width = source.width; var height = source.height; SetUpShaderParameters(source); // Pass #1 - Downsampling, prefiltering and CoC calculation var rt1 = RenderTexture.GetTemporary(width / 2, height / 2, 0, RenderTextureFormat.ARGBHalf); source.filterMode = FilterMode.Point; Graphics.Blit(source, rt1, material, 0); // Pass #2 - Bokeh simulation var rt2 = RenderTexture.GetTemporary(width / 2, height / 2, 0, RenderTextureFormat.ARGBHalf); rt1.filterMode = FilterMode.Bilinear; Graphics.Blit(rt1, rt2, material, 1 + (int)kernelSize); // Pass #3 - Additional blur rt2.filterMode = FilterMode.Bilinear; Graphics.Blit(rt2, rt1, material, 5); // Pass #4 - Upsampling and composition material.SetTexture(blurTexId, rt1); Graphics.Blit(source, destination, material, 6); RenderTexture.ReleaseTemporary(rt1); RenderTexture.ReleaseTemporary(rt2); } private float CalculateFocalLength () { if (!UseCameraFov) return FocalLength; var fov = targetCamera.fieldOfView * Mathf.Deg2Rad; return 0.5f * filmHeight / Mathf.Tan(0.5f * fov); } private float CalculateMaxCoCRadius (int screenHeight) { // Estimate the allowable maximum radius of CoC from the kernel // size (the equation below was empirically derived). const float radiusInPixels = (float)kernelSize * 4 + 6; // Applying a 5% limit to the CoC radius to keep the size of // TileMax/NeighborMax small enough. return Mathf.Min(0.05f, radiusInPixels / screenHeight); } private void SetUpShaderParameters (RenderTexture source) { var dist = PointOfFocus != null ? Vector3.Dot(PointOfFocus.position - targetCamera.transform.position, targetCamera.transform.forward) : FocusDistance; var f = CalculateFocalLength(); var s1 = Mathf.Max(dist, f); material.SetFloat(distanceId, s1); var coeff = f * f / (fNumber * (s1 - f) * filmHeight * 2); coeff = Mathf.Max(.001f, coeff); // Clamp the value to prevent glitches when gradually disabling the effect. material.SetFloat(lensCoeffId, coeff); var maxCoC = CalculateMaxCoCRadius(source.height); material.SetFloat(maxCoCId, maxCoC); material.SetFloat(rcpMaxCoCId, 1 / maxCoC); var rcpAspect = (float)source.height / source.width; material.SetFloat(rcpAspectId, rcpAspect); } } } }
44.051724
171
0.605773
[ "Unlicense" ]
ChrisKindred/CartomancyGame
CartomancyGame/Assets/Naninovel/Runtime/FX/DepthOfField.cs
10,220
C#
using System; using UnityEngine; using UnityEngine.Experimental.VFX; namespace UnityEditor.VFX { public class LoopAndDelay : VFXSpawnerCallbacks { public class InputProperties { public int NumLoops = 2; public float LoopDuration = 4.0f; public float Delay = 1.0f; } bool m_Waiting; float m_WaitTTL; int m_RemainingLoops = int.MinValue; static private readonly int numLoopsPropertyID = Shader.PropertyToID("NumLoops"); static private readonly int loopDurationPropertyID = Shader.PropertyToID("LoopDuration"); static private readonly int delayPropertyID = Shader.PropertyToID("Delay"); public sealed override void OnPlay(VFXSpawnerState state, VFXExpressionValues vfxValues, VisualEffect vfxComponent) { } public sealed override void OnUpdate(VFXSpawnerState state, VFXExpressionValues vfxValues, VisualEffect vfxComponent) { if (m_RemainingLoops == int.MinValue) m_RemainingLoops = vfxValues.GetInt(numLoopsPropertyID); if (state.totalTime > vfxValues.GetFloat(loopDurationPropertyID)) { if (!m_Waiting) { m_WaitTTL = vfxValues.GetFloat(delayPropertyID); m_Waiting = true; } else { m_WaitTTL -= state.deltaTime; if (m_WaitTTL < 0.0f) { m_Waiting = false; state.totalTime = 0.0f; if (m_RemainingLoops > 0) // if positive, remove one from count m_RemainingLoops--; if (m_RemainingLoops != 0) // if 0, stop forever state.playing = true; // Re-enable the spawn context m_RemainingLoops = Math.Max(-1, m_RemainingLoops); // sustain at -1 if in infinite mode } else { state.playing = false; // Stop the Spawn context for the duration of the delay } } } } public sealed override void OnStop(VFXSpawnerState state, VFXExpressionValues vfxValues, VisualEffect vfxComponent) { } } }
34.5
125
0.545756
[ "BSD-2-Clause" ]
1-10/VisualEffectGraphSample
GitHub/com.unity.visualeffectgraph/CustomSpawners/LoopAndDelay.cs
2,415
C#
// ------------------------------------------------------------------------------ // <auto-generated> // Generated by Xsd2Code. Version 3.4.0.18239 Microsoft Reciprocal License (Ms-RL) // <NameSpace>Dms.Ambulance.V2100</NameSpace><Collection>Array</Collection><codeType>CSharp</codeType><EnableDataBinding>False</EnableDataBinding><EnableLazyLoading>False</EnableLazyLoading><TrackingChangesEnable>False</TrackingChangesEnable><GenTrackingClasses>False</GenTrackingClasses><HidePrivateFieldInIDE>False</HidePrivateFieldInIDE><EnableSummaryComment>True</EnableSummaryComment><VirtualProp>False</VirtualProp><IncludeSerializeMethod>True</IncludeSerializeMethod><UseBaseClass>False</UseBaseClass><GenBaseClass>False</GenBaseClass><GenerateCloneMethod>True</GenerateCloneMethod><GenerateDataContracts>False</GenerateDataContracts><CodeBaseTag>Net35</CodeBaseTag><SerializeMethodName>Serialize</SerializeMethodName><DeserializeMethodName>Deserialize</DeserializeMethodName><SaveToFileMethodName>SaveToFile</SaveToFileMethodName><LoadFromFileMethodName>LoadFromFile</LoadFromFileMethodName><GenerateXMLAttributes>True</GenerateXMLAttributes><OrderXMLAttrib>False</OrderXMLAttrib><EnableEncoding>False</EnableEncoding><AutomaticProperties>False</AutomaticProperties><GenerateShouldSerialize>False</GenerateShouldSerialize><DisableDebug>False</DisableDebug><PropNameSpecified>Default</PropNameSpecified><Encoder>UTF8</Encoder><CustomUsings></CustomUsings><ExcludeIncludedTypes>True</ExcludeIncludedTypes><EnableInitializeFields>False</EnableInitializeFields> // </auto-generated> // ------------------------------------------------------------------------------ namespace Dms.Ambulance.V2100 { using System; using System.Diagnostics; using System.Xml.Serialization; using System.Collections; using System.Xml.Schema; using System.ComponentModel; using System.IO; using System.Text; [System.CodeDom.Compiler.GeneratedCodeAttribute("Xsd2Code", "3.4.0.18239")] [System.SerializableAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.XmlTypeAttribute(TypeName="StrucDoc.Thead", Namespace="urn:hl7-org:v3")] public partial class StrucDocThead { private StrucDocTr[] trField; private string idField; private string languageField; private string styleCodeField; private StrucDocTheadAlign alignField; private bool alignFieldSpecified; private string charField; private string charoffField; private StrucDocTheadValign valignField; private bool valignFieldSpecified; private static System.Xml.Serialization.XmlSerializer serializer; [System.Xml.Serialization.XmlElementAttribute("tr")] public StrucDocTr[] tr { get { return this.trField; } set { this.trField = value; } } [System.Xml.Serialization.XmlAttributeAttribute(DataType="ID")] public string ID { get { return this.idField; } set { this.idField = value; } } [System.Xml.Serialization.XmlAttributeAttribute(DataType="NMTOKEN")] public string language { get { return this.languageField; } set { this.languageField = value; } } [System.Xml.Serialization.XmlAttributeAttribute(DataType="NMTOKENS")] public string styleCode { get { return this.styleCodeField; } set { this.styleCodeField = value; } } [System.Xml.Serialization.XmlAttributeAttribute()] public StrucDocTheadAlign align { get { return this.alignField; } set { this.alignField = value; } } [System.Xml.Serialization.XmlIgnoreAttribute()] public bool alignSpecified { get { return this.alignFieldSpecified; } set { this.alignFieldSpecified = value; } } [System.Xml.Serialization.XmlAttributeAttribute()] public string @char { get { return this.charField; } set { this.charField = value; } } [System.Xml.Serialization.XmlAttributeAttribute()] public string charoff { get { return this.charoffField; } set { this.charoffField = value; } } [System.Xml.Serialization.XmlAttributeAttribute()] public StrucDocTheadValign valign { get { return this.valignField; } set { this.valignField = value; } } [System.Xml.Serialization.XmlIgnoreAttribute()] public bool valignSpecified { get { return this.valignFieldSpecified; } set { this.valignFieldSpecified = value; } } private static System.Xml.Serialization.XmlSerializer Serializer { get { if ((serializer == null)) { serializer = new System.Xml.Serialization.XmlSerializer(typeof(StrucDocThead)); } return serializer; } } #region Serialize/Deserialize /// <summary> /// Serializes current StrucDocThead object into an XML document /// </summary> /// <returns>string XML value</returns> public virtual string Serialize() { System.IO.StreamReader streamReader = null; System.IO.MemoryStream memoryStream = null; try { memoryStream = new System.IO.MemoryStream(); Serializer.Serialize(memoryStream, this); memoryStream.Seek(0, System.IO.SeekOrigin.Begin); streamReader = new System.IO.StreamReader(memoryStream); return streamReader.ReadToEnd(); } finally { if ((streamReader != null)) { streamReader.Dispose(); } if ((memoryStream != null)) { memoryStream.Dispose(); } } } /// <summary> /// Deserializes workflow markup into an StrucDocThead object /// </summary> /// <param name="xml">string workflow markup to deserialize</param> /// <param name="obj">Output StrucDocThead object</param> /// <param name="exception">output Exception value if deserialize failed</param> /// <returns>true if this XmlSerializer can deserialize the object; otherwise, false</returns> public static bool Deserialize(string xml, out StrucDocThead obj, out System.Exception exception) { exception = null; obj = default(StrucDocThead); try { obj = Deserialize(xml); return true; } catch (System.Exception ex) { exception = ex; return false; } } public static bool Deserialize(string xml, out StrucDocThead obj) { System.Exception exception = null; return Deserialize(xml, out obj, out exception); } public static StrucDocThead Deserialize(string xml) { System.IO.StringReader stringReader = null; try { stringReader = new System.IO.StringReader(xml); return ((StrucDocThead)(Serializer.Deserialize(System.Xml.XmlReader.Create(stringReader)))); } finally { if ((stringReader != null)) { stringReader.Dispose(); } } } /// <summary> /// Serializes current StrucDocThead object into file /// </summary> /// <param name="fileName">full path of outupt xml file</param> /// <param name="exception">output Exception value if failed</param> /// <returns>true if can serialize and save into file; otherwise, false</returns> public virtual bool SaveToFile(string fileName, out System.Exception exception) { exception = null; try { SaveToFile(fileName); return true; } catch (System.Exception e) { exception = e; return false; } } public virtual void SaveToFile(string fileName) { System.IO.StreamWriter streamWriter = null; try { string xmlString = Serialize(); System.IO.FileInfo xmlFile = new System.IO.FileInfo(fileName); streamWriter = xmlFile.CreateText(); streamWriter.WriteLine(xmlString); streamWriter.Close(); } finally { if ((streamWriter != null)) { streamWriter.Dispose(); } } } /// <summary> /// Deserializes xml markup from file into an StrucDocThead object /// </summary> /// <param name="fileName">string xml file to load and deserialize</param> /// <param name="obj">Output StrucDocThead object</param> /// <param name="exception">output Exception value if deserialize failed</param> /// <returns>true if this XmlSerializer can deserialize the object; otherwise, false</returns> public static bool LoadFromFile(string fileName, out StrucDocThead obj, out System.Exception exception) { exception = null; obj = default(StrucDocThead); try { obj = LoadFromFile(fileName); return true; } catch (System.Exception ex) { exception = ex; return false; } } public static bool LoadFromFile(string fileName, out StrucDocThead obj) { System.Exception exception = null; return LoadFromFile(fileName, out obj, out exception); } public static StrucDocThead LoadFromFile(string fileName) { System.IO.FileStream file = null; System.IO.StreamReader sr = null; try { file = new System.IO.FileStream(fileName, FileMode.Open, FileAccess.Read); sr = new System.IO.StreamReader(file); string xmlString = sr.ReadToEnd(); sr.Close(); file.Close(); return Deserialize(xmlString); } finally { if ((file != null)) { file.Dispose(); } if ((sr != null)) { sr.Dispose(); } } } #endregion #region Clone method /// <summary> /// Create a clone of this StrucDocThead object /// </summary> public virtual StrucDocThead Clone() { return ((StrucDocThead)(this.MemberwiseClone())); } #endregion } }
38.045307
1,368
0.550527
[ "MIT" ]
Kusnaditjung/MimDms
src/Dms.Ambulance.V2100/Generated/StrucDocThead.cs
11,756
C#
// Copyright (c) Pomelo Foundation. All rights reserved. // Licensed under the MIT. See LICENSE in the project root for license information. using System; using System.Linq; using Pomelo.EntityFrameworkCore.MySql.Infrastructure.Internal; using Pomelo.EntityFrameworkCore.MySql.Storage.Internal; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Pomelo.EntityFrameworkCore.MySql.Infrastructure; using Microsoft.EntityFrameworkCore.Diagnostics; using MySqlConnector; using Pomelo.EntityFrameworkCore.MySql.Storage; namespace Pomelo.EntityFrameworkCore.MySql.Internal { public class MySqlOptions : IMySqlOptions { private static readonly MySqlSchemaNameTranslator _ignoreSchemaNameTranslator = (_, objectName) => objectName; public MySqlOptions() { ConnectionSettings = new MySqlConnectionSettings(); ServerVersion = null; // We do not use the MySQL versions's default, but explicitly use `utf8mb4` // if not changed by the user. CharSet = CharSet.Utf8Mb4; // NCHAR and NVARCHAR are prefdefined by MySQL. NationalCharSet = CharSet.Utf8Mb3; ReplaceLineBreaksWithCharFunction = true; DefaultDataTypeMappings = new MySqlDefaultDataTypeMappings(); // Throw by default if a schema is being used with any type. SchemaNameTranslator = null; // TODO: Change to `true` for EF Core 5. IndexOptimizedBooleanColumns = false; LimitKeyedOrIndexedStringColumnLength = true; } public virtual void Initialize(IDbContextOptions options) { var mySqlOptions = options.FindExtension<MySqlOptionsExtension>() ?? new MySqlOptionsExtension(); var mySqlJsonOptions = (MySqlJsonOptionsExtension)options.Extensions.LastOrDefault(e => e is MySqlJsonOptionsExtension); ConnectionSettings = GetConnectionSettings(mySqlOptions); ServerVersion = mySqlOptions.ServerVersion ?? throw new InvalidOperationException($"The {nameof(ServerVersion)} has not been set."); CharSet = mySqlOptions.CharSet ?? CharSet; NoBackslashEscapes = mySqlOptions.NoBackslashEscapes; ReplaceLineBreaksWithCharFunction = mySqlOptions.ReplaceLineBreaksWithCharFunction; DefaultDataTypeMappings = ApplyDefaultDataTypeMappings(mySqlOptions.DefaultDataTypeMappings, ConnectionSettings); SchemaNameTranslator = mySqlOptions.SchemaNameTranslator ?? (mySqlOptions.SchemaBehavior == MySqlSchemaBehavior.Ignore ? _ignoreSchemaNameTranslator : null); IndexOptimizedBooleanColumns = mySqlOptions.IndexOptimizedBooleanColumns; JsonChangeTrackingOptions = mySqlJsonOptions?.JsonChangeTrackingOptions ?? default; LimitKeyedOrIndexedStringColumnLength = mySqlOptions.LimitKeyedOrIndexedStringColumnLength; } public virtual void Validate(IDbContextOptions options) { var mySqlOptions = options.FindExtension<MySqlOptionsExtension>() ?? new MySqlOptionsExtension(); var mySqlJsonOptions = (MySqlJsonOptionsExtension)options.Extensions.LastOrDefault(e => e is MySqlJsonOptionsExtension); var connectionSettings = GetConnectionSettings(mySqlOptions); if (!Equals(ServerVersion, mySqlOptions.ServerVersion)) { throw new InvalidOperationException( CoreStrings.SingletonOptionChanged( nameof(MySqlOptionsExtension.ServerVersion), nameof(DbContextOptionsBuilder.UseInternalServiceProvider))); } if (!Equals(ConnectionSettings.TreatTinyAsBoolean, connectionSettings.TreatTinyAsBoolean)) { throw new InvalidOperationException( CoreStrings.SingletonOptionChanged( nameof(MySqlConnectionStringBuilder.TreatTinyAsBoolean), nameof(DbContextOptionsBuilder.UseInternalServiceProvider))); } if (!Equals(ConnectionSettings.GuidFormat, connectionSettings.GuidFormat)) { throw new InvalidOperationException( CoreStrings.SingletonOptionChanged( nameof(MySqlConnectionStringBuilder.GuidFormat), nameof(DbContextOptionsBuilder.UseInternalServiceProvider))); } if (!Equals(CharSet, mySqlOptions.CharSet ?? CharSet.Utf8Mb4)) { throw new InvalidOperationException( CoreStrings.SingletonOptionChanged( nameof(MySqlDbContextOptionsBuilder.CharSet), nameof(DbContextOptionsBuilder.UseInternalServiceProvider))); } if (!Equals(NoBackslashEscapes, mySqlOptions.NoBackslashEscapes)) { throw new InvalidOperationException( CoreStrings.SingletonOptionChanged( nameof(MySqlDbContextOptionsBuilder.DisableBackslashEscaping), nameof(DbContextOptionsBuilder.UseInternalServiceProvider))); } if (!Equals(ReplaceLineBreaksWithCharFunction, mySqlOptions.ReplaceLineBreaksWithCharFunction)) { throw new InvalidOperationException( CoreStrings.SingletonOptionChanged( nameof(MySqlDbContextOptionsBuilder.DisableLineBreakToCharSubstition), nameof(DbContextOptionsBuilder.UseInternalServiceProvider))); } if (!Equals(DefaultDataTypeMappings, ApplyDefaultDataTypeMappings(mySqlOptions.DefaultDataTypeMappings ?? new MySqlDefaultDataTypeMappings(), connectionSettings))) { throw new InvalidOperationException( CoreStrings.SingletonOptionChanged( nameof(MySqlDbContextOptionsBuilder.DefaultDataTypeMappings), nameof(DbContextOptionsBuilder.UseInternalServiceProvider))); } if (!Equals( SchemaNameTranslator, mySqlOptions.SchemaBehavior == MySqlSchemaBehavior.Ignore ? _ignoreSchemaNameTranslator : SchemaNameTranslator)) { throw new InvalidOperationException( CoreStrings.SingletonOptionChanged( nameof(MySqlDbContextOptionsBuilder.SchemaBehavior), nameof(DbContextOptionsBuilder.UseInternalServiceProvider))); } if (!Equals(IndexOptimizedBooleanColumns, mySqlOptions.IndexOptimizedBooleanColumns)) { throw new InvalidOperationException( CoreStrings.SingletonOptionChanged( nameof(MySqlDbContextOptionsBuilder.EnableIndexOptimizedBooleanColumns), nameof(DbContextOptionsBuilder.UseInternalServiceProvider))); } if (!Equals(JsonChangeTrackingOptions, mySqlJsonOptions?.JsonChangeTrackingOptions ?? default)) { throw new InvalidOperationException( CoreStrings.SingletonOptionChanged( nameof(MySqlJsonOptionsExtension.JsonChangeTrackingOptions), nameof(DbContextOptionsBuilder.UseInternalServiceProvider))); } if (!Equals(LimitKeyedOrIndexedStringColumnLength, mySqlOptions.LimitKeyedOrIndexedStringColumnLength)) { throw new InvalidOperationException( CoreStrings.SingletonOptionChanged( nameof(MySqlDbContextOptionsBuilder.LimitKeyedOrIndexedStringColumnLength), nameof(DbContextOptionsBuilder.UseInternalServiceProvider))); } } protected virtual MySqlDefaultDataTypeMappings ApplyDefaultDataTypeMappings(MySqlDefaultDataTypeMappings defaultDataTypeMappings, MySqlConnectionSettings connectionSettings) { defaultDataTypeMappings ??= DefaultDataTypeMappings; // Explicitly set MySqlDefaultDataTypeMappings values take precedence over connection string options. if (connectionSettings.TreatTinyAsBoolean.HasValue && defaultDataTypeMappings.ClrBoolean == MySqlBooleanType.Default) { defaultDataTypeMappings = defaultDataTypeMappings.WithClrBoolean( connectionSettings.TreatTinyAsBoolean.Value ? MySqlBooleanType.TinyInt1 : MySqlBooleanType.Bit1); } if (defaultDataTypeMappings.ClrDateTime == MySqlDateTimeType.Default) { defaultDataTypeMappings = defaultDataTypeMappings.WithClrDateTime( ServerVersion.Supports.DateTime6 ? MySqlDateTimeType.DateTime6 : MySqlDateTimeType.DateTime); } if (defaultDataTypeMappings.ClrDateTimeOffset == MySqlDateTimeType.Default) { defaultDataTypeMappings = defaultDataTypeMappings.WithClrDateTimeOffset( ServerVersion.Supports.DateTime6 ? MySqlDateTimeType.DateTime6 : MySqlDateTimeType.DateTime); } if (defaultDataTypeMappings.ClrTimeSpan == MySqlTimeSpanType.Default) { defaultDataTypeMappings = defaultDataTypeMappings.WithClrTimeSpan( ServerVersion.Supports.DateTime6 ? MySqlTimeSpanType.Time6 : MySqlTimeSpanType.Time); } return defaultDataTypeMappings; } private static MySqlConnectionSettings GetConnectionSettings(MySqlOptionsExtension relationalOptions) { if (relationalOptions.Connection != null) { return new MySqlConnectionSettings(relationalOptions.Connection); } if (relationalOptions.ConnectionString != null) { return new MySqlConnectionSettings(relationalOptions.ConnectionString); } throw new InvalidOperationException(RelationalStrings.NoConnectionOrConnectionString); } protected bool Equals(MySqlOptions other) { return Equals(ConnectionSettings, other.ConnectionSettings) && Equals(ServerVersion, other.ServerVersion) && Equals(CharSet, other.CharSet) && Equals(NationalCharSet, other.NationalCharSet) && NoBackslashEscapes == other.NoBackslashEscapes && ReplaceLineBreaksWithCharFunction == other.ReplaceLineBreaksWithCharFunction && Equals(DefaultDataTypeMappings, other.DefaultDataTypeMappings) && Equals(SchemaNameTranslator, other.SchemaNameTranslator) && IndexOptimizedBooleanColumns == other.IndexOptimizedBooleanColumns && JsonChangeTrackingOptions == other.JsonChangeTrackingOptions && LimitKeyedOrIndexedStringColumnLength == other.LimitKeyedOrIndexedStringColumnLength; } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) { return false; } if (ReferenceEquals(this, obj)) { return true; } if (obj.GetType() != this.GetType()) { return false; } return Equals((MySqlOptions)obj); } public override int GetHashCode() { var hashCode = new HashCode(); hashCode.Add(ConnectionSettings); hashCode.Add(ServerVersion); hashCode.Add(CharSet); hashCode.Add(NationalCharSet); hashCode.Add(NoBackslashEscapes); hashCode.Add(ReplaceLineBreaksWithCharFunction); hashCode.Add(DefaultDataTypeMappings); hashCode.Add(SchemaNameTranslator); hashCode.Add(IndexOptimizedBooleanColumns); hashCode.Add(JsonChangeTrackingOptions); hashCode.Add(LimitKeyedOrIndexedStringColumnLength); return hashCode.ToHashCode(); } public virtual MySqlConnectionSettings ConnectionSettings { get; private set; } public virtual ServerVersion ServerVersion { get; private set; } public virtual CharSet CharSet { get; private set; } public virtual CharSet NationalCharSet { get; } public virtual bool NoBackslashEscapes { get; private set; } public virtual bool ReplaceLineBreaksWithCharFunction { get; private set; } public virtual MySqlDefaultDataTypeMappings DefaultDataTypeMappings { get; private set; } public virtual MySqlSchemaNameTranslator SchemaNameTranslator { get; private set; } public virtual bool IndexOptimizedBooleanColumns { get; private set; } public virtual MySqlJsonChangeTrackingOptions JsonChangeTrackingOptions { get; private set; } public virtual bool LimitKeyedOrIndexedStringColumnLength { get; private set; } } }
47.492958
181
0.645685
[ "MIT" ]
Rynaret/Pomelo.EntityFrameworkCore.MySql
src/EFCore.MySql/Internal/MySqlOptions.cs
13,488
C#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Testing; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Tools.Formatters; using Microsoft.CodeAnalysis.Tools.Tests.Utilities; using Microsoft.CodeAnalysis.Tools.Utilities; using Microsoft.Extensions.Logging; using Microsoft.VisualStudio.Composition; using Xunit; using Xunit.Abstractions; #nullable enable namespace Microsoft.CodeAnalysis.Tools.Tests.Formatters { public abstract class AbstractFormatterTest { private static MetadataReference MicrosoftVisualBasicReference => MetadataReference.CreateFromFile(typeof(Microsoft.VisualBasic.Strings).Assembly.Location); private static Lazy<IExportProviderFactory> ExportProviderFactory { get; } static AbstractFormatterTest() { ExportProviderFactory = new Lazy<IExportProviderFactory>( () => { var discovery = new AttributedPartDiscovery(Resolver.DefaultInstance, isNonPublicSupported: true); var parts = Task.Run(() => discovery.CreatePartsAsync(MefHostServices.DefaultAssemblies)).GetAwaiter().GetResult(); var catalog = ComposableCatalog.Create(Resolver.DefaultInstance).AddParts(parts); var configuration = CompositionConfiguration.Create(catalog); var runtimeComposition = RuntimeComposition.CreateRuntimeComposition(configuration); return runtimeComposition.CreateExportProviderFactory(); }, LazyThreadSafetyMode.ExecutionAndPublication); } protected virtual ReferenceAssemblies ReferenceAssemblies => ReferenceAssemblies.NetStandard.NetStandard20; protected virtual string DefaultFilePathPrefix => "Test"; protected virtual string DefaultTestProjectName => "TestProject"; // This folder path needs to appear rooted when adding the AnalyzerConfigDocument. // We achieve this by prepending a directory separator. protected virtual string DefaultFolderPath => Path.DirectorySeparatorChar + DefaultTestProjectName; protected virtual string DefaultTestProjectPath => Path.Combine(DefaultFolderPath, $"{DefaultTestProjectName}.{DefaultFileExt}proj"); protected virtual string DefaultEditorConfigPath => Path.Combine(DefaultFolderPath, ".editorconfig"); protected virtual string DefaultFilePath => Path.Combine(DefaultFolderPath, $"{DefaultFilePathPrefix}0.{DefaultFileExt}"); protected abstract string DefaultFileExt { get; } private protected abstract ICodeFormatter Formatter { get; } protected ITestOutputHelper? TestOutputHelper { get; set; } protected AbstractFormatterTest() { TestState = new SolutionState(DefaultFilePathPrefix, DefaultFileExt); } /// <summary> /// Gets the language name used for the test. /// </summary> public abstract string Language { get; } public SolutionState TestState { get; } private protected string ToEditorConfig(IReadOnlyDictionary<string, string> editorConfig) => $@"root = true [*.{DefaultFileExt}] { string.Join(Environment.NewLine, editorConfig.Select(kvp => $"{kvp.Key} = {kvp.Value}")) } "; private protected Task<SourceText> AssertCodeUnchangedAsync( string code, IReadOnlyDictionary<string, string> editorConfig, Encoding? encoding = null, FixCategory fixCategory = FixCategory.Whitespace, IEnumerable<AnalyzerReference>? analyzerReferences = null, DiagnosticSeverity codeStyleSeverity = DiagnosticSeverity.Error, DiagnosticSeverity analyzerSeverity = DiagnosticSeverity.Error) { return AssertCodeChangedAsync(code, code, ToEditorConfig(editorConfig), encoding, fixCategory, analyzerReferences, codeStyleSeverity, analyzerSeverity); } private protected Task<SourceText> AssertCodeChangedAsync( string testCode, string expectedCode, IReadOnlyDictionary<string, string> editorConfig, Encoding? encoding = null, FixCategory fixCategory = FixCategory.Whitespace, IEnumerable<AnalyzerReference>? analyzerReferences = null, DiagnosticSeverity codeStyleSeverity = DiagnosticSeverity.Error, DiagnosticSeverity analyzerSeverity = DiagnosticSeverity.Error) { return AssertCodeChangedAsync(testCode, expectedCode, ToEditorConfig(editorConfig), encoding, fixCategory, analyzerReferences, codeStyleSeverity, analyzerSeverity); } private protected async Task<SourceText> AssertCodeChangedAsync( string testCode, string expectedCode, string editorConfig, Encoding? encoding = null, FixCategory fixCategory = FixCategory.Whitespace, IEnumerable<AnalyzerReference>? analyzerReferences = null, DiagnosticSeverity codeStyleSeverity = DiagnosticSeverity.Error, DiagnosticSeverity analyzerSeverity = DiagnosticSeverity.Error) { var text = SourceText.From(testCode, encoding ?? Encoding.UTF8); TestState.Sources.Add(text); var solution = await GetSolutionAsync(TestState.Sources.ToArray(), TestState.AdditionalFiles.ToArray(), TestState.AdditionalReferences.ToArray(), editorConfig, analyzerReferences); var project = solution.Projects.Single(); var document = project.Documents.Single(); var fileMatcher = SourceFileMatcher.CreateMatcher(new[] { document.FilePath! }, exclude: Array.Empty<string>()); var formatOptions = new FormatOptions( workspaceFilePath: project.FilePath!, workspaceType: WorkspaceType.Solution, logLevel: LogLevel.Trace, fixCategory, codeStyleSeverity, analyzerSeverity, saveFormattedFiles: true, changesAreErrors: false, fileMatcher, reportPath: string.Empty, includeGeneratedFiles: false); var pathsToFormat = GetOnlyFileToFormat(solution); var logger = new TestLogger(); var formattedSolution = await Formatter.FormatAsync(solution, pathsToFormat, formatOptions, logger, new List<FormattedFile>(), default); var formattedDocument = GetOnlyDocument(formattedSolution); var formattedText = await formattedDocument.GetTextAsync(); try { Assert.Equal(expectedCode, formattedText.ToString()); } catch { TestOutputHelper?.WriteLine(logger.GetLog()); throw; } return formattedText; } /// <summary> /// Gets the only <see cref="DocumentId"/>. /// </summary> /// <param name="solution">A Solution containing a single Project containing a single Document.</param> /// <returns>The only document id.</returns> internal ImmutableArray<DocumentId> GetOnlyFileToFormat(Solution solution) => ImmutableArray.Create(GetOnlyDocument(solution).Id); /// <summary> /// Gets the only <see cref="Document"/> contained within the only <see cref="Project"/> within the <see cref="Solution"/>. /// </summary> /// <param name="solution">A Solution containing a single Project containing a single Document.</param> /// <returns>The document contained within.</returns> public Document GetOnlyDocument(Solution solution) => solution.Projects.Single().Documents.Single(); /// <summary> /// Gets the collection of inputs to provide to the XML documentation resolver. /// </summary> /// <remarks> /// <para>Files in this collection may be referenced via <c>&lt;include&gt;</c> elements in documentation /// comments.</para> /// </remarks> public Dictionary<string, string> XmlReferences { get; } = new Dictionary<string, string>(); /// <summary> /// Given an array of strings as sources and a language, turn them into a <see cref="Project"/> and return the /// solution. /// </summary> /// <param name="sources">Classes in the form of strings.</param> /// <param name="additionalFiles">Additional documents to include in the project.</param> /// <param name="additionalMetadataReferences">Additional metadata references to include in the project.</param> /// <param name="editorConfig">The .editorconfig to apply to this solution.</param> /// <returns>A solution containing a project with the specified sources and additional files.</returns> private protected async Task<Solution> GetSolutionAsync((string filename, SourceText content)[] sources, (string filename, SourceText content)[] additionalFiles, MetadataReference[] additionalMetadataReferences, IReadOnlyDictionary<string, string> editorConfig, IEnumerable<AnalyzerReference>? analyzerReferences = null) { return await GetSolutionAsync(sources, additionalFiles, additionalMetadataReferences, ToEditorConfig(editorConfig), analyzerReferences); } /// <summary> /// Given an array of strings as sources and a language, turn them into a <see cref="Project"/> and return the /// solution. /// </summary> /// <param name="sources">Classes in the form of strings.</param> /// <param name="additionalFiles">Additional documents to include in the project.</param> /// <param name="additionalMetadataReferences">Additional metadata references to include in the project.</param> /// <param name="editorConfig">The .editorconfig to apply to this solution.</param> /// <returns>A solution containing a project with the specified sources and additional files.</returns> private protected async Task<Solution> GetSolutionAsync((string filename, SourceText content)[] sources, (string filename, SourceText content)[] additionalFiles, MetadataReference[] additionalMetadataReferences, string editorConfig, IEnumerable<AnalyzerReference>? analyzerReferences = null) { analyzerReferences ??= Enumerable.Empty<AnalyzerReference>(); var project = await CreateProjectAsync(sources, additionalFiles, additionalMetadataReferences, analyzerReferences, Language, SourceText.From(editorConfig, Encoding.UTF8)); return project.Solution; } /// <summary> /// Create a project using the input strings as sources. /// </summary> /// <remarks> /// <para>This method first creates a <see cref="Project"/> by calling <see cref="CreateProjectImpl"/>, and then /// applies compilation options to the project by calling <see cref="ApplyCompilationOptions"/>.</para> /// </remarks> /// <param name="sources">Classes in the form of strings.</param> /// <param name="additionalFiles">Additional documents to include in the project.</param> /// <param name="additionalMetadataReferences">Additional metadata references to include in the project.</param> /// <param name="language">The language the source classes are in. Values may be taken from the /// <see cref="LanguageNames"/> class.</param> /// <param name="editorConfigText">The .editorconfig to apply to this project.</param> /// <returns>A <see cref="Project"/> created out of the <see cref="Document"/>s created from the source /// strings.</returns> protected async Task<Project> CreateProjectAsync((string filename, SourceText content)[] sources, (string filename, SourceText content)[] additionalFiles, MetadataReference[] additionalMetadataReferences, IEnumerable<AnalyzerReference> analyzerReferences, string language, SourceText editorConfigText) { language ??= Language; return await CreateProjectImplAsync(sources, additionalFiles, additionalMetadataReferences, analyzerReferences, language, editorConfigText); } /// <summary> /// Create a project using the input strings as sources. /// </summary> /// <param name="sources">Classes in the form of strings.</param> /// <param name="additionalFiles">Additional documents to include in the project.</param> /// <param name="additionalMetadataReferences">Additional metadata references to include in the project.</param> /// <param name="language">The language the source classes are in. Values may be taken from the /// <see cref="LanguageNames"/> class.</param> /// <param name="editorConfigText">The .editorconfig to apply to this project.</param> /// <returns>A <see cref="Project"/> created out of the <see cref="Document"/>s created from the source /// strings.</returns> protected virtual async Task<Project> CreateProjectImplAsync((string filename, SourceText content)[] sources, (string filename, SourceText content)[] additionalFiles, MetadataReference[] additionalMetadataReferences, IEnumerable<AnalyzerReference> analyzerReferences, string language, SourceText editorConfigText) { var projectId = ProjectId.CreateNewId(debugName: DefaultTestProjectName); var solution = (await CreateSolutionAsync(projectId, language, editorConfigText)) .AddAnalyzerReferences(projectId, analyzerReferences) .AddMetadataReferences(projectId, additionalMetadataReferences); for (var i = 0; i < sources.Length; i++) { (var newFileName, var source) = sources[i]; var documentId = DocumentId.CreateNewId(projectId, debugName: newFileName); solution = solution.AddDocument(documentId, newFileName, source, filePath: Path.Combine(DefaultFolderPath, newFileName)); } for (var i = 0; i < additionalFiles.Length; i++) { (var newFileName, var source) = additionalFiles[i]; var documentId = DocumentId.CreateNewId(projectId, debugName: newFileName); solution = solution.AddAdditionalDocument(documentId, newFileName, source); } return solution.GetProject(projectId)!; } /// <summary> /// Creates a solution that will be used as parent for the sources that need to be checked. /// </summary> /// <param name="projectId">The project identifier to use.</param> /// <param name="language">The language for which the solution is being created.</param> /// <param name="editorConfigText">The .editorconfig to apply to this solution.</param> /// <returns>The created solution.</returns> protected virtual async Task<Solution> CreateSolutionAsync(ProjectId projectId, string language, SourceText editorConfigText) { var xmlReferenceResolver = new TestXmlReferenceResolver(); foreach (var xmlReference in XmlReferences) { xmlReferenceResolver.XmlReferences.Add(xmlReference.Key, xmlReference.Value); } var compilationOptions = CreateCompilationOptions() .WithXmlReferenceResolver(xmlReferenceResolver) .WithAssemblyIdentityComparer(ReferenceAssemblies.AssemblyIdentityComparer); var parseOptions = CreateParseOptions(); var referenceAssemblies = await ReferenceAssemblies.ResolveAsync(language, CancellationToken.None); var editorConfigDocument = DocumentInfo.Create( DocumentId.CreateNewId(projectId, DefaultEditorConfigPath), name: DefaultEditorConfigPath, loader: TextLoader.From(TextAndVersion.Create(editorConfigText, VersionStamp.Create())), filePath: DefaultEditorConfigPath); var projectInfo = ProjectInfo.Create( projectId, VersionStamp.Create(), name: DefaultTestProjectName, assemblyName: DefaultTestProjectName, language, filePath: DefaultTestProjectPath, outputFilePath: Path.ChangeExtension(DefaultTestProjectPath, "dll"), compilationOptions: compilationOptions, parseOptions: parseOptions, metadataReferences: referenceAssemblies, isSubmission: false) .WithDefaultNamespace(DefaultTestProjectName) .WithAnalyzerConfigDocuments(ImmutableArray.Create(editorConfigDocument)); var solution = CreateWorkspace() .CurrentSolution .AddProject(projectInfo); if (language == LanguageNames.VisualBasic) { solution = solution.AddMetadataReference(projectId, MicrosoftVisualBasicReference); } return solution; } public virtual AdhocWorkspace CreateWorkspace() { var exportProvider = ExportProviderFactory.Value.CreateExportProvider(); var host = MefHostServices.Create(exportProvider.AsCompositionContext()); return new AdhocWorkspace(host); } protected abstract CompilationOptions CreateCompilationOptions(); protected abstract ParseOptions CreateParseOptions(); } }
52.701754
328
0.673546
[ "MIT" ]
dmonroym/format
tests/Formatters/AbstractFormatterTests.cs
18,026
C#
using System; using System.Collections.Generic; using UnityEditor.Graphing; using UnityEditor.ShaderGraph.Drawing.Slots; using UnityEditor.ShaderGraph.Internal; using UnityEngine; using UnityEngine.UIElements; namespace UnityEditor.ShaderGraph { [Serializable] class GradientInputMaterialSlot : GradientMaterialSlot, IMaterialSlotHasValue<Gradient> { [SerializeField] Gradient m_Value = new Gradient(); [SerializeField] Gradient m_DefaultValue = new Gradient(); public GradientInputMaterialSlot() { } public GradientInputMaterialSlot( int slotId, string displayName, string shaderOutputName, ShaderStageCapability stageCapability = ShaderStageCapability.All, bool hidden = false) : base(slotId, displayName, shaderOutputName, SlotType.Input, stageCapability, hidden) { } public Gradient value { get { return m_Value; } set { m_Value = value; } } public Gradient defaultValue { get { return m_DefaultValue; } } public override VisualElement InstantiateControl() { return new GradientSlotControlView(this); } public override string GetDefaultValue(GenerationMode generationMode) { var matOwner = owner as AbstractMaterialNode; if (matOwner == null) throw new Exception(string.Format("Slot {0} either has no owner, or the owner is not a {1}", this, typeof(AbstractMaterialNode))); if (generationMode.IsPreview()) return GradientUtil.GetGradientForPreview(matOwner.GetVariableNameForSlot(id)); return ConcreteSlotValueAsVariable(); } protected override string ConcreteSlotValueAsVariable() { return GradientUtil.GetGradientValue(value, ""); } public override void AddDefaultProperty(PropertyCollector properties, GenerationMode generationMode) { var matOwner = owner as AbstractMaterialNode; if (matOwner == null) throw new Exception(string.Format("Slot {0} either has no owner, or the owner is not a {1}", this, typeof(AbstractMaterialNode))); if (generationMode != GenerationMode.Preview) return; GradientUtil.GetGradientPropertiesForPreview(properties, matOwner.GetVariableNameForSlot(id), value); } public override void GetPreviewProperties(List<PreviewProperty> properties, string name) { properties.Add(new PreviewProperty(PropertyType.Gradient) { name = name, gradientValue = value }); } public override void CopyValuesFrom(MaterialSlot foundSlot) { var slot = foundSlot as GradientInputMaterialSlot; if (slot != null) value = slot.value; } } }
32.180851
146
0.62876
[ "MIT" ]
Agameofscones/2d_slipsworth_sim
2d_Slipsworth_Sim/Library/PackageCache/com.unity.shadergraph@7.3.1/Editor/Data/Graphs/GradientInputMaterialSlot.cs
3,025
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.DomainRegistration.Outputs { /// <summary> /// Identifies an object. /// </summary> [OutputType] public sealed class NameIdentifierResponse { /// <summary> /// Name of the object. /// </summary> public readonly string? Name; [OutputConstructor] private NameIdentifierResponse(string? name) { Name = name; } } }
24.032258
81
0.636242
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/DomainRegistration/Outputs/NameIdentifierResponse.cs
745
C#
namespace Capture.Workflow.Core.Classes { public enum VariableTypeEnum { String, Number, Date, Boolean } }
13.818182
40
0.552632
[ "MIT" ]
BresciMa/digiCamControl
Capture.Workflow.Core/Classes/VariableTypeEnum.cs
154
C#
// Copyright 2021 Máté Szabó // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Reflection.Emit; using HarmonyLib; using RimWorld; using RWP.Service; using Verse; namespace RWP.Patches { [HarmonyPatch(typeof(ForbidUtility), nameof(ForbidUtility.InAllowedArea))] public static class ForbidUtility_InAllowedArea_Patch { public static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions) { var instructionsList = instructions.ToList(); FieldInfo playerSettingsField = AccessTools.Field(typeof(Pawn), nameof(Pawn.playerSettings)); MethodInfo rootProperty = AccessTools.DeclaredPropertyGetter(typeof(RWPMod), nameof(RWPMod.Root)); MethodInfo serviceProperty = AccessTools.DeclaredPropertyGetter( typeof(RWPRoot), nameof(RWPRoot.EffectiveAreaRestrictionService)); MethodInfo getEffectiveAreaRestrictionMethod = AccessTools.Method( typeof(EffectiveAreaRestrictionService), nameof(EffectiveAreaRestrictionService.GetEffectiveAreaRestriction)); for (int i = 0; i < instructionsList.Count; i++) { if (instructionsList[i].IsLdarg(1) && instructionsList[i + 1].LoadsField(playerSettingsField)) { yield return new CodeInstruction(OpCodes.Call, rootProperty); yield return new CodeInstruction(OpCodes.Call, serviceProperty); yield return instructionsList[i]; yield return new CodeInstruction(OpCodes.Callvirt, getEffectiveAreaRestrictionMethod); i += 5; } else { yield return instructionsList[i]; } } } } }
40.04918
110
0.664756
[ "Apache-2.0" ]
mszabo-wikia/RimWorld-RWP
Source/Patches/ForbidUtility_InAllowedArea_Patch.cs
2,448
C#
/******************************************************************************** * Module : Lapis.Math.Numbers.BigNumbers  * Class : BigInteger  * Description : Represents an arbitrarily large interger.  * Created : 2015/6/25  * Note : *********************************************************************************/ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Lapis.Math.Numbers.BigNumbers { public partial class BigInteger { /// <summary> /// Converts an <see cref="Int32"/> value to a <see cref="BigInteger"/> object. /// </summary> /// <param name="value">The value to be wrapped.</param> /// <returns>A <see cref="BigInteger"/> object that wraps <paramref name="value"/>.</returns> public static BigInteger FromInt32(int value) { var sign = value.CompareTo(0); if (sign == 0) return Zero; var n = value > 0 ? value : -value; var digit0 = n % BaseInt; var digit1 = n / BaseInt; int[] data; if (digit1 == 0) data = new int[1] { digit0 }; else data = new int[2] { digit0, digit1 }; return new BigInteger(sign, data); } /// <summary> /// Converts an <see cref="UInt32"/> value to a <see cref="BigInteger"/> object. /// </summary> /// <param name="value">The value to be wrapped.</param> /// <returns>A <see cref="BigInteger"/> object that wraps <paramref name="value"/>.</returns> [CLSCompliant(false)] public static BigInteger FromUInt32(uint value) { var sign = value.CompareTo(0); if (sign == 0) return Zero; var n = value; var digit0 = n % BaseInt; var digit1 = n / BaseInt; int[] data; if (digit1 == 0) data = new int[1] { (int)digit0 }; else data = new int[2] { (int)digit0, (int)digit1 }; return new BigInteger(sign, data); } /// <summary> /// Converts an <see cref="Int64"/> value to a <see cref="BigInteger"/> object. /// </summary> /// <param name="value">The value to be wrapped.</param> /// <returns>A <see cref="BigInteger"/> object that wraps <paramref name="value"/>.</returns> public static BigInteger FromInt64(long value) { var sign = value.CompareTo(0); if (sign == 0) return Zero; var n = value > 0 ? value : -value; var digit0 = n % BaseInt; n = n / BaseInt; var digit1 = n % BaseInt; n = n / BaseInt; var digit2 = n % BaseInt; var digit3 = n / BaseInt; int[] data; if (digit3 != 0) data = new int[4] { (int)digit0, (int)digit1, (int)digit2, (int)digit3 }; else if (digit2 != 0) data = new int[3] { (int)digit0, (int)digit1, (int)digit2 }; else if (digit1 != 0) data = new int[2] { (int)digit0, (int)digit1 }; else data = new int[1] { (int)digit0 }; return new BigInteger(sign, data); } /// <summary> /// Converts an <see cref="UInt64"/> value to a <see cref="BigInteger"/> object. /// </summary> /// <param name="value">The value to be wrapped.</param> /// <returns>A <see cref="BigInteger"/> object that wraps <paramref name="value"/>.</returns> [CLSCompliant(false)] public static BigInteger FromUInt64(ulong value) { var sign = value.CompareTo(0); if (sign == 0) return Zero; var n = value; var digit0 = n % BaseInt; n = n / BaseInt; var digit1 = n % BaseInt; n = n / BaseInt; var digit2 = n % BaseInt; var digit3 = n / BaseInt; int[] data; if (digit3 != 0) data = new int[4] { (int)digit0, (int)digit1, (int)digit2, (int)digit3 }; else if (digit2 != 0) data = new int[3] { (int)digit0, (int)digit1, (int)digit2 }; else if (digit1 != 0) data = new int[2] { (int)digit0, (int)digit1 }; else data = new int[1] { (int)digit0 }; return new BigInteger(sign, data); } /// <summary> /// Returns the string representation of the <see cref="BigInteger"/> object. /// </summary> /// <returns>The string representation of the <see cref="BigInteger"/> object.</returns> public override string ToString() { if (Sign == 0) return "0"; var sb = new StringBuilder(); for (long i = 0; i < Length - 1; i++) sb.Insert(0, _data[i].ToString("D9")); sb.Insert(0, _data[Length - 1].ToString()); if (Sign < 0) sb.Insert(0, "-"); return sb.ToString(); } /// <summary> /// Converts the string representation of a number to its <see cref="BigInteger"/> equivalent. /// </summary> /// <param name="value">A string that contains the number to convert.</param> /// <returns>A <see cref="BigInteger"/> object that is equivalent to the number specified in the <paramref name="value"/> parameter. </returns> /// <exception cref="ArgumentNullException"><paramref name="value"/> is <see langword="null"/>.</exception> /// <exception cref="FormatException"><paramref name="value"/> is not in the correct format.</exception> public static BigInteger FromString(string value) { if (value == null) throw new ArgumentNullException(); if (string.IsNullOrWhiteSpace(value)) goto fail; value = value.Trim(); int sign, start; if (value[0] == '-') { sign = -1; start = 1; } else { sign = 1; start = 0; } int[] data = new int[value.Length / 9 + 1]; var sb = new StringBuilder(); char c; int count = 0; for (int i = value.Length - 1; i >= start; i--) { c = value[i]; if (char.IsDigit(c)) sb.Insert(0, c.ToString()); else goto fail; if (sb.Length == 9) { data[count] = int.Parse(sb.ToString()); sb.Clear(); count++; } } if (sb.Length > 0) { data[count] = int.Parse(sb.ToString()); sb.Clear(); } return new BigInteger(sign, data); fail: throw new FormatException(ExceptionResource.IncorrectStringFormat); } } }
38.222798
151
0.461841
[ "MIT" ]
LapisDev/LapisMath
src/Lapis.Math.Numbers/BigNumbers/BigInteger.Conversion.cs
7,383
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the workspaces-2015-04-08.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.WorkSpaces.Model { /// <summary> /// The configuration of this WorkSpace is not supported for this operation. For more /// information, see <a href="https://docs.aws.amazon.com/workspaces/latest/adminguide/required-service-components.html">Required /// Configuration and Service Components for WorkSpaces </a>. /// </summary> #if !PCL && !NETSTANDARD [Serializable] #endif public partial class UnsupportedWorkspaceConfigurationException : AmazonWorkSpacesException { /// <summary> /// Constructs a new UnsupportedWorkspaceConfigurationException with the specified error /// message. /// </summary> /// <param name="message"> /// Describes the error encountered. /// </param> public UnsupportedWorkspaceConfigurationException(string message) : base(message) {} /// <summary> /// Construct instance of UnsupportedWorkspaceConfigurationException /// </summary> /// <param name="message"></param> /// <param name="innerException"></param> public UnsupportedWorkspaceConfigurationException(string message, Exception innerException) : base(message, innerException) {} /// <summary> /// Construct instance of UnsupportedWorkspaceConfigurationException /// </summary> /// <param name="innerException"></param> public UnsupportedWorkspaceConfigurationException(Exception innerException) : base(innerException) {} /// <summary> /// Construct instance of UnsupportedWorkspaceConfigurationException /// </summary> /// <param name="message"></param> /// <param name="innerException"></param> /// <param name="errorType"></param> /// <param name="errorCode"></param> /// <param name="requestId"></param> /// <param name="statusCode"></param> public UnsupportedWorkspaceConfigurationException(string message, Exception innerException, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode) : base(message, innerException, errorType, errorCode, requestId, statusCode) {} /// <summary> /// Construct instance of UnsupportedWorkspaceConfigurationException /// </summary> /// <param name="message"></param> /// <param name="errorType"></param> /// <param name="errorCode"></param> /// <param name="requestId"></param> /// <param name="statusCode"></param> public UnsupportedWorkspaceConfigurationException(string message, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode) : base(message, errorType, errorCode, requestId, statusCode) {} #if !PCL && !NETSTANDARD /// <summary> /// Constructs a new instance of the UnsupportedWorkspaceConfigurationException class with serialized data. /// </summary> /// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param> /// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is null. </exception> /// <exception cref="T:System.Runtime.Serialization.SerializationException">The class name is null or <see cref="P:System.Exception.HResult" /> is zero (0). </exception> protected UnsupportedWorkspaceConfigurationException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { } /// <summary> /// Sets the <see cref="T:System.Runtime.Serialization.SerializationInfo" /> with information about the exception. /// </summary> /// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param> /// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is a null reference (Nothing in Visual Basic). </exception> #if BCL35 [System.Security.Permissions.SecurityPermission( System.Security.Permissions.SecurityAction.LinkDemand, Flags = System.Security.Permissions.SecurityPermissionFlag.SerializationFormatter)] #endif [System.Security.SecurityCritical] // These FxCop rules are giving false-positives for this method [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2134:MethodsMustOverrideWithConsistentTransparencyFxCopRule")] public override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { base.GetObjectData(info, context); } #endif } }
50.190476
184
0.694339
[ "Apache-2.0" ]
JeffAshton/aws-sdk-net
sdk/src/Services/WorkSpaces/Generated/Model/UnsupportedWorkspaceConfigurationException.cs
6,324
C#
using System; using System.Threading; namespace LevelDB { class Program { static string testPath = @"C:\Temp\Test"; static string CleanTestDB() { DB.Destroy(new Options { CreateIfMissing = true }, testPath); return testPath; } static void Main3() { var path = CleanTestDB(); using (var db = new DB(new Options {CreateIfMissing = true}, path)) { db.Put(1, new[] {2, 3}, new WriteOptions()); db.Put(2, new[] {1, 2, 4}); db.Put(3, new[] {1, 3}); db.Put(4, new[] {2, 5, 7}); db.Put(5, new[] {4, 6, 7, 8}); db.Put(6, new[] {5}); db.Put(7, new[] {4, 5, 8}); db.Put(8, new[] {5, 7}); var a = db.Get(1); var b = db.Get(2); var c = db.Get(3); var d = db.Get(4); var e = db.Get(5); var f = db.Get(6); var g = db.Get(7); var h = db.Get(8); } } static void Main() { var l = new Logger(s => Console.WriteLine(s)); var x = new Options { CreateIfMissing = true, RestartInterval = 13, MaxOpenFiles = 100, InfoLog = l }; var db = new DB(x, @"C:\Temp\A"); db.Put("hello", "world"); var world = db.Get("hello"); Console.WriteLine(world); for (var j = 0; j < 5; j++) { var r = new Random(0); var data = ""; for (int i = 0; i < 1024; i++) { data += 'a' + r.Next(26); } for (int i = 0; i < 5*1024; i++) { db.Put(string.Format("row{0}", i), data); } Thread.Sleep(100); } Console.WriteLine(); //using(var logger = new Logger(Console.WriteLine)) //{ // Console.WriteLine("hello"); //} db.Dispose(); GC.KeepAlive(l); } } }
27.623529
79
0.356899
[ "Apache-2.0" ]
Reactive-Extensions/LevelDB
LevelDB.net/Program.cs
2,350
C#
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- using Microsoft.Azure.Commands.Sql.Common; using Microsoft.Azure.Commands.Sql.DataMasking.Model; using System.Management.Automation; namespace Microsoft.Azure.Commands.Sql.DataMasking.Cmdlet { /// <summary> /// Sets the data masking policy properties for a specific database. /// </summary> [Cmdlet("Set", ResourceManager.Common.AzureRMConstants.AzureRMPrefix + "SqlDatabaseDataMaskingPolicy", SupportsShouldProcess = true), OutputType(typeof(DatabaseDataMaskingPolicyModel))] public class SetAzureSqlDatabaseDataMaskingPolicy : SqlDatabaseDataMaskingPolicyCmdletBase { /// <summary> /// Defines whether the cmdlets will output the model object at the end of its execution /// </summary> [Parameter(Mandatory = false)] public SwitchParameter PassThru { get; set; } /// <summary> /// Gets or sets the privileged login names /// </summary> [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "A semicolon separated list of privileged user ids login name")] public string PrivilegedLogins { get; set; } /// <summary> /// Gets or sets the privileged users names /// </summary> [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "A semicolon separated list of privileged user ids login name")] public string PrivilegedUsers { get; set; } /// <summary> /// Gets or sets the name of the data masking state /// </summary> [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "Defines if data masking is enabled or disabled for this database")] [ValidateSet(SecurityConstants.Enabled, SecurityConstants.Disabled, IgnoreCase = false)] [ValidateNotNullOrEmpty] public string DataMaskingState { get; set; } /// <summary> /// Returns true if the model object that was constructed by this cmdlet should be written out /// </summary> /// <returns>True if the model object should be written out, False otherwise</returns> protected override bool WriteResult() { return PassThru; } /// <summary> /// Updates the given model element with the cmdlet specific operation /// </summary> /// <param name="model">A model object</param> protected override DatabaseDataMaskingPolicyModel ApplyUserInputToModel(DatabaseDataMaskingPolicyModel model) { base.ApplyUserInputToModel(model); if (PrivilegedLogins != null) // empty string here means that the user clears the logins list { WriteWarning("The parameter PrivilegedLogins is being deprecated and will be removed in a future release. Use the PrivilegedUsers parameter to provide SQL users excluded from masking."); model.PrivilegedUsers = PrivilegedLogins; } if (PrivilegedUsers != null) // empty string here means that the user clears the users list { model.PrivilegedUsers = PrivilegedUsers; } if (!string.IsNullOrEmpty(DataMaskingState)) { model.DataMaskingState = (DataMaskingState == SecurityConstants.Enabled) ? DataMaskingStateType.Enabled : DataMaskingStateType.Disabled; } return model; } } }
49.149425
203
0.640084
[ "MIT" ]
Andrean/azure-powershell
src/ResourceManager/Sql/Commands.Sql/Data Masking/Cmdlet/SetAzureSqlDatabaseDataMaskingPolicy.cs
4,192
C#