111 lines
2.8 KiB
C#
111 lines
2.8 KiB
C#
using System;
|
|
using System.IO;
|
|
using System.Net.Http;
|
|
using Microsoft.SqlServer.Server;
|
|
using Newtonsoft.Json;
|
|
using Newtonsoft.Json.Linq;
|
|
|
|
// ReSharper disable CheckNamespace
|
|
namespace BITKit
|
|
// ReSharper restore CheckNamespace
|
|
{
|
|
public record ContextModel:IBinarySerialize
|
|
|
|
{
|
|
public static ContextModel Get(object data)
|
|
{
|
|
return new ContextModel()
|
|
{
|
|
StatusCode = 200,
|
|
Message = "success",
|
|
Data = data
|
|
};
|
|
}
|
|
|
|
public static ContextModel Error(string message)
|
|
{
|
|
return new ContextModel()
|
|
{
|
|
StatusCode = 500,
|
|
Message = message,
|
|
Data = false
|
|
};
|
|
}
|
|
|
|
public static ContextModel GetFromJson(string json)
|
|
{
|
|
try
|
|
{
|
|
var result = new ContextModel();
|
|
var jObject = JObject.Parse(json);
|
|
if (jObject.TryGetValue("status_code", out var statusCode))
|
|
result.StatusCode = statusCode.Value<int>();
|
|
if (jObject.TryGetValue("message", out var message))
|
|
result.Message = message.Value<string>();
|
|
if (jObject.TryGetValue("data", out var data))
|
|
result.Data = data;
|
|
return JsonConvert.DeserializeObject<ContextModel>(json);
|
|
}
|
|
catch (Exception)
|
|
{
|
|
BIT4Log.Warning(json);
|
|
throw;
|
|
}
|
|
}
|
|
|
|
public static implicit operator string(ContextModel self)
|
|
{
|
|
return self.ToString();
|
|
}
|
|
#if NET5_0_OR_GREATER
|
|
public static implicit operator HttpContent(ContextModel self)
|
|
{
|
|
return new StringContent(self, System.Text.Encoding.UTF8, "application/json");
|
|
}
|
|
#endif
|
|
|
|
public override string ToString()
|
|
{
|
|
return JsonConvert.SerializeObject(this);
|
|
}
|
|
|
|
[JsonProperty("status_code")] public int StatusCode = 200;
|
|
[JsonProperty("message")] public string Message = string.Empty;
|
|
[JsonProperty("data")] public object Data = string.Empty;
|
|
[JsonIgnore] public bool IsSuccess => StatusCode is 200 or 0;
|
|
|
|
public bool TryAs<T>(out T value)
|
|
{
|
|
switch (Data)
|
|
{
|
|
case T t:
|
|
value = t;
|
|
return true;
|
|
case JToken jToken:
|
|
value = jToken.ToObject<T>();
|
|
return true;
|
|
default:
|
|
value = default;
|
|
return false;
|
|
}
|
|
}
|
|
|
|
public void Read(BinaryReader r)
|
|
{
|
|
StatusCode = r.ReadInt32();
|
|
Message = r.ReadString();
|
|
Data = r.ReadBoolean() ? BITBinary.Read(r) : null;
|
|
}
|
|
|
|
public void Write(BinaryWriter w)
|
|
{
|
|
w.Write(StatusCode);
|
|
w.Write(Message);
|
|
w.Write(Data is not null);
|
|
if (Data is not null)
|
|
{
|
|
BITBinary.Write(w, Data);
|
|
}
|
|
}
|
|
}
|
|
} |