private void AnalyzeMethodInvocation(OperationAnalysisContext context, ContractResolver resolver) { var invocation = (IInvocationOperation)context.Operation; // We do care only about the following methods (and not about AssertNotNull, Invariants and Ensures) var contractMethods = ContractMethodNames.Assume | ContractMethodNames.AllAsserts | ContractMethodNames.AllRequires; // Looking for contract methods based on 'RuntimeContracts' package. if (resolver.IsContractInvocation(invocation.TargetMethod, contractMethods) && invocation.Arguments.Length > 2) { // Checking that the message is not provided. if (invocation.Arguments[1].IsImplicit) { context.ReportDiagnostic(Diagnostic.Create(Rule, invocation.Syntax.GetLocation())); } } else if (resolver.IsFluentContractInvocation(invocation.TargetMethod) && invocation.Parent is IConditionalAccessOperation conditionalAccess && conditionalAccess.WhenNotNull is IInvocationOperation checkInvocation && checkInvocation.Arguments.Length > 0) { // First argument for IsTrue is a struct. And the second one is the message if (checkInvocation.Arguments[1].IsImplicit) { context.ReportDiagnostic(Diagnostic.Create(Rule, invocation.Parent.Syntax.GetLocation())); } } }
private static async Task <Document> UseFluentContractsOrRemovePostconditionsAsync( Document document, List <InvocationExpressionSyntax> invocationExpressions, CancellationToken cancellationToken) { var semanticModel = await document.GetSemanticModelAsync(cancellationToken); var root = await document.GetSyntaxRootAsync(cancellationToken); var nodeTranslationMap = new Dictionary <SyntaxNode, SyntaxNode>(); foreach (var invocationExpression in invocationExpressions) { var operation = (IInvocationOperation)semanticModel.GetOperation(invocationExpression); var contractResolver = new ContractResolver(semanticModel.Compilation); if (contractResolver.GetContractInvocation(operation.TargetMethod, out var contractMethod)) { var(source, replacement) = GetFluentContractsReplacements(operation, contractMethod, semanticModel, cancellationToken); nodeTranslationMap[source] = replacement; } } root = root.ReplaceNodes(nodeTranslationMap.Keys, (source, temp) => nodeTranslationMap[source]); return(document.WithSyntaxRoot(root)); }
private static void AnalyzeSyntax(SyntaxNodeAnalysisContext context) { var invocation = (InvocationExpressionSyntax)context.Node; var resolver = new ContractResolver(context.SemanticModel); if (resolver.IsContractInvocation(invocation) && invocation.ArgumentList.Arguments.Count == 2) { var firstArgument = invocation.ArgumentList.Arguments[0]; if (firstArgument.Expression is LiteralExpressionSyntax les && les.Kind() == SyntaxKind.FalseLiteralExpression) { // This is Assert(false, ....). The second argument may be in any form in this case. return; } var messageExpression = invocation.ArgumentList.Arguments[1]; if (messageExpression.Expression is InterpolatedStringExpressionSyntax ise && ise.DescendantNodes().Any(n => n.Kind() == SyntaxKind.IdentifierName)) { // Found interpolated string with expressions inside context.ReportDiagnostic(Diagnostic.Create(Rule, invocation.GetLocation())); return; } if (messageExpression.Expression is BinaryExpressionSyntax bes && bes.OperatorToken.Kind() == SyntaxKind.PlusToken && (bes.Left is LiteralExpressionSyntax || bes.Right is LiteralExpressionSyntax) && bes.DescendantNodes().Any(n => n.Kind() == SyntaxKind.IdentifierName)) { // Found "literal" + expression context.ReportDiagnostic(Diagnostic.Create(Rule, invocation.GetLocation())); return; } } }
protected override OpenApiSchema GenerateSchemaFor(Type type, SchemaRepository schemaRepository) { var jsonDictionaryContract = (JsonDictionaryContract)ContractResolver.ResolveContract(type); var keyType = jsonDictionaryContract.DictionaryKeyType ?? typeof(object); var valueType = jsonDictionaryContract.DictionaryValueType ?? typeof(object); if (keyType.IsEnum) { // This is a special case where we can include named properties based on the enum values return(new OpenApiSchema { Type = "object", Properties = jsonDictionaryContract.DictionaryKeyType.GetEnumNames() .ToDictionary( name => name, name => RootGenerator.GenerateSchema(valueType, schemaRepository) ) }); } return(new OpenApiSchema { Type = "object", AdditionalPropertiesAllowed = true, AdditionalProperties = RootGenerator.GenerateSchema(valueType, schemaRepository) }); }
public Handler(IJobScheduler jobScheduler, IDialogService dialogService, IAppContext context, ILogger logger, ContractResolver resolver) { _logger = logger; _context = context; _resolver = resolver; _jobScheduler = jobScheduler; _dialogService = dialogService; }
/// <summary> /// Returns a value indicating whether or not the given type can be written by this serializer. /// </summary> /// <param name="type">The object type.</param> /// <returns><c>true</c> if the type can be written, otherwise <c>false</c>.</returns> protected override bool CanWriteType(Type type) { if (type == null) { throw new ArgumentNullException(nameof(type)); } return(ContractResolver.CanResolve(TypeHelper.GetUnderlyingType(type))); }
protected override bool CanGenerateSchemaFor(Type type) { var jsonContract = ContractResolver.ResolveContract(type); return((type.IsEnum && Options.UseReferencedDefinitionsForEnums) || // enum (jsonContract is JsonObjectContract) || // regular object (jsonContract is JsonArrayContract && ((JsonArrayContract)jsonContract).CollectionItemType == jsonContract.UnderlyingType) || // self-referencing array (jsonContract is JsonDictionaryContract && ((JsonDictionaryContract)jsonContract).DictionaryValueType == jsonContract.UnderlyingType)); // self-referencing dictionary }
protected override OpenApiSchema GenerateSchemaFor(Type type, SchemaRepository schemaRepository) { var jsonPrimitiveContract = (JsonPrimitiveContract)ContractResolver.ResolveContract(type); var schema = jsonPrimitiveContract.UnderlyingType.IsEnum ? GenerateEnumSchema(jsonPrimitiveContract) : FactoryMethodMap[jsonPrimitiveContract.UnderlyingType](); return(schema); }
public T Deserialize <T>(byte[] obj) { var resolver = new ContractResolver(); var settings = new JsonSerializerSettings { ContractResolver = resolver }; var s = enc.GetString(obj); return(JsonConvert.DeserializeObject <T>(s, settings)); }
private static void AnalyzeInvocation(OperationAnalysisContext context, ContractResolver resolver) { var invocation = (IInvocationOperation)context.Operation; if (resolver.IsStandardContractInvocation(invocation.TargetMethod)) { var diagnostic = Diagnostic.Create(Rule, invocation.Syntax.GetLocation()); context.ReportDiagnostic(diagnostic); } }
public void Resolve() { ContractResolver resolver = new ContractResolver(ContractResolverType.OptOut); string json = JsonConvert.SerializeObject(mockup, new JsonSerializerSettings() { ContractResolver = resolver }); Assert.Equal("{\"Name\":\"Test Object\",\"Number\":42,\"TrueFalse\":true}", json); }
public void OptIn() { ContractResolver resolver = new ContractResolver(ContractResolverType.OptIn, "Name"); string json = JsonConvert.SerializeObject(mockup, new JsonSerializerSettings() { ContractResolver = resolver }); Assert.Equal("{\"Name\":\"Test Object\"}", json); }
protected override OpenApiSchema GenerateSchemaFor(Type type, SchemaRepository schemaRepository) { var jsonArrayContract = (JsonArrayContract)ContractResolver.ResolveContract(type); return(new OpenApiSchema { Type = "array", Items = RootGenerator.GenerateSchema(jsonArrayContract.CollectionItemType, schemaRepository), UniqueItems = jsonArrayContract.UnderlyingType.IsSet() ? (bool?)true : null }); }
protected virtual ProxyBuilderEntry ImplementProxy(Type stubType) { if (stubType.GetTypeInfo().IsSealed) { throw new ArgumentException("Cannot implement transparent proxy on a sealed type.", nameof(stubType)); } var contract = ContractResolver.CreateClientContract(new[] { stubType }); var builder = ModuleBuilder.DefineType(NextProxyTypeName(), TypeAttributes.Class | TypeAttributes.Sealed, stubType.GetTypeInfo().IsInterface ? typeof(object) : stubType, stubType.GetTypeInfo().IsInterface ? new[] { stubType } : emptyTypes); var realProxy = builder.DefineField("$_RealProxy", typeof(JsonRpcRealProxy), FieldAttributes.Private | FieldAttributes.InitOnly); { var ctor = builder.DefineConstructor(MethodAttributes.Public, CallingConventions.HasThis, new[] { typeof(JsonRpcRealProxy) }); var gen = ctor.GetILGenerator(); gen.Emit(OpCodes.Ldarg_0); // this gen.Emit(OpCodes.Ldarg_1); // realproxy gen.Emit(OpCodes.Stfld, realProxy); gen.Emit(OpCodes.Ret); } int memberCounter = 0; // Used to generate method names. var methodTable = new List <JsonRpcMethod>(); foreach (var member in stubType.GetRuntimeMethods().Where(m => m.IsAbstract)) { var implName = "$_Impl_" + memberCounter + member.Name; if (member is MethodInfo method) { memberCounter++; var impl = builder.DefineMethod(implName, MethodAttributes.Private | MethodAttributes.Final | MethodAttributes.Virtual | MethodAttributes.NewSlot | MethodAttributes.HideBySig, method.ReturnType, method.GetParameters().Select(pa => pa.ParameterType).ToArray()); builder.DefineMethodOverride(impl, method); if (contract.Methods.TryGetValue(method, out var rpcMethod)) { ImplementProxyMethod(method, rpcMethod, methodTable.Count, impl, realProxy); methodTable.Add(rpcMethod); } else { var gen = impl.GetILGenerator(); gen.Emit(OpCodes.Ldstr, $"\"{method.Name}\" is not implemented by JSON RPC proxy builder."); gen.Emit(OpCodes.Newobj, NotImplementedException_ctor1); gen.Emit(OpCodes.Throw); } } } return(new ProxyBuilderEntry(builder.CreateTypeInfo().AsType(), methodTable)); }
public override void Initialize(AnalysisContext context) { context.EnableConcurrentExecution(); context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics); context.RegisterCompilationStartAction(context => { var resolver = new ContractResolver(context.Compilation); context.RegisterOperationAction(context => AnalyzeMethodInvocation(context, resolver), OperationKind.Invocation); }); }
public void Constructor() { ContractResolver resolver; resolver = new ContractResolver(); Assert.IsType <ContractResolver>(resolver); resolver = new ContractResolver(); Assert.IsType <ContractResolver>(resolver); resolver = new ContractResolver(ContractResolverType.OptIn); Assert.IsType <ContractResolver>(resolver); }
private void AnalyzeMethodInvocation(OperationAnalysisContext context, ContractResolver resolver) { var invocation = (IInvocationOperation)context.Operation; // We do care only about the following methods (and not about AssertNotNull, Invariants and Ensures) var contractMethods = ContractMethodNames.AssertNotNull | ContractMethodNames.RequiresNotNull; // Looking for contract methods based on 'RuntimeContracts' package. if (resolver.IsContractInvocation(invocation.TargetMethod, contractMethods)) { context.ReportDiagnostic(Diagnostic.Create(Rule, invocation.Syntax.GetLocation())); } }
private string GetPropertyNameFromMemberExpression(MemberExpression memberExpression) { var jsonObjectContract = ContractResolver.ResolveContract(memberExpression.Expression.Type) as JsonObjectContract; if (jsonObjectContract != null) { return(jsonObjectContract.Properties .First(jsonProperty => jsonProperty.UnderlyingName == memberExpression.Member.Name) .PropertyName); } return(null); }
private static void AnalyzeSyntax(SyntaxNodeAnalysisContext context) { var invocation = (InvocationExpressionSyntax)context.Node; var resolver = new ContractResolver(context.SemanticModel); if (resolver.IsStandardContractInvocation(invocation)) { var diagnostic = Diagnostic.Create(Rule, invocation.GetLocation()); context.ReportDiagnostic(diagnostic); } }
protected override OpenApiSchema GenerateSchemaFor(Type type, SchemaRepository schemaRepository) { var jsonArrayContract = (JsonArrayContract)ContractResolver.ResolveContract(type); //var properties = new Dictionary<string, OpenApiSchema>(); //ObjectSchemaGenerator.AddTypeAttribute(_serializerSettings, type, properties); return(new OpenApiSchema { Type = "array", Items = RootGenerator.GenerateSchema(jsonArrayContract.CollectionItemType, schemaRepository), UniqueItems = jsonArrayContract.UnderlyingType.IsSet() ? (bool?)true : null, }); }
/// <summary> /// Serialize the value into an JSON AST. /// </summary> /// <param name="type">The type to serialize from.</param> /// <param name="value">The value to serialize.</param> /// <param name="fieldNamingStrategy">The field naming strategy when serializing and deserializing the JSON.</param> /// <returns>The JSON object that represents the serialized value.</returns> protected override JsonValue SerializeValue(Type type, object value, IFieldNamingStrategy fieldNamingStrategy) { if (ContractResolver.CanResolve(TypeHelper.GetUnderlyingType(type))) { return(SerializeContract(type, value, fieldNamingStrategy)); } if (TypeHelper.GetUnderlyingType(type) == typeof(JsonApiError)) { return(SerializeJsonApiError(type, value)); } throw new HypermediaException("Not supported."); }
/// <summary> /// Serialize the value into an JSON AST. /// </summary> /// <param name="type">The type to serialize from.</param> /// <param name="value">The value to serialize.</param> /// <returns>The JSON object that represents the serialized value.</returns> protected override JsonValue SerializeValue(Type type, object value) { if (ContractResolver.CanResolve(TypeHelper.GetUnderlyingType(type))) { return(SerializeContract(type, value)); } if (TypeHelper.GetUnderlyingType(type) == typeof(JsonApiError)) { return(SerializeJsonApiError(type, value)); } return(SerializeHttpError((HttpError)value)); }
/// <summary> /// Determines whether this <see cref="T:Microsoft.AspNetCore.Mvc.Formatters.InputFormatter" /> can deserialize an object of the given /// <paramref name="type" />. /// </summary> /// <param name="type">The <see cref="T:System.Type" /> of object that will be read.</param> /// <returns><c>true</c> if the <paramref name="type" /> can be read, otherwise <c>false</c>.</returns> protected override bool CanReadType(Type type) { if (type == null) { throw new ArgumentNullException(nameof(type)); } if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(IPatch <>)) { return(ContractResolver.CanResolve(type.GetGenericArguments()[0])); } return(base.CanReadType(type)); }
protected override OpenApiSchema GenerateSchemaFor(Type type, SchemaRepository schemaRepository) { var jsonObjectContract = (JsonObjectContract)ContractResolver.ResolveContract(type); var properties = new Dictionary <string, OpenApiSchema>(); AddTypeAttribute(_serializerSettings, type, properties); var requiredPropertyNames = new List <string>(); foreach (var jsonProperty in jsonObjectContract.Properties) { if (jsonProperty.Ignored) { continue; } var attributes = jsonProperty.TryGetMemberInfo(out MemberInfo memberInfo) ? memberInfo.GetCustomAttributes(true) : new object[] { }; if (Options.IgnoreObsoleteProperties && attributes.OfType <ObsoleteAttribute>().Any()) { continue; } properties.Add(jsonProperty.PropertyName, GeneratePropertySchema(jsonProperty, memberInfo, attributes, schemaRepository)); if (jsonProperty.Required == Required.AllowNull || jsonProperty.Required == Required.Always || attributes.OfType <RequiredAttribute>().Any()) { requiredPropertyNames.Add(jsonProperty.PropertyName); } } var additionalProperties = (jsonObjectContract.ExtensionDataValueType != null) ? RootGenerator.GenerateSchema(jsonObjectContract.ExtensionDataValueType, schemaRepository) : null; var schema = new OpenApiSchema { Type = "object", Properties = properties, Required = new SortedSet <string>(requiredPropertyNames), AdditionalPropertiesAllowed = (additionalProperties != null), AdditionalProperties = additionalProperties }; return(schema); }
private JsonPatchProperty FindPropertyAndParent( object targetObject, string propertyPath) { try { var splitPath = propertyPath.Split('/'); // skip the first one if it's empty var startIndex = (string.IsNullOrWhiteSpace(splitPath[0]) ? 1 : 0); for (int i = startIndex; i < splitPath.Length; i++) { var jsonContract = (JsonObjectContract)ContractResolver.ResolveContract(targetObject.GetType()); foreach (var property in jsonContract.Properties) { if (string.Equals(property.PropertyName, splitPath[i], StringComparison.OrdinalIgnoreCase)) { if (i == (splitPath.Length - 1)) { return(new JsonPatchProperty(property, targetObject)); } else { targetObject = property.ValueProvider.GetValue(targetObject); // if property is of IList type then get the array index from splitPath and get the // object at the indexed position from the list. if (GetIListType(property.PropertyType) != null) { var index = int.Parse(splitPath[++i]); targetObject = ((IList)targetObject)[index]; } } break; } } } return(null); } catch (Exception) { // will result in JsonPatchException in calling class, as expected return(null); } }
public T Deserialize <T>(byte[] obj) { try { var resolver = new ContractResolver(); var settings = new JsonSerializerSettings { ContractResolver = resolver }; var s = enc.GetString(obj); return(JsonConvert.DeserializeObject <T>(s, settings)); } catch (Exception e) { LogManager.GetLogger("ASC").Error("Redis Deserialize<T>", e); throw; } }
private void AnalyzeOperation(OperationAnalysisContext context, ContractResolver resolver) { var invocation = (IInvocationOperation)context.Operation; var contracts = AllAsserts | AllRequires | Assume | Ensures | EnsuresOnThrow; // Excluding ForAll and postconditions. contracts &= ~(RequiresForAll | Postconditions); if (resolver.IsContractInvocation(invocation.TargetMethod, contracts)) { if (AssertionMessageConstructedProgrammatically(invocation)) { var diagnostic = Diagnostic.Create(Rule, invocation.Syntax.GetLocation()); context.ReportDiagnostic(diagnostic); } } }
private void ApplyFilters(OpenApiSchema schema, Type type, SchemaRepository schemaRepository) { if (schema.Reference != null) { return; } var filterContext = new SchemaFilterContext( type, ContractResolver.ResolveContract(type), schemaRepository, RootGenerator); foreach (var filter in Options.SchemaFilters) { filter.Apply(schema, filterContext); } }
protected override OpenApiSchema GenerateSchemaFor(Type type, SchemaRepository schemaRepository) { var jsonPrimitiveContract = (JsonPrimitiveContract)ContractResolver.ResolveContract(type); if (jsonPrimitiveContract.UnderlyingType.IsEnum) { return(GenerateEnumSchema(jsonPrimitiveContract)); } if (FactoryMethodMap.ContainsKey(jsonPrimitiveContract.UnderlyingType)) { return(FactoryMethodMap[jsonPrimitiveContract.UnderlyingType]()); } return(new OpenApiSchema { Type = "string" }); }
public Handler( ContractResolver contractResolver, IMediator mediator, IAppSettings appSettings, IAppContext appContext, ILogger logger, ITelemetry telemetry, IJobScheduler jobScheduler, INamedPipeServer namedPipeServer) { _logger = logger; _mediator = mediator; _telemetry = telemetry; _appContext = appContext; _appSettings = appSettings; _jobScheduler = jobScheduler; _namedPipeServer = namedPipeServer; _contractResolver = contractResolver; }
public void Resolve_Ok(string contractName) { ContractResolver resolver = new ContractResolver(); Assert.NotNull(resolver.Resolve(new[] {typeof (Contract)}, contractName)); }