ApiCore: single line expressions replaced by expressions with braces

This commit is contained in:
Maksim Chegulov 2022-02-07 19:03:16 +03:00
parent a913fa4589
commit 179c8ddb84
22 changed files with 407 additions and 120 deletions

View File

@ -67,19 +67,27 @@ public class ConfirmAuthHandler : AuthenticationHandler<AuthenticationSchemeOpti
if (!_securityContext.IsAuthenticated)
{
if (emailValidationKeyModel.UiD.HasValue && !emailValidationKeyModel.UiD.Equals(Guid.Empty))
{
userId = emailValidationKeyModel.UiD.Value;
}
else
{
if (emailValidationKeyModel.Type == Web.Studio.Utility.ConfirmType.EmailActivation
|| emailValidationKeyModel.Type == Web.Studio.Utility.ConfirmType.EmpInvite
|| emailValidationKeyModel.Type == Web.Studio.Utility.ConfirmType.LinkInvite)
if (emailValidationKeyModel.Type == ConfirmType.EmailActivation
|| emailValidationKeyModel.Type == ConfirmType.EmpInvite
|| emailValidationKeyModel.Type == ConfirmType.LinkInvite)
{
userId = ASC.Core.Configuration.Constants.CoreSystem.ID;
}
else
{
userId = _userManager.GetUserByEmail(emailValidationKeyModel.Email).ID;
}
}
}
else
{
userId = _securityContext.CurrentAccount.ID;
}
_securityContext.AuthenticateMeWithoutCookie(userId, claims);
}
@ -96,6 +104,8 @@ public class ConfirmAuthHandler : AuthenticationHandler<AuthenticationSchemeOpti
public class ConfirmAuthHandlerExtension
{
public static void Register(DIHelper services) =>
services.TryAdd<EmailValidationKeyModelHelper>();
public static void Register(DIHelper services)
{
return services.TryAdd<EmailValidationKeyModelHelper>();
}
}

View File

@ -31,7 +31,6 @@ public class CookieAuthHandler : AuthenticationHandler<AuthenticationSchemeOptio
protected override Task<AuthenticateResult> HandleAuthenticateAsync()
{
var result = _authorizationHelper.ProcessBasicAuthorization(out _);
if (!result)
{
_securityContext.Logout();
@ -42,7 +41,6 @@ public class CookieAuthHandler : AuthenticationHandler<AuthenticationSchemeOptio
return Task.FromResult(
result ?
AuthenticateResult.Success(new AuthenticationTicket(Context.User, new AuthenticationProperties(), Scheme.Name)) :
AuthenticateResult.Fail(new AuthenticationException(HttpStatusCode.Unauthorized.ToString()))
);
AuthenticateResult.Fail(new AuthenticationException(HttpStatusCode.Unauthorized.ToString())));
}
}

View File

@ -5,7 +5,10 @@ public class ControllerNameAttribute : Attribute
{
public string Name { get; }
public ControllerNameAttribute(string name) => Name = name;
public ControllerNameAttribute(string name)
{
Name = name;
}
}
public class ControllerNameAttributeConvention : IControllerModelConvention
@ -14,6 +17,8 @@ public class ControllerNameAttributeConvention : IControllerModelConvention
{
var controllerNameAttribute = controller.Attributes.OfType<ControllerNameAttribute>().SingleOrDefault();
if (controllerNameAttribute != null)
{
controller.ControllerName = controllerNameAttribute.Name;
}
}
}

View File

@ -40,11 +40,15 @@ public class ApiContext : ICloneable
set
{
if (HttpContextAccessor.HttpContext.Items.ContainsKey(nameof(TotalCount)))
{
HttpContextAccessor.HttpContext.Items[nameof(TotalCount)] = value;
}
else
{
HttpContextAccessor.HttpContext.Items.Add(nameof(TotalCount), value);
}
}
}
/// <summary>
/// Filters responce to specific type from request parameter "type"
@ -115,14 +119,20 @@ public class ApiContext : ICloneable
_securityContext = securityContext;
_tenantManager = tenantManager;
HttpContextAccessor = httpContextAccessor;
if (httpContextAccessor.HttpContext == null) return;
if (httpContextAccessor.HttpContext == null)
{
return;
}
Count = s_maxCount;
var query = HttpContextAccessor.HttpContext.Request.Query;
//Try parse values
var count = query.GetRequestValue("count");
if (!string.IsNullOrEmpty(count) && ulong.TryParse(count, out var countParsed))
Count = Math.Min((long)countParsed, s_maxCount); //Count specified and valid
{
//Count specified and valid
Count = Math.Min((long)countParsed, s_maxCount);
}
var startIndex = query.GetRequestValue("startIndex");
if (startIndex != null && long.TryParse(startIndex, out var startIndexParsed))
@ -132,7 +142,10 @@ public class ApiContext : ICloneable
}
var sortOrder = query.GetRequestValue("sortOrder");
if ("descending".Equals(sortOrder)) SortDescending = true;
if ("descending".Equals(sortOrder))
{
SortDescending = true;
}
FilterToType = query.GetRequestValue("type");
SortBy = query.GetRequestValue("sortBy");
@ -143,7 +156,10 @@ public class ApiContext : ICloneable
Fields = query.GetRequestArray("fields");
var updatedSince = query.GetRequestValue("updatedSince");
if (updatedSince != null) UpdatedSince = Convert.ToDateTime(updatedSince);
if (updatedSince != null)
{
UpdatedSince = Convert.ToDateTime(updatedSince);
}
}
/// <summary>
@ -187,15 +203,24 @@ public class ApiContext : ICloneable
return this;
}
public object Clone() => MemberwiseClone();
public object Clone()
{
return MemberwiseClone();
}
public override string ToString() => string.Format("C:{0},S:{1},So:{2},Sd:{3},Fb;{4},Fo:{5},Fv:{6},Us:{7},Ftt:{8}", Count, StartIndex,
public override string ToString()
{
return string.Format("C:{0},S:{1},So:{2},Sd:{3},Fb;{4},Fo:{5},Fv:{6},Us:{7},Ftt:{8}", Count, StartIndex,
SortBy, SortDescending, FilterBy, FilterOp, FilterValue, UpdatedSince.Ticks, FilterToType);
}
public void AuthByClaim()
{
var id = HttpContextAccessor.HttpContext.User.Claims.FirstOrDefault(r => r.Type == ClaimTypes.Sid);
if (Guid.TryParse(id?.Value, out var userId)) _securityContext.AuthenticateMeWithoutCookie(userId);
if (Guid.TryParse(id?.Value, out var userId))
{
_securityContext.AuthenticateMeWithoutCookie(userId);
}
}
}
@ -235,6 +260,10 @@ public static class QueryExtension
public static class ApiContextExtension
{
public static bool Check(this ApiContext context, string field) =>
context?.Fields == null || (context.Fields != null && context.Fields.Contains(field, StringComparer.InvariantCultureIgnoreCase));
public static bool Check(this ApiContext context, string field)
{
return context?.Fields == null
|| (context.Fields != null
&& context.Fields.Contains(field, StringComparer.InvariantCultureIgnoreCase));
}
}

View File

@ -78,33 +78,45 @@ public class ApiDateTime : IComparable<ApiDateTime>, IComparable
TimeZoneOffset = offset;
}
public static ApiDateTime Parse(string data, TenantManager tenantManager, TimeZoneConverter timeZoneConverter) =>
Parse(data, null, tenantManager, timeZoneConverter);
public static ApiDateTime Parse(string data, TenantManager tenantManager, TimeZoneConverter timeZoneConverter)
{
return Parse(data, null, tenantManager, timeZoneConverter);
}
public static ApiDateTime Parse(string data, TimeZoneInfo tz, TenantManager tenantManager, TimeZoneConverter timeZoneConverter)
{
if (string.IsNullOrEmpty(data)) throw new ArgumentNullException(nameof(data));
if (data.Length < 7) throw new ArgumentException("invalid date time format");
if (string.IsNullOrEmpty(data))
{
throw new ArgumentNullException(nameof(data));
}
if (data.Length < 7)
{
throw new ArgumentException("invalid date time format");
}
var offsetPart = data.Substring(data.Length - 6, 6);
if (DateTime.TryParseExact(data, Formats, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal, out var dateTime))
{
//Parse time
var tzOffset = TimeSpan.Zero;
if (offsetPart.Contains(':') && TimeSpan.TryParse(offsetPart.TrimStart('+'), out tzOffset))
if (offsetPart.Contains(':')
&& TimeSpan.TryParse(offsetPart.TrimStart('+'), out tzOffset))
{
return new ApiDateTime(dateTime, tzOffset);
}
if (!data.EndsWith("Z", true, CultureInfo.InvariantCulture))
{
if (tz == null) tz = GetTimeZoneInfo(tenantManager, timeZoneConverter);
if (tz == null)
{
tz = GetTimeZoneInfo(tenantManager, timeZoneConverter);
}
tzOffset = tz.GetUtcOffset(dateTime);
dateTime = dateTime.Subtract(tzOffset);
}
return new ApiDateTime(dateTime, tzOffset);
}
throw new ArgumentException("invalid date time format: " + data);
@ -117,17 +129,25 @@ public class ApiDateTime : IComparable<ApiDateTime>, IComparable
UtcTime = DateTime.MinValue;
if (timeZone == null)
{
timeZone = GetTimeZoneInfo(_tenantManager, _timeZoneConverter);
}
//Hack
if (timeZone.IsInvalidTime(new DateTime(value.Ticks, DateTimeKind.Unspecified)))
{
value = value.AddHours(1);
}
if (value.Kind == DateTimeKind.Local)
{
value = TimeZoneInfo.ConvertTimeToUtc(new DateTime(value.Ticks, DateTimeKind.Unspecified), timeZone);
}
if (value.Kind == DateTimeKind.Unspecified)
{
value = new DateTime(value.Ticks, DateTimeKind.Utc); //Assume it's utc
}
if (value.Kind == DateTimeKind.Utc)
{
@ -154,7 +174,9 @@ public class ApiDateTime : IComparable<ApiDateTime>, IComparable
private string ToRoundTripString(DateTime date, TimeSpan offset)
{
var dateString = date.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffff", CultureInfo.InvariantCulture);
var offsetString = offset.Ticks == 0 ? "Z" : ((offset < TimeSpan.Zero) ? "-" : "+") + offset.ToString("hh\\:mm", CultureInfo.InvariantCulture);
var offsetString = offset.Ticks == 0
? "Z" : ((offset < TimeSpan.Zero)
? "-" : "+") + offset.ToString("hh\\:mm", CultureInfo.InvariantCulture);
return dateString + offsetString;
}
@ -180,64 +202,115 @@ public class ApiDateTime : IComparable<ApiDateTime>, IComparable
public static bool operator >(ApiDateTime left, ApiDateTime right)
{
if (ReferenceEquals(left, right)) return false;
if (left == null) return false;
if (ReferenceEquals(left, right))
{
return false;
}
if (left == null)
{
return false;
}
return left.CompareTo(right) > 0;
}
public static bool operator >=(ApiDateTime left, ApiDateTime right)
{
if (ReferenceEquals(left, right)) return false;
if (left == null) return false;
if (ReferenceEquals(left, right))
{
return false;
}
if (left == null)
{
return false;
}
return left.CompareTo(right) >= 0;
}
public static bool operator <=(ApiDateTime left, ApiDateTime right) => !(left >= right);
public static bool operator <=(ApiDateTime left, ApiDateTime right)
{
return !(left >= right);
}
public static bool operator <(ApiDateTime left, ApiDateTime right) => !(left > right);
public static bool operator <(ApiDateTime left, ApiDateTime right)
{
return !(left > right);
}
public static bool operator ==(ApiDateTime left, ApiDateTime right) => Equals(left, right);
public static bool operator ==(ApiDateTime left, ApiDateTime right)
{
return Equals(left, right);
}
public static bool operator !=(ApiDateTime left, ApiDateTime right) => !(left == right);
public static bool operator !=(ApiDateTime left, ApiDateTime right)
{
return !(left == right);
}
public static implicit operator DateTime(ApiDateTime d)
{
if (d == null) return DateTime.MinValue;
if (d == null)
{
return DateTime.MinValue;
}
return d.UtcTime;
}
public static implicit operator DateTime?(ApiDateTime d)
{
if (d == null) return null;
if (d == null)
{
return null;
}
return d.UtcTime;
}
public int CompareTo(DateTime other) => CompareTo(new ApiDateTime(_tenantManager, _timeZoneConverter, other));
public int CompareTo(DateTime other)
{
return CompareTo(new ApiDateTime(_tenantManager, _timeZoneConverter, other));
}
public int CompareTo(ApiDateTime other)
{
if (other == null) return 1;
if (other == null)
{
return 1;
}
return UtcTime.CompareTo(other.UtcTime);
}
public override bool Equals(object obj)
{
if (obj is null) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != typeof(ApiDateTime)) return false;
if (obj is null)
{
return false;
}
if (ReferenceEquals(this, obj))
{
return true;
}
if (obj.GetType() != typeof(ApiDateTime))
{
return false;
}
return Equals((ApiDateTime)obj);
}
public bool Equals(ApiDateTime other)
{
if (other is null) return false;
if (ReferenceEquals(this, other)) return true;
if (other is null)
{
return false;
}
if (ReferenceEquals(this, other))
{
return true;
}
return UtcTime.Equals(other.UtcTime) && TimeZoneOffset.Equals(other.TimeZoneOffset);
}
@ -253,7 +326,9 @@ public class ApiDateTime : IComparable<ApiDateTime>, IComparable
public int CompareTo(object obj)
{
if (obj is DateTime dateTime)
{
return CompareTo(dateTime);
}
return obj is ApiDateTime apiDateTime ? CompareTo(apiDateTime) : 0;
}
@ -261,14 +336,18 @@ public class ApiDateTime : IComparable<ApiDateTime>, IComparable
public override string ToString()
{
var localUtcTime = UtcTime;
if (!UtcTime.Equals(DateTime.MinValue))
{
localUtcTime = UtcTime.Add(TimeZoneOffset);
}
return ToRoundTripString(localUtcTime, TimeZoneOffset);
}
public static ApiDateTime GetSample() => new ApiDateTime(DateTime.UtcNow, TimeSpan.Zero);
public static ApiDateTime GetSample()
{
return new ApiDateTime(DateTime.UtcNow, TimeSpan.Zero);
}
}
public class ApiDateTimeTypeConverter : DateTimeConverter
@ -276,7 +355,9 @@ public class ApiDateTimeTypeConverter : DateTimeConverter
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
{
if (destinationType == typeof(string))
{
return value.ToString();
}
return base.ConvertTo(context, culture, value, destinationType);
}
@ -284,10 +365,13 @@ public class ApiDateTimeTypeConverter : DateTimeConverter
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
if (value is string @string)
{
return ApiDateTime.Parse(@string, null, null);
}
if (value is DateTime time)
{
return new ApiDateTime(null, null, time);
}
return base.ConvertFrom(context, culture, value);
}
@ -298,18 +382,27 @@ public class ApiDateTimeConverter : System.Text.Json.Serialization.JsonConverter
public override ApiDateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
if (reader.TryGetDateTime(out var result))
{
return new ApiDateTime(result, TimeSpan.Zero);
}
else
{
if (DateTime.TryParseExact(reader.GetString(), ApiDateTime.Formats, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out var dateTime))
if (DateTime.TryParseExact(reader.GetString(), ApiDateTime.Formats,
CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out var dateTime))
{
return new ApiDateTime(dateTime, TimeSpan.Zero);
}
else
{
return new ApiDateTime();
}
}
}
public override void Write(Utf8JsonWriter writer, ApiDateTime value, JsonSerializerOptions options) =>
public override void Write(Utf8JsonWriter writer, ApiDateTime value, JsonSerializerOptions options)
{
writer.WriteStringValue(value.ToString());
}
}
[Scope]
@ -324,5 +417,8 @@ public class ApiDateTimeHelper
_timeZoneConverter = timeZoneConverter;
}
public ApiDateTime Get(DateTime? from) => ApiDateTime.FromDate(_tenantManager, _timeZoneConverter, from);
public ApiDateTime Get(DateTime? from)
{
return ApiDateTime.FromDate(_tenantManager, _timeZoneConverter, from);
}
}

View File

@ -21,8 +21,10 @@ public abstract class BaseStartup
DIHelper = new DIHelper();
if (bool.TryParse(Configuration["core:products"], out var loadProducts))
{
LoadProducts = loadProducts;
}
}
public virtual void ConfigureServices(IServiceCollection services)
{
@ -31,7 +33,9 @@ public abstract class BaseStartup
services.AddMemoryCache();
if (AddAndUseSession)
{
services.AddSession();
}
DIHelper.Configure(services);
@ -70,8 +74,9 @@ public abstract class BaseStartup
var kafkaConfiguration = Configuration.GetSection("kafka").Get<KafkaSettings>();
if (kafkaConfiguration != null)
{
DIHelper.TryAdd(typeof(ICacheNotify<>), typeof(KafkaCache<>));
}
else if (redisConfiguration != null)
{
DIHelper.TryAdd(typeof(ICacheNotify<>), typeof(RedisCache<>));
@ -79,12 +84,16 @@ public abstract class BaseStartup
services.AddStackExchangeRedisExtensions<NewtonsoftSerializer>(redisConfiguration);
}
else
{
DIHelper.TryAdd(typeof(ICacheNotify<>), typeof(MemoryCacheNotify<>));
}
DIHelper.TryAdd(typeof(IWebhookPublisher), typeof(WebhookPublisher));
if (LoadProducts)
{
DIHelper.RegisterProducts(Configuration, HostEnvironment.ContentRootPath);
}
var builder = services.AddMvcCore(config =>
{
@ -111,7 +120,9 @@ public abstract class BaseStartup
.AddScheme<AuthenticationSchemeOptions, CookieAuthHandler>("cookie", a => { });
if (ConfirmAddScheme)
{
authBuilder.AddScheme<AuthenticationSchemeOptions, ConfirmAuthHandler>("confirm", a => { });
}
services.AddAutoMapper(Assembly.GetAssembly(typeof(MappingProfile)));
}
@ -126,7 +137,9 @@ public abstract class BaseStartup
app.UseRouting();
if (AddAndUseSession)
{
app.UseSession();
}
app.UseAuthentication();
@ -165,7 +178,8 @@ public static class LogNLogConfigureExtenstion
{
return hostBuilder.ConfigureLogging((hostBuildexContext, r) =>
{
_ = new ConfigureLogNLog(hostBuildexContext.Configuration, new ConfigurationExtension(hostBuildexContext.Configuration), hostBuildexContext.HostingEnvironment);
_ = new ConfigureLogNLog(hostBuildexContext.Configuration,
new ConfigurationExtension(hostBuildexContext.Configuration), hostBuildexContext.HostingEnvironment);
r.AddNLog(LogManager.Configuration);
});
}

View File

@ -18,7 +18,10 @@ public class CustomEndpointDataSource : EndpointDataSource
var enableFormat = attr == null || !attr.DisableFormat;
if (enableFormat)
endpoints.Add(new RouteEndpoint(r.RequestDelegate, RoutePatternFactory.Parse(r.RoutePattern.RawText + ".{format}"), r.Order, r.Metadata, r.DisplayName));
{
endpoints.Add(new RouteEndpoint(r.RequestDelegate, RoutePatternFactory.Parse(r.RoutePattern.RawText
+ ".{format}"), r.Order, r.Metadata, r.DisplayName));
}
else
{
endpoints.Add(new RouteEndpoint(r.RequestDelegate, RoutePatternFactory.Parse(r.RoutePattern.RawText + ".json"), r.Order - 1, r.Metadata, r.DisplayName));
@ -26,10 +29,14 @@ public class CustomEndpointDataSource : EndpointDataSource
}
return endpoints;
}).ToList();
}
public override IChangeToken GetChangeToken() => Source.GetChangeToken();
public override IChangeToken GetChangeToken()
{
return Source.GetChangeToken();
}
}
public static class EndpointExtension

View File

@ -23,7 +23,6 @@ public static class CustomHealthCheck
tags: new string[] { "postgredb" });
var kafkaSettings = configurationExtension.GetSetting<KafkaSettings>("kafka");
if (kafkaSettings != null && !string.IsNullOrEmpty(kafkaSettings.BootstrapServers))
{
var clientConfig = new ClientConfig { BootstrapServers = kafkaSettings.BootstrapServers };
@ -34,9 +33,7 @@ public static class CustomHealthCheck
}
var elasticSettings = configuration.GetSection("elastic");
if (elasticSettings != null && elasticSettings.GetChildren().Any())
{
var host = elasticSettings.GetSection("Host").Value ?? "localhost";
@ -45,10 +42,12 @@ public static class CustomHealthCheck
var elasticSearchUri = $"{scheme}://{host}:{port}";
if (Uri.IsWellFormedUriString(elasticSearchUri, UriKind.Absolute))
{
hcBuilder.AddElasticsearch(elasticSearchUri,
name: "elasticsearch",
tags: new string[] { "elasticsearch" });
}
}
return services;
}

View File

@ -29,5 +29,4 @@ public class ItemKeyValuePair<TKey, TValue>
{
public TKey Key { get; set; }
public TValue Value { get; set; }
}

View File

@ -27,21 +27,33 @@ namespace ASC.Api.Utils;
public static class Validate
{
public static T If<T>(this T item, Func<T, bool> @if, Func<T> then) where T : class =>
@if(item) ? then() : item;
public static T If<T>(this T item, Func<T, bool> @if, Func<T> then) where T : class
{
return @if(item) ? then() : item;
}
public static T IfNull<T>(this T item, Func<T> func) where T : class => item.If((x) =>
x == default(T), func);
public static T IfNull<T>(this T item, Func<T> func) where T : class
{
return item.If((x) => x == default(T), func);
}
public static T ThrowIfNull<T>(this T item, Exception e) where T : class =>
item.IfNull(() => { throw e; });
public static T ThrowIfNull<T>(this T item, Exception e) where T : class
{
return item.IfNull(() => { throw e; });
}
public static T NotFoundIfNull<T>(this T item) where T : class =>
NotFoundIfNull(item, "Item not found");
public static T NotFoundIfNull<T>(this T item) where T : class
{
return NotFoundIfNull(item, "Item not found");
}
public static T NotFoundIfNull<T>(this T item, string message) where T : class =>
item.IfNull(() => { throw new ItemNotFoundException(message); });
public static T NotFoundIfNull<T>(this T item, string message) where T : class
{
return item.IfNull(() => { throw new ItemNotFoundException(message); });
}
public static T? NullIfDefault<T>(this T item) where T : struct =>
EqualityComparer<T>.Default.Equals(item, default(T)) ? default(T?) : item;
public static T? NullIfDefault<T>(this T item) where T : struct
{
return EqualityComparer<T>.Default.Equals(item, default(T)) ? default(T?) : item;
}
}

View File

@ -2,8 +2,10 @@
public class XmlOutputFormatter : IOutputFormatter
{
public bool CanWriteResult(OutputFormatterCanWriteContext context) =>
context.ContentType == MimeMapping.GetMimeMapping(".xml");
public bool CanWriteResult(OutputFormatterCanWriteContext context)
{
return context.ContentType == MimeMapping.GetMimeMapping(".xml");
}
public Task WriteAsync(OutputFormatterWriteContext context)
{

View File

@ -81,4 +81,3 @@ global using NLog;
global using NLog.Extensions.Logging;
global using StackExchange.Redis.Extensions.Core.Configuration;
global using StackExchange.Redis.Extensions.Newtonsoft;

View File

@ -5,13 +5,21 @@ public abstract class CommonApiResponse
public int Status { get; set; }
public HttpStatusCode StatusCode { get; set; }
protected CommonApiResponse(HttpStatusCode statusCode) => StatusCode = statusCode;
protected CommonApiResponse(HttpStatusCode statusCode)
{
StatusCode = statusCode;
public static SuccessApiResponse Create(HttpStatusCode statusCode, object response) =>
new SuccessApiResponse(statusCode, response);
}
public static ErrorApiResponse CreateError(HttpStatusCode statusCode, Exception error) =>
new ErrorApiResponse(statusCode, error);
public static SuccessApiResponse Create(HttpStatusCode statusCode, object response)
{
return new SuccessApiResponse(statusCode, response);
}
public static ErrorApiResponse CreateError(HttpStatusCode statusCode, Exception error)
{
return new ErrorApiResponse(statusCode, error);
}
}
public class ErrorApiResponse : CommonApiResponse
@ -37,13 +45,28 @@ public class SuccessApiResponse : CommonApiResponse
Response = response;
Total = total;
if (count.HasValue) Count = count;
if (count.HasValue)
{
Count = count;
}
else
{
if (response is List<object> list) Count = list.Count;
else if (response is IEnumerable<object> collection) Count = collection.Count();
else if (response == null) Count = 0;
else Count = 1;
if (response is List<object> list)
{
Count = list.Count;
}
else if (response is IEnumerable<object> collection)
{
Count = collection.Count();
}
else if (response == null)
{
Count = 0;
}
else
{
Count = 1;
}
}
}
}
@ -55,12 +78,14 @@ public class CommonApiError
public string Stack { get; set; }
public int Hresult { get; set; }
public static CommonApiError FromException(Exception exception, string message = null) =>
new CommonApiError()
public static CommonApiError FromException(Exception exception, string message = null)
{
return new CommonApiError()
{
Message = message ?? exception.Message,
Type = exception.GetType().ToString(),
Stack = exception.StackTrace,
Hresult = exception.HResult
};
}
}

View File

@ -4,7 +4,10 @@ public class CultureMiddleware
{
private readonly RequestDelegate _next;
public CultureMiddleware(RequestDelegate next) => _next = next;
public CultureMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context, UserManager userManager, TenantManager tenantManager, AuthContext authContext)
{
@ -14,10 +17,16 @@ public class CultureMiddleware
{
var user = userManager.GetUsers(authContext.CurrentAccount.ID);
if (!string.IsNullOrEmpty(user.CultureName)) culture = user.GetCulture();
if (!string.IsNullOrEmpty(user.CultureName))
{
culture = user.GetCulture();
}
}
if (culture == null) culture = tenantManager.GetCurrentTenant().GetCulture();
if (culture == null)
{
culture = tenantManager.GetCurrentTenant().GetCulture();
}
Thread.CurrentThread.CurrentCulture = culture;
Thread.CurrentThread.CurrentUICulture = culture;
@ -28,6 +37,8 @@ public class CultureMiddleware
public static class CultureMiddlewareExtensions
{
public static IApplicationBuilder UseCultureMiddleware(this IApplicationBuilder builder) =>
builder.UseMiddleware<CultureMiddleware>();
public static IApplicationBuilder UseCultureMiddleware(this IApplicationBuilder builder)
{
return builder.UseMiddleware<CultureMiddleware>();
}
}

View File

@ -4,7 +4,10 @@ public class DisposeMiddleware
{
private readonly RequestDelegate _next;
public DisposeMiddleware(RequestDelegate next) => _next = next;
public DisposeMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
@ -16,6 +19,8 @@ public class DisposeMiddleware
public static class DisposeMiddlewareExtensions
{
public static IApplicationBuilder UseDisposeMiddleware(this IApplicationBuilder builder) =>
builder.UseMiddleware<DisposeMiddleware>();
public static IApplicationBuilder UseDisposeMiddleware(this IApplicationBuilder builder)
{
return builder.UseMiddleware<DisposeMiddleware>();
}
}

View File

@ -50,7 +50,10 @@ public class ProductSecurityFilter : IResourceFilter
public void OnResourceExecuting(ResourceExecutingContext context)
{
if (!_authContext.IsAuthenticated) return;
if (!_authContext.IsAuthenticated)
{
return;
}
if (context.ActionDescriptor is ControllerActionDescriptor controllerActionDescriptor)
{
@ -58,7 +61,9 @@ public class ProductSecurityFilter : IResourceFilter
if (pid != Guid.Empty)
{
if (CallContext.GetData("asc.web.product_id") == null)
{
CallContext.SetData("asc.web.product_id", pid);
}
if (!_webItemSecurity.IsAvailableForMe(pid))
{
@ -71,7 +76,10 @@ public class ProductSecurityFilter : IResourceFilter
private static Guid FindProduct(ControllerActionDescriptor method)
{
if (method == null || string.IsNullOrEmpty(method.ControllerName)) return default;
if (method == null || string.IsNullOrEmpty(method.ControllerName))
{
return default;
}
var name = method.ControllerName.ToLower();
if (name == "community")
@ -80,11 +88,17 @@ public class ProductSecurityFilter : IResourceFilter
if (!string.IsNullOrEmpty(url))
{
var module = url.Split('/')[0];
if (s_products.ContainsKey(module)) return s_products[module];
if (s_products.ContainsKey(module))
{
return s_products[module];
}
}
}
if (s_products.ContainsKey(name)) return s_products[name];
if (s_products.ContainsKey(name))
{
return s_products[name];
}
return default;
}

View File

@ -7,7 +7,10 @@ public class CustomExceptionFilterAttribute : ExceptionFilterAttribute
var status = (HttpStatusCode)context.HttpContext.Response.StatusCode;
string message = null;
if (status == HttpStatusCode.OK) status = HttpStatusCode.InternalServerError;
if (status == HttpStatusCode.OK)
{
status = HttpStatusCode.InternalServerError;
}
switch (context.Exception)
{

View File

@ -39,5 +39,8 @@ public class Contact
Value = value;
}
public static Contact GetSample() => new Contact("GTalk", "my@gmail.com");
public static Contact GetSample()
{
return new Contact("GTalk", "my@gmail.com");
}
}

View File

@ -33,14 +33,16 @@ public class EmployeeWraper
public string AvatarSmall { get; set; }
public string ProfileUrl { get; set; }
public static EmployeeWraper GetSample() =>
new EmployeeWraper
public static EmployeeWraper GetSample()
{
return new EmployeeWraper
{
Id = Guid.Empty,
DisplayName = "Mike Zanyatski",
Title = "Manager",
AvatarSmall = "url to small avatar",
};
}
}
[Scope]
@ -68,7 +70,10 @@ public class EmployeeWraperHelper
}
public EmployeeWraper Get(UserInfo userInfo) => Init(new EmployeeWraper(), userInfo);
public EmployeeWraper Get(UserInfo userInfo)
{
return Init(new EmployeeWraper(), userInfo);
}
public EmployeeWraper Get(Guid userId)
{
@ -87,12 +92,18 @@ public class EmployeeWraperHelper
result.Id = userInfo.ID;
result.DisplayName = _displayUserSettingsHelper.GetFullUserName(userInfo);
if (!string.IsNullOrEmpty(userInfo.Title)) result.Title = userInfo.Title;
if (!string.IsNullOrEmpty(userInfo.Title))
{
result.Title = userInfo.Title;
}
var userInfoLM = userInfo.LastModified.GetHashCode();
if (_httpContext.Check("avatarSmall"))
result.AvatarSmall = UserPhotoManager.GetSmallPhotoURL(userInfo.ID, out var isdef) + (isdef ? "" : $"?_={userInfoLM}");
{
result.AvatarSmall = UserPhotoManager.GetSmallPhotoURL(userInfo.ID, out var isdef)
+ (isdef ? "" : $"?_={userInfoLM}");
}
if (result.Id != Guid.Empty)
{

View File

@ -112,7 +112,11 @@ public class EmployeeWraperFullHelper : EmployeeWraperHelper
public static Expression<Func<User, UserInfo>> GetExpression(ApiContext apiContext)
{
if (apiContext?.Fields == null) return null;
if (apiContext?.Fields == null)
{
return null;
}
var newExpr = Expression.New(typeof(UserInfo));
//i => new UserInfo { ID = i.id }
@ -120,7 +124,10 @@ public class EmployeeWraperFullHelper : EmployeeWraperHelper
var bindExprs = new List<MemberAssignment>();
if (apiContext.Check("Id"))
bindExprs.Add(Expression.Bind(typeof(UserInfo).GetProperty("ID"), Expression.Property(parameter, typeof(User).GetProperty("Id"))));
{
bindExprs.Add(Expression.Bind(typeof(UserInfo).GetProperty("ID"),
Expression.Property(parameter, typeof(User).GetProperty("Id"))));
}
var body = Expression.MemberInit(newExpr, bindExprs);
var lambda = Expression.Lambda<Func<User, UserInfo>>(body, parameter);
@ -151,21 +158,31 @@ public class EmployeeWraperFullHelper : EmployeeWraperHelper
Init(result, userInfo);
if (userInfo.Sex.HasValue)
{
result.Sex = userInfo.Sex.Value ? "male" : "female";
}
if (!string.IsNullOrEmpty(userInfo.Location))
{
result.Location = userInfo.Location;
}
if (!string.IsNullOrEmpty(userInfo.Notes))
{
result.Notes = userInfo.Notes;
}
if (!string.IsNullOrEmpty(userInfo.MobilePhone))
{
result.MobilePhone = userInfo.MobilePhone;
}
result.MobilePhoneActivationStatus = userInfo.MobilePhoneActivationStatus;
if (!string.IsNullOrEmpty(userInfo.CultureName))
{
result.CultureName = userInfo.CultureName;
}
FillConacts(result, userInfo);
@ -180,25 +197,36 @@ public class EmployeeWraperFullHelper : EmployeeWraperHelper
result.Groups = groups;
result.Department = string.Join(", ", result.Groups.Select(d => d.Name.HtmlEncode()));
}
else result.Department = "";
else
{
result.Department = "";
}
}
var userInfoLM = userInfo.LastModified.GetHashCode();
if (_context.Check("avatarMax"))
{
result.AvatarMax = UserPhotoManager.GetMaxPhotoURL(userInfo.ID, out var isdef) + (isdef ? "" : $"?_={userInfoLM}");
}
if (_context.Check("avatarMedium"))
{
result.AvatarMedium = UserPhotoManager.GetMediumPhotoURL(userInfo.ID, out var isdef) + (isdef ? "" : $"?_={userInfoLM}");
}
if (_context.Check("avatar"))
{
result.Avatar = UserPhotoManager.GetBigPhotoURL(userInfo.ID, out var isdef) + (isdef ? "" : $"?_={userInfoLM}");
}
if (_context.Check("listAdminModules"))
{
var listAdminModules = userInfo.GetListAdminModules(_webItemSecurity);
if (listAdminModules.Any()) result.ListAdminModules = listAdminModules;
if (listAdminModules.Any())
{
result.ListAdminModules = listAdminModules;
}
}
return result;
@ -206,17 +234,24 @@ public class EmployeeWraperFullHelper : EmployeeWraperHelper
private void FillConacts(EmployeeWraperFull employeeWraperFull, UserInfo userInfo)
{
if (userInfo.ContactsList == null) return;
if (userInfo.ContactsList == null)
{
return;
}
var contacts = new List<Contact>();
for (var i = 0; i < userInfo.ContactsList.Count; i += 2)
{
if (i + 1 < userInfo.ContactsList.Count)
{
contacts.Add(new Contact(userInfo.ContactsList[i], userInfo.ContactsList[i + 1]));
}
}
if (contacts.Any())
{
employeeWraperFull.Contacts = contacts;
}
}
}

View File

@ -42,6 +42,13 @@ public class GroupWrapperSummary
Manager = userManager.GetUsers(userManager.GetDepartmentManager(group.ID)).UserName;
}
public static GroupWrapperSummary GetSample() =>
new GroupWrapperSummary { Id = Guid.Empty, Manager = "Jake.Zazhitski", Name = "Group Name" };
public static GroupWrapperSummary GetSample()
{
return new GroupWrapperSummary
{
Id = Guid.Empty,
Manager = "Jake.Zazhitski",
Name = "Group Name"
};
}
}

View File

@ -4,7 +4,10 @@ public class DefaultRouteAttribute : RouteAttribute
{
public static string BaseUrl { get; set; }
static DefaultRouteAttribute() => BaseUrl = "api/2.0";
static DefaultRouteAttribute()
{
BaseUrl = "api/2.0";
}
public DefaultRouteAttribute() : base(BaseUrl) { }
}