Former-commit-id: 6d818dd16546c8e39cfa58f85bc6d22148b13218
TangShanKaiPing
wanggang 5 years ago
parent cd6a7bcc86
commit 5b8386ee4a

@ -0,0 +1,197 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.ModelBinding.Metadata;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Dynamic;
using System.Linq;
using System.Reflection;
namespace CSharpObjectJsonSchema.Controllers
{
public static class ControllerExtensions
{
public static object GetJsonSchema<T>(this ControllerBase controller)
{
if (controller is null)
{
throw new ArgumentNullException(nameof(controller));
}
var metadata = controller.HttpContext.RequestServices.GetRequiredService<IModelMetadataProvider>().GetMetadataForType(typeof(T));
return CreateJson(controller, metadata as DefaultModelMetadata);
}
public static object CreateJson(this ControllerBase controller, DefaultModelMetadata metadata)
{
if (metadata is null)
{
return null;
}
try
{
dynamic json = new ExpandoObject();
var dictionary = (IDictionary<string, object>)json;
//type
if (metadata.IsComplexType && metadata.IsCollectionType)
{
json.type = "array";
json.items = new { type = metadata.ModelType.GenericTypeArguments[0].Name };
}
else if (metadata.IsEnum)
{
json.type = "string";
dictionary["enum"] = metadata.IsNullableValueType ? Enum.GetNames(metadata.ModelType.GenericTypeArguments[0]) : Enum.GetNames(metadata.ModelType);
}
else
{
var modelType = metadata.IsNullableValueType ? metadata.ModelType.GenericTypeArguments[0] : metadata.ModelType;
if (modelType == typeof(string))
{
json.type = "string";
}
else if (modelType == typeof(int) || modelType == typeof(long))
{
json.type = "integer";
}
else if (modelType == typeof(float) || modelType == typeof(double) || modelType == typeof(decimal))
{
json.type = "number";
}
else if (modelType == typeof(bool))
{
json.type = "boolean";
}
else if (modelType == typeof(DateTime))
{
json.type = "string";
}
else
{
json.type = "object";
}
}
//title
if (metadata.DisplayName != null)
{
json.title = metadata.DisplayName;
}
foreach (var attribute in metadata.Attributes.Attributes)
{
if (attribute is DescriptionAttribute descriptionAttribute)
{//description
json.description = descriptionAttribute.Description;
}
else if (attribute is RegularExpressionAttribute regularExpressionAttribute)
{//pattern
json.pattern = regularExpressionAttribute.Pattern;
}
else if (attribute is DataTypeAttribute dataTypeAttribute)
{//format
if (dataTypeAttribute.DataType == DataType.DateTime)
{
json.format = "date-time";
}
else if (dataTypeAttribute.DataType == DataType.Time)
{
json.format = "time";
}
else if (dataTypeAttribute.DataType == DataType.EmailAddress)
{
json.format = "email";
}
else if (dataTypeAttribute.DataType == DataType.Url)
{
json.format = "uri";
}
else if (dataTypeAttribute.DataType == DataType.Custom)
{//自定义
json.format = dataTypeAttribute.GetDataTypeName().ToLower();
}
else
{
json.format = dataTypeAttribute.DataType.ToString().ToLower();
}
}
else if (attribute is ReadOnlyAttribute readOnlyAttribute)
{//readOnly
json.readOnly = readOnlyAttribute.IsReadOnly;
}
else if (attribute is MinLengthAttribute minLengthAttribute)
{//minLength
json.minLength = minLengthAttribute.Length;
}
else if (attribute is MaxLengthAttribute maxLengthAttribute)
{//maxLength
json.maxLength = maxLengthAttribute.Length;
}
else if (attribute is StringLengthAttribute stringLengthAttribute)
{//minLength,maxLength
json.minLength = stringLengthAttribute.MinimumLength;
json.maxLength = stringLengthAttribute.MaximumLength;
}
else if (attribute is RangeAttribute rangeAttribute)
{//minimum,maximum
json.minimum = rangeAttribute.Minimum;
json.maximum = rangeAttribute.Maximum;
}
else if (attribute is ScaffoldColumnAttribute scaffoldColumnAttribute)
{//scaffold 自定义
json.scaffold = scaffoldColumnAttribute.Scaffold;
}
else if (attribute is HiddenInputAttribute hiddenInputAttribute)
{//hidden 自定义
json.hidden = hiddenInputAttribute.DisplayValue;
}
else if (attribute is UIHintAttribute uIHintAttribute)
{//ui 自定义
json.ui = uIHintAttribute.UIHint;
}
else if (attribute is CompareAttribute compareAttribute)
{//compare 自定义
json.compare = compareAttribute.OtherProperty;
}
else if (attribute is RemoteAttribute remoteAttribute)
{//remote 自定义
var routeData = attribute.GetType().GetProperty("RouteData", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(remoteAttribute) as RouteValueDictionary;
json.remote = new
{
url = controller.Url.Action(routeData["action"].ToString(), routeData["controller"].ToString(), new { Area = routeData["area"].ToString() }),
remoteAttribute.AdditionalFields,
//remoteAttribute.
};
}
}
dynamic properties = new ExpandoObject();
var propertiesDictionary = (IDictionary<string, object>)properties;
var requiredList = new List<string>();
if (metadata.IsComplexType && !metadata.IsCollectionType && metadata.Properties.Any())
{
foreach (var item in metadata.Properties)
{
var modelMetadataItem = item as DefaultModelMetadata;
propertiesDictionary[item.PropertyName] = CreateJson(controller, modelMetadataItem);
if (modelMetadataItem.IsRequired)
{
requiredList.Add(item.PropertyName);
}
}
json.properties = properties;
if (requiredList.Any())
{
json.required = requiredList;
}
}
return json;
}
catch (Exception ex)
{
return null;
}
}
}
}

@ -1,19 +1,8 @@
using CSharpObjectJsonSchema.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.ModelBinding.Metadata;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Diagnostics;
using System.Dynamic;
using System.Linq;
using System.Reflection;
namespace CSharpObjectJsonSchema.Controllers
{
@ -28,86 +17,7 @@ namespace CSharpObjectJsonSchema.Controllers
public string Index()
{
var metadata = this.HttpContext.RequestServices.GetRequiredService<IModelMetadataProvider>().GetMetadataForType(new TestModel().GetType()) as DefaultModelMetadata;
var json = CreateJson(metadata);
return JsonConvert.SerializeObject(json, Formatting.Indented);
}
private object CreateJson(DefaultModelMetadata metadata)
{
try
{
dynamic json = new ExpandoObject();
var dictionary = (IDictionary<string, object>)json;
//type
if (metadata.IsComplexType && metadata.IsCollectionType)
{
json.type = "array";
json.items = new { type = metadata.ModelType.GenericTypeArguments[0].Name };
}
else if (metadata.IsNullableValueType)
{
json.type = metadata.ModelType.GenericTypeArguments[0].Name;
}
else
{
json.type = metadata.ModelType.Name;
}
if (!metadata.IsComplexType && !metadata.IsNullableValueType && metadata.ModelType != typeof(string))
{
json.required = true;
}
if (metadata.DisplayName != null)
{
json.title = metadata.DisplayName;
}
foreach (var attribute in metadata.Attributes.Attributes)
{
if (attribute is DescriptionAttribute descriptionAttribute)
{
json.description = descriptionAttribute.Description;
}
else if (attribute is RegularExpressionAttribute regularExpressionAttribute)
{
json.pattern = regularExpressionAttribute.Pattern;
}
else if (attribute is RequiredAttribute requiredAttribute)
{
json.required = true;
}
//
else if (attribute is CompareAttribute compareAttribute)
{
json.compare = compareAttribute.OtherProperty;
}
else if (attribute is RemoteAttribute remoteAttribute)
{
var routeData = attribute.GetType().GetProperty("RouteData", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(remoteAttribute) as RouteValueDictionary;
json.remote = new
{
url = Url.Action(routeData["action"].ToString(), routeData["controller"].ToString(), new { Area = routeData["area"].ToString() }),
remoteAttribute.AdditionalFields,
//remoteAttribute.
};
}
}
dynamic properties = new ExpandoObject();
var propertiesDictionary = (IDictionary<string, object>)properties;
if (metadata.IsComplexType && !metadata.IsCollectionType && metadata.Properties.Any())
{
foreach (var item in metadata.Properties)
{
propertiesDictionary[item.PropertyName] = CreateJson(item as DefaultModelMetadata);
}
json.properties = properties;
}
return json;
}
catch (Exception ex)
{
return null;
}
//Console.WriteLine(metadata.DataTypeName);
return JsonConvert.SerializeObject(this.GetJsonSchema<TestModel>(), Formatting.Indented);
}
public IActionResult Privacy()

@ -36,14 +36,15 @@ namespace CSharpObjectJsonSchema.Models
[ScaffoldColumn(true)]
[MaxLength(10)]
[MinLength(2)]
[StringLength(5,MinimumLength =1)]
[Range(1,2)]
[StringLength(5, MinimumLength = 1)]
[Range(1, 2)]
[Required]
[RegularExpression("w+", ErrorMessage = "RegularExpression错误提示")]
[Remote("Action", "Controller", "test", AdditionalFields = "DateTimeValue,DateTimeValue2", ErrorMessage = "Remote错误提示", HttpMethod = "Get")]
public string StringValue { get; set; }
[Compare("StringValue")]
[StringLength(5)]
public string StringValue2 { get; set; }
public EnumTpye1 EnumValue { get; set; }

@ -7,6 +7,7 @@ using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Infrastructure.Web.Mvc
@ -96,6 +97,29 @@ namespace Infrastructure.Web.Mvc
return View(model);
}
[HttpPost]
public virtual IActionResult Delete(List<Guid> list)
{
if (list == null)
{
throw new ArgumentNullException(nameof(list));
}
try
{
foreach (var id in list)
{
var entity = _settingService.Table().FirstOrDefault(o => o.Id == id);
_settingService.DeleteSetting(entity);
}
return RedirectTo();
}
catch (DbUpdateException ex)
{
ex.PrintStack();
return RedirectTo(rawMesage: ex.Message);
}
}
public IActionResult Ajax(SettingType type)
{
return PartialView("_Ajax", new EditSettingModel { Type = type });

@ -18,26 +18,27 @@
<div class="pull-left">
@if (User.IsInRole($"Add-{entityName}"))
{
<a class="btn btn-primary" href="/Admin/Setting/Add">
<a class="btn btn-primary" href="@Url.Action("Add")">
新建
</a>
}
@if (User.IsInRole($"Edit-{entityName}"))
{
<a class="btn btn-primary" href="/Admin/Setting/Edit">
移除
</a>
}
@if (User.IsInRole($"Edit-{entityName}"))
{
<a class="btn btn-primary" href="/Admin/Setting/Edit">
还原
</a>
}
@*@if (User.IsInRole($"Edit-{entityName}"))
{
<button type="submit" class="confirm btn btn-primary" data-action="@Url.Action("Remove")">
移除
</button>
}
@if (User.IsInRole($"Edit-{entityName}"))
{
<button type="submit" class="confirm btn btn-primary" data-action="@Url.Action("Restore")">
还原
</button>
}*@
@if (User.IsInRole($"Delete-{entityName}"))
{
<a class="btn btn-danger" href="/Admin/Setting/Edit">删除</a>
}
<button type="submit" class="confirm btn btn-danger" data-action="@Url.Action("Delete")">
删除
</button>}
</div>
</div>
</div>

@ -132,7 +132,7 @@ namespace IoT.Shared.Services
private void InitConnection()
{
this._notifyHost = GetSetting("notify:host");
var url = $"http://{this._notifyHost}/hub?group={GetSetting("sn")}";
var url = $"{this._notifyHost}/hub?group={GetSetting("sn")}";
this._logger.LogDebug($"init connection for {url}");
if (this.Connection != null)
{

@ -17,9 +17,7 @@ namespace UserCenter.Controllers
{
private readonly IRepository<Scene> _sceneRepo;
public SceneController(IConfiguration cfg,
IRepository<Scene> sceneRepo,
IRepository<Device> deviceRepo)
public SceneController(IRepository<Scene> sceneRepo)
{
this._sceneRepo = sceneRepo;
}

@ -2,7 +2,6 @@
using Infrastructure.Data;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
@ -17,15 +16,12 @@ namespace UserCenter.Controllers
[ApiController]
public class SrsController : ControllerBase
{
private readonly IConfiguration _cfg;
private readonly IRepository<Device> _deviceRepo;
private readonly IRepository<LiveRecord> _liveRecordRepo;
public SrsController(IConfiguration cfg,
IRepository<Device> deviceRepo,
public SrsController(IRepository<Device> deviceRepo,
IRepository<LiveRecord> liveRecordRepo)
{
this._cfg = cfg;
this._deviceRepo = deviceRepo;
this._liveRecordRepo = liveRecordRepo;
}
@ -55,7 +51,7 @@ namespace UserCenter.Controllers
{
DeviceNumber = device.Number,
DeviceName = device?.DisplayName,
Name = $"回放{DateTime.Now.ToString("yyyy-MM-dd HH:mm")}",
Name = $"回放{DateTime.Now:yyyy-MM-dd HH:mm}",
Value = $"/video{result["file"].Substring(result["file"].LastIndexOf('/'))}"
});
this._liveRecordRepo.SaveChanges();

@ -167,7 +167,7 @@ namespace IoTCenter.Controllers
}
}
public IActionResult ExecApiAll(string connectionId, string method, string query, List<string> numbers)
public IActionResult ExecApiAll(string connectionId, string method, List<string> numbers)
{
try
{

@ -67,6 +67,7 @@ namespace IoTCenter
set.Add(new Setting { Name = "name", Value = "物联中心", Type = SettingType.Text });
set.Add(new Setting { Name = "logo", Value = "/images/logo.png", Type = SettingType.ImageUrl });
set.Add(new Setting { Name = "copyright", Value = "Copyright © {0} Company. All rights reserved", Type = SettingType.Html });
set.Add(new Setting { Name = "iosAppUrl", Value = "itms-services://?action=download-manifest&url=https://iot.edusoa.com/IoTCenter/Info.plist", Type = SettingType.Text });
//
var macAddress = Helper.Instance.GetMacAddress();
set.Add(new Setting { Name = "sn", Value = macAddress, Type = SettingType.Text });

@ -2,7 +2,7 @@
<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
<TargetLatestRuntimePatch>true</TargetLatestRuntimePatch>
<Version>1.0.0-beta.417</Version>
<Version>1.0.0-beta.420</Version>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\Infrastructure\Infrastructure.csproj" />

@ -3,6 +3,7 @@
var name = settingSerice.GetSetting("name").Value;
var logo = settingSerice.GetSetting("logo").Value;
var copyright = settingSerice.GetSetting("copyright").Value;
var iosAppUrl = settingSerice.GetSetting("iosAppUrl").Value;
}
<!DOCTYPE html>
<html>
@ -114,7 +115,7 @@
QRCode.toCanvas(document.getElementById('android_app'), androidUrl, {width:150}, function (error) {
if (error) console.error(error)
})
var iosUrl = 'itms-services://?action=download-manifest&url='+ location.protocol + '//' + location.host + '@Url.Content("~/Info.plist")';
var iosUrl = '@iosAppUrl'; 'itms-services://?action=download-manifest&url='+ location.protocol + '//' + location.host + '@Url.Content("~/Info.plist")';
QRCode.toCanvas(document.getElementById('ios_app'), iosUrl, { width: 150 },function (error) {
if (error) console.error(error)
})

@ -77,7 +77,7 @@ namespace IoTNode
var stream = "localhost";
set.Add(new Setting { Name = "debug", Value = "false" });
set.Add(new Setting { Name = "notify:enabled", Value = "true" });
set.Add(new Setting { Name = "notify:host", Value = $"{host}:8011" });
set.Add(new Setting { Name = "notify:host", Value = $"http://{host}:8011" });
set.Add(new Setting { Name = "timer.seconds", Value = "300" });
set.Add(new Setting { Name = "onvif.timer", Value = "1" });
set.Add(new Setting { Name = "onvif.speed", Value = "0.2" });

@ -2,7 +2,7 @@
<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
<TargetLatestRuntimePatch>true</TargetLatestRuntimePatch>
<Version>1.0.0-beta.414.3</Version>
<Version>1.0.0-beta.420</Version>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Hangfire.Core" Version="1.7.10" />

@ -4,11 +4,8 @@ using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Serilog;
using Serilog.Formatting.Json;
using Serilog.Sinks.Elasticsearch;
using Serilog.Sinks.RollingFile;
using Serilog.Sinks.InfluxDB;
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
@ -41,28 +38,25 @@ namespace StudyCenter
})
.ConfigureLogging((c, o) => //http://localhost:9200/_search?size=100
{
if (config.GetValue<bool>("useLogServer", false))
if (config.GetValue("useLogServer", false))
{
var url = c.Configuration["elasticsearch:url"];
Log.Logger = new LoggerConfiguration()
.WriteTo.Elasticsearch(new ElasticsearchSinkOptions(new Uri(url))
{
TypeName = "_doc",
AutoRegisterTemplate = true,
AutoRegisterTemplateVersion = AutoRegisterTemplateVersion.ESv7,
FailureCallback = e => Debug.WriteLine("Unable to submit event " + e.MessageTemplate),
EmitEventFailure = EmitEventFailureHandling.WriteToSelfLog |
EmitEventFailureHandling.WriteToFailureSink |
EmitEventFailureHandling.RaiseCallback,
FailureSink = new RollingFileSink("logs/log.txt", new JsonFormatter(), fileSizeLimitBytes: 100 * 1024 * 1024, 1)
})
.CreateLogger();
var connectionInfo = new InfluxDBConnectionInfo
{
Address = config["logserver:influxdb:address"],
Port = config.GetValue("logserver:influxdb:port", 8086),
DbName = config["logserver:influxdb:dbName"],
Username = config["logserver:influxdb:username"],
Password = config["logserver:influxdb:password"]
};
Log.Logger = new LoggerConfiguration().WriteTo.InfluxDB("iotcenter", connectionInfo).CreateLogger();
}
else
{
Log.Logger = new LoggerConfiguration().WriteTo.Console().CreateLogger();
}
o.AddSerilog();
Log.Logger.Information("start...");
})
.UseStartup<Startup>()
.Build()

Loading…
Cancel
Save