Skip to content

Commit

Permalink
Merge pull request #25 from nogic1008/feature/NullableAnnotations
Browse files Browse the repository at this point in the history
Enable Nullable Reference Type(annotations)
  • Loading branch information
neuecc authored Nov 8, 2019
2 parents 3f864cd + 040d11e commit 55c982f
Show file tree
Hide file tree
Showing 16 changed files with 101 additions and 79 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ namespace MicroBatchFramework // .WebHosting
{
public static class BatchEngineHostingExtensions
{
public static IWebHostBuilder PrepareBatchEngineMiddleware(this IWebHostBuilder builder, IBatchInterceptor interceptor = null)
public static IWebHostBuilder PrepareBatchEngineMiddleware(this IWebHostBuilder builder, IBatchInterceptor? interceptor = null)
{
var batchTypes = CollectBatchTypes();
var target = new TargetBatchTypeCollection(batchTypes);
Expand All @@ -31,7 +31,7 @@ public static IWebHostBuilder PrepareBatchEngineMiddleware(this IWebHostBuilder
});
}

public static Task RunBatchEngineWebHosting(this IWebHostBuilder builder, string urls, SwaggerOptions swaggerOptions = null, IBatchInterceptor interceptor = null)
public static Task RunBatchEngineWebHosting(this IWebHostBuilder builder, string urls, SwaggerOptions? swaggerOptions = null, IBatchInterceptor? interceptor = null)
{
return builder
.PrepareBatchEngineMiddleware(interceptor)
Expand All @@ -43,7 +43,7 @@ public static Task RunBatchEngineWebHosting(this IWebHostBuilder builder, string
var entryAsm = Assembly.GetEntryAssembly()!;
var xmlName = entryAsm.GetName().Name + ".xml";
var xmlPath = Path.Combine(Path.GetDirectoryName(entryAsm.Location) ?? "", xmlName);
swaggerOptions = new SwaggerOptions(entryAsm.GetName().Name, "", "/") { XmlDocumentPath = xmlPath };
swaggerOptions = new SwaggerOptions(entryAsm.GetName().Name!, "", "/") { XmlDocumentPath = xmlPath };
}
services.AddSingleton<SwaggerOptions>(swaggerOptions);
})
Expand Down Expand Up @@ -105,7 +105,7 @@ static List<Type> CollectBatchTypes()
if (!(asm.FullName is null)
&& (asm.FullName.StartsWith("System") || asm.FullName.StartsWith("Microsoft.Extensions"))) continue;

Type[] types;
Type[]? types;
try
{
types = asm.GetTypes();
Expand Down
8 changes: 4 additions & 4 deletions src/MicroBatchFramework.WebHosting/BatchEngineMiddleware.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@ internal class WebHostingInterceptor : IBatchInterceptor
readonly IBatchInterceptor innerInterceptor;

public bool CompleteSuccessfully { get; private set; }
public string ErrorMessage { get; private set; }
public Exception Exception { get; private set; }
public string? ErrorMessage { get; private set; }
public Exception? Exception { get; private set; }

public WebHostingInterceptor(IBatchInterceptor innerInterceptor)
{
Expand All @@ -37,7 +37,7 @@ public ValueTask OnBatchRunBeginAsync(BatchContext context)
return innerInterceptor.OnBatchRunBeginAsync(context);
}

public ValueTask OnBatchRunCompleteAsync(BatchContext context, string errorMessageIfFailed, Exception exceptionIfExists)
public ValueTask OnBatchRunCompleteAsync(BatchContext context, string? errorMessageIfFailed, Exception? exceptionIfExists)
{
this.CompleteSuccessfully = (errorMessageIfFailed == null && exceptionIfExists == null);
this.ErrorMessage = errorMessageIfFailed;
Expand Down Expand Up @@ -115,7 +115,7 @@ public async Task Invoke(HttpContext httpContext)
}

// create args
string[] args = null;
string?[] args;
try
{
if (httpContext.Request.HasFormContentType)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
<PropertyGroup>
<TargetFramework>netcoreapp3.0</TargetFramework>
<LangVersion>8.0</LangVersion>
<Nullable>warnings</Nullable>
<Nullable>enable</Nullable>
</PropertyGroup>

<ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
// This definition is borrowed from Swashbuckle.

#nullable disable annotations
using Newtonsoft.Json;
using System.Collections.Generic;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ public class SwaggerDefinitionBuilder
readonly HttpContext httpContext;
readonly IEnumerable<MethodInfo> handlers;

ILookup<Tuple<string, string>, XmlCommentStructure> xDocLookup;
ILookup<Tuple<string, string>, XmlCommentStructure>? xDocLookup;

public SwaggerDefinitionBuilder(SwaggerOptions options, HttpContext httpContext, IEnumerable<MethodInfo> handlers)
{
Expand All @@ -33,15 +33,13 @@ public byte[] BuildSwaggerJson()
{
try
{
if (options.XmlDocumentPath != null && !File.Exists(options.XmlDocumentPath))
if (options.XmlDocumentPath != null && File.Exists(options.XmlDocumentPath))
{
xDocLookup = null;
xDocLookup = BuildXmlMemberCommentStructure(options.XmlDocumentPath);
}
else
{
xDocLookup = (options.XmlDocumentPath != null)
? BuildXmlMemberCommentStructure(options.XmlDocumentPath)
: null;
xDocLookup = null;
}

var doc = new SwaggerDocument();
Expand All @@ -54,7 +52,7 @@ public byte[] BuildSwaggerJson()

// tags.
var xmlServiceName = (xDocLookup != null)
? BuildXmlTypeSummary(options.XmlDocumentPath)
? BuildXmlTypeSummary(options.XmlDocumentPath!) // xDocLookup is not null if XmlDocumentPath is not null.
: null;

doc.tags = handlers
Expand All @@ -63,7 +61,7 @@ public byte[] BuildSwaggerJson()
.Distinct()
.Select(x =>
{
string desc = null;
string? desc = null;
if (xmlServiceName != null)
{
xmlServiceName.TryGetValue(x, out desc);
Expand All @@ -80,7 +78,7 @@ public byte[] BuildSwaggerJson()
{
// MemberInfo.DeclaringType is null only if it is a member of a VB Module.
string declaringTypeName = item.DeclaringType!.Name;
XmlCommentStructure xmlComment = null;
XmlCommentStructure? xmlComment = null;
if (xDocLookup != null)
{
// ParameterInfo.Name will be null only it is ReturnParameter.
Expand Down Expand Up @@ -123,7 +121,7 @@ public byte[] BuildSwaggerJson()
}
}

Schemas.Parameter[] BuildParameters(IDictionary<string, Schema> definitions, XmlCommentStructure xmlComment, MethodInfo method)
Schemas.Parameter[] BuildParameters(IDictionary<string, Schema> definitions, XmlCommentStructure? xmlComment, MethodInfo method)
{
var parameterInfos = method.GetParameters();
var parameters = parameterInfos
Expand All @@ -132,7 +130,8 @@ Schemas.Parameter[] BuildParameters(IDictionary<string, Schema> definitions, Xml
var parameterXmlComment = UnwrapTypeName(x.ParameterType);
if (xmlComment != null)
{
xmlComment.Parameters.TryGetValue(x.Name, out parameterXmlComment!);
// Name is null only if Parameter is ReturnParameter.
xmlComment.Parameters.TryGetValue(x.Name!, out parameterXmlComment!);
parameterXmlComment = UnwrapTypeName(x.ParameterType) + " " + parameterXmlComment;
}

Expand All @@ -147,8 +146,8 @@ Schemas.Parameter[] BuildParameters(IDictionary<string, Schema> definitions, Xml
? new PartialSchema { type = ToSwaggerDataType(collectionType) }
: null;

string defaultObjectExample = null;
object[] enums = null;
string? defaultObjectExample = null;
object[]? enums = null;
if (x.ParameterType.GetTypeInfo().IsEnum || (collectionType != null && collectionType.GetTypeInfo().IsEnum))
{
// Compiler cannot understand collectionType is not null.
Expand All @@ -169,7 +168,7 @@ Schemas.Parameter[] BuildParameters(IDictionary<string, Schema> definitions, Xml
}

var swaggerDataType = ToSwaggerDataType(x.ParameterType);
Schema refSchema = null;
Schema? refSchema = null;
if (swaggerDataType == "object")
{
BuildSchema(definitions, x.ParameterType);
Expand Down Expand Up @@ -203,7 +202,7 @@ string BuildSchema(IDictionary<string, Schema> definitions, Type type)
var fullName = type.FullName;
if (fullName == null) return ""; // safety(TODO:IDictionary<> is not supported)

Schema schema;
Schema? schema;
if (definitions.TryGetValue(fullName, out schema)) return "#/definitions/" + fullName;

var properties = type.GetProperties(BindingFlags.Instance | BindingFlags.Public);
Expand All @@ -229,10 +228,11 @@ string BuildSchema(IDictionary<string, Schema> definitions, Type type)
}
else
{
Schema items = null;
Schema? items = null;
if (swaggerDataType == "array")
{
var collectionType = GetCollectionType(memberType);
// If swaggerDataType is array, it will be Collection.
Type collectionType = GetCollectionType(memberType)!;
var dataType = ToSwaggerDataType(collectionType);
if (dataType == "object")
{
Expand All @@ -258,7 +258,7 @@ string BuildSchema(IDictionary<string, Schema> definitions, Type type)
}
}

IList<object> schemaEnum = null;
IList<object>? schemaEnum = null;
if (memberType.GetTypeInfo().IsEnum)
{
schemaEnum = Enum.GetNames(memberType);
Expand Down Expand Up @@ -298,7 +298,7 @@ static Type GetMemberType(MemberInfo memberInfo)
throw new Exception();
}

static Type GetCollectionType(Type type)
static Type? GetCollectionType(Type type)
{
if (type.IsArray) return type.GetElementType();

Expand Down Expand Up @@ -338,14 +338,14 @@ static ILookup<Tuple<string, string>, XmlCommentStructure> BuildXmlMemberComment
.ToDictionary(e => e.Item1, e => e.Item2.Value.Trim());

return new XmlCommentStructure
{
ClassName = match.Groups[1].Value,
MethodName = match.Groups[2].Value,
Summary = summary.Trim(),
Remarks = remarks.Trim(),
Parameters = parameters,
Returns = returns.Trim()
};
(
className: match.Groups[1].Value,
methodName: match.Groups[2].Value,
summary: summary.Trim(),
remarks: remarks.Trim(),
parameters: parameters,
returns: returns.Trim()
);
})
.ToLookup(x => Tuple.Create(x.ClassName, x.MethodName));

Expand Down Expand Up @@ -422,7 +422,7 @@ static string UnwrapTypeName(Type t)
return Regex.Replace(t.GetGenericTypeDefinition().Name, @"`.+$", "") + "&lt;" + innerFormat + "&gt;";
}

class Item1EqualityCompaerer<T1, T2> : EqualityComparer<Tuple<T1, T2>>
class Item1EqualityCompaerer<T1, T2> : EqualityComparer<Tuple<T1, T2>> where T1 : class
{
public override bool Equals(Tuple<T1, T2> x, Tuple<T1, T2> y)
{
Expand All @@ -443,6 +443,16 @@ class XmlCommentStructure
public string Remarks { get; set; }
public Dictionary<string, string> Parameters { get; set; }
public string Returns { get; set; }

public XmlCommentStructure(string className, string methodName, string summary, string remarks, Dictionary<string,string> parameters, string returns)
{
ClassName = className;
MethodName = methodName;
Summary = summary;
Remarks = remarks;
Parameters = parameters;
Returns = returns;
}
}
}

Expand All @@ -459,7 +469,7 @@ protected override JsonProperty CreateProperty(MemberInfo member, MemberSerializ
{
property.ShouldSerialize = instance =>
{
IEnumerable enumerable = null;
IEnumerable? enumerable = null;

// this value could be in a public field or public property
switch (member.MemberType)
Expand Down
6 changes: 3 additions & 3 deletions src/MicroBatchFramework.WebHosting/Swagger/SwaggerOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,9 @@ public class SwaggerOptions
/// <summary>
/// (FilePath, LoadedEmbeddedBytes) => CustomBytes)
/// </summary>
public Func<string, byte[], byte[]> ResolveCustomResource { get; set; }
public Func<HttpContext, string> CustomHost { get; set; }
public string XmlDocumentPath { get; set; }
public Func<string, byte[]?, byte[]>? ResolveCustomResource { get; set; }
public Func<HttpContext, string>? CustomHost { get; set; }
public string? XmlDocumentPath { get; set; }
public string JsonName { get; set; }
public string[] ForceSchemas { get; set; }

Expand Down
4 changes: 4 additions & 0 deletions src/MicroBatchFramework/BatchBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@
{
public abstract class BatchBase
{
// Context will be set non-null value by BatchEngine,
// but it might be null because it has public setter.
#nullable disable warnings
public BatchContext Context { get; set; }
#nullable restore warnings
}
}
4 changes: 2 additions & 2 deletions src/MicroBatchFramework/BatchContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,12 @@ namespace MicroBatchFramework
{
public class BatchContext
{
public string[] Arguments { get; private set; }
public string?[] Arguments { get; private set; }
public DateTime Timestamp { get; private set; }
public CancellationToken CancellationToken { get; private set; }
public ILogger<BatchEngine> Logger { get; private set; }

public BatchContext(string[] arguments, DateTime timestamp, CancellationToken cancellationToken, ILogger<BatchEngine> logger)
public BatchContext(string?[] arguments, DateTime timestamp, CancellationToken cancellationToken, ILogger<BatchEngine> logger)
{
Arguments = arguments;
Timestamp = timestamp;
Expand Down
Loading

0 comments on commit 55c982f

Please sign in to comment.