2
0
mirror of https://github.com/esiur/esiur-dotnet.git synced 2025-05-06 11:32:59 +00:00

HTTP+Entity

This commit is contained in:
Ahmed Zamil 2020-02-29 07:20:46 +03:00
parent fde1b1d8ad
commit 8bd9b3282c
9 changed files with 107 additions and 81 deletions

View File

@ -32,6 +32,8 @@ using System.Collections.Generic;
using System.Text;
using Microsoft.EntityFrameworkCore.Proxies;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Esyur.Proxy;
using System.Linq;
namespace Esyur.Stores.EntityCore
{
@ -69,9 +71,12 @@ namespace Esyur.Stores.EntityCore
}*/
public AsyncReply<IResource> Get(string path)
public async AsyncReply<IResource> Get(string path)
{
throw new NotImplementedException();
var p = path.Split('/');
var type = Options.Cache.Keys.Where(x => x.Name.ToLower() == p[0].ToLower()).FirstOrDefault();
var id = Convert.ToInt32(p[1]);
return DbContext.Find(type, id) as IResource;
}
public async AsyncReply<bool> Put(IResource resource)
@ -79,13 +84,22 @@ namespace Esyur.Stores.EntityCore
return true;
}
[Attribute]
public EsyurExtensionOptions Options { get; set; }
[Attribute]
public DbContext DbContext { get; set; }
public string Link(IResource resource)
{
var p = resource.GetType().GetProperty("Id");
if (p != null)
return this.Instance.Name + "/" + resource.GetType().Name + "/" + p.GetValue(resource);
var type = ResourceProxy.GetBaseType(resource.GetType());
var id = Options.Cache[type].GetValue(resource);
if (id != null)
return this.Instance.Name + "/" + type.Name + "/" + id.ToString();
else
return this.Instance.Name + "/" + resource.GetType().Name;
return this.Instance.Name + "/" + type.Name;
}
public bool Record(IResource resource, string propertyName, object value, ulong age, DateTime dateTime)

View File

@ -19,6 +19,7 @@
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="3.1.1.2" />
<PackageReference Include="System.Collections" Version="4.3.0" />
</ItemGroup>
<ItemGroup>

View File

@ -32,11 +32,24 @@ using Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal;
using Microsoft.EntityFrameworkCore.Utilities;
using Microsoft.EntityFrameworkCore.Proxies.Internal;
using System.Linq;
using Microsoft.EntityFrameworkCore.Metadata;
using System.Reflection;
using Esyur.Proxy;
namespace Esyur.Stores.EntityCore
{
public class EsyurExtensionOptions : IDbContextOptionsExtension
{
public Dictionary<Type, PropertyInfo> Cache { get; } = new Dictionary<Type, PropertyInfo>();
public void AddType(IEntityType type)
{
if (!Cache.ContainsKey(type.ClrType))
Cache.Add(type.ClrType, type.FindPrimaryKey().Properties[0].PropertyInfo);
}
private DbContextOptionsExtensionInfo _info;
EntityStore _store;
@ -64,7 +77,6 @@ namespace Esyur.Stores.EntityCore
throw new InvalidOperationException("");
}
}
//throw new NotImplementedException();
}
public EsyurExtensionOptions(EntityStore store)
@ -76,7 +88,6 @@ namespace Esyur.Stores.EntityCore
private sealed class ExtensionInfo : DbContextOptionsExtensionInfo
{
private string _logFragment;
public ExtensionInfo(IDbContextOptionsExtension extension)
: base(extension)
@ -90,23 +101,11 @@ namespace Esyur.Stores.EntityCore
public override string LogFragment => "Esyur";
// => _logFragment ??= Extension.UseLazyLoadingProxies && Extension.UseChangeDetectionProxies
// ? "using lazy-loading and change detection proxies "
// : Extension.UseLazyLoadingProxies
// ? "using lazy-loading proxies "
//: Extension.UseChangeDetectionProxies
//? "using change detection proxies "
//: "";
public override long GetServiceProviderHashCode() => 2312;//541;//2922;// Extension.UseProxies ? : 0;
public override long GetServiceProviderHashCode() => 2312;
public override void PopulateDebugInfo(IDictionary<string, string> debugInfo)
{
//debugInfo["Proxies:" + nameof(ProxiesExtensions.UseLazyLoadingProxies)]
// = (Extension._useLazyLoadingProxies ? 541 : 0).ToString(CultureInfo.InvariantCulture);
//debugInfo["Proxies:" + nameof(ProxiesExtensions.UseChangeDetectionProxies)]
// = (Extension._useChangeDetectionProxies ? 541 : 0).ToString(CultureInfo.InvariantCulture);
}
}

View File

@ -60,6 +60,7 @@ namespace Esyur.Stores.EntityCore
}
public static DbContextOptionsBuilder UseEsyur(this DbContextOptionsBuilder optionsBuilder,
DbContext context,
string name = null,
IResource parent = null,
IPermissionsManager manager = null
@ -70,8 +71,11 @@ namespace Esyur.Stores.EntityCore
if (extension == null)
{
var store = Warehouse.New<EntityStore>(name, null, parent, manager);
extension = new EsyurExtensionOptions(store);
store.Options = extension;
store.DbContext = context;
}
((IDbContextOptionsBuilderInfrastructure)optionsBuilder).AddOrUpdateExtension(extension);
@ -82,6 +86,7 @@ namespace Esyur.Stores.EntityCore
public static DbContextOptionsBuilder<TContext> UseEsyur<TContext>(
this DbContextOptionsBuilder<TContext> optionsBuilder,
DbContext context,
string name = null,
IResource parent = null,
IPermissionsManager manager = null)
@ -95,6 +100,8 @@ namespace Esyur.Stores.EntityCore
{
var store = Warehouse.New<EntityStore>(name, null, parent, manager);
extension = new EsyurExtensionOptions(store);
store.Options = extension;
store.DbContext = context;
}

View File

@ -67,6 +67,9 @@ namespace Esyur.Stores.EntityCore
ILazyLoader loader,
object[] constructorArguments)
{
//var key = entityType.FindPrimaryKey();
options.AddType(entityType);
var manager = options.Store.Instance.Managers.Count > 0 ? options.Store.Instance.Managers.First() : null;
return Warehouse.New(entityType.ClrType, "", options.Store, null, manager);
}

View File

@ -57,7 +57,12 @@ namespace Esyur.Misc
public static event LogEvent SystemLog;
static Random random = new Random();
public static string Version { get; }= FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location).FileVersion;
//FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(assembly.Location);
// string version = fvi.FileVersion;
/*
@ -419,7 +424,7 @@ namespace Esyur.Misc
//var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789~!@#$%^&*()_-+=\\?/";
var result = new string(
Enumerable.Repeat(chars, length)
.Select(s => s[random.Next(s.Length)])
.Select(s => s[rand.Next(s.Length)])
.ToArray());
//if (result.Length < length)
// Console.WriteLine();

View File

@ -121,7 +121,7 @@ namespace Esyur.Net.HTTP
Response.Headers["Sec-WebSocket-Protocol"] = Request.Headers["Sec-WebSocket-Protocol"];
Response.Number = HTTPResponsePacket.ResponseCode.HTTP_SWITCHING;
Response.Number = HTTPResponsePacket.ResponseCode.Switching;
Response.Text = "Switching Protocols";
WSMode = true;
@ -253,7 +253,7 @@ namespace Esyur.Net.HTTP
if (!File.Exists(filename))
{
Response.Number = HTTPResponsePacket.ResponseCode.HTTP_NOTFOUND;
Response.Number = HTTPResponsePacket.ResponseCode.NotFound;
Send("File Not Found");
return true;
}
@ -267,8 +267,8 @@ namespace Esyur.Net.HTTP
var ims = DateTime.Parse(Request.Headers["if-modified-since"]);
if (Math.Abs((fileEditTime - ims).TotalSeconds) < 0)
{
Response.Number = HTTPResponsePacket.ResponseCode.HTTP_NOTMODIFIED;
Response.Text = "Not Modified";
Response.Number = HTTPResponsePacket.ResponseCode.NotModified;
//Response.Text = "Not Modified";
Send((byte[])null);
}
}
@ -280,7 +280,7 @@ namespace Esyur.Net.HTTP
Response.Number = HTTPResponsePacket.ResponseCode.HTTP_OK;
Response.Number = HTTPResponsePacket.ResponseCode.OK;
// Fri, 30 Oct 2007 14:19:41 GMT
Response.Headers["Last-Modified"] = fileEditTime.ToString("ddd, dd MMM yyyy HH:mm:ss");
FileInfo fi = new FileInfo(filename);

View File

@ -231,7 +231,7 @@ namespace Esyur.Net.HTTP
if (resource.Execute(sender))
return;
sender.Response.Number = HTTPResponsePacket.ResponseCode.HTTP_SERVERERROR;
sender.Response.Number = HTTPResponsePacket.ResponseCode.InternalServerError;
sender.Send("Bad Request");
sender.Close();
}

View File

@ -43,16 +43,29 @@ namespace Esyur.Net.Packets
public enum ResponseCode : int
{
HTTP_SWITCHING = 101,
HTTP_OK = 200,
HTTP_NOTFOUND = 404,
HTTP_SERVERERROR = 500,
HTTP_MOVED = 301,
HTTP_NOTMODIFIED = 304,
HTTP_REDIRECT = 307
Switching= 101,
OK = 200,
Created = 201,
Accepted = 202,
NoContent = 204,
MovedPermanently = 301,
Found = 302,
SeeOther = 303,
NotModified = 304,
TemporaryRedirect = 307,
BadRequest = 400,
Unauthorized = 401,
Forbidden = 403,
NotFound = 404,
MethodNotAllowed = 405,
NotAcceptable = 406,
PreconditionFailed = 412,
UnsupportedMediaType = 415,
InternalServerError = 500,
NotImplemented = 501,
}
public class HTTPCookie
public struct HTTPCookie
{
public string Name;
public string Value;
@ -61,46 +74,45 @@ namespace Esyur.Net.Packets
public bool HttpOnly;
public string Domain;
public HTTPCookie(string Name, string Value)
public HTTPCookie(string name, string value)
{
this.Name = Name;
this.Value = Value;
this.Name = name;
this.Value = value;
this.Path = null;
this.Expires = DateTime.MinValue;
this.HttpOnly = false;
this.Domain = null;
}
public HTTPCookie(string Name, string Value, DateTime Expires)
public HTTPCookie(string name, string value, DateTime expires)
{
this.Name = Name;
this.Value = Value;
this.Expires = Expires;
this.Name = name;
this.Value = value;
this.Expires = expires;
this.HttpOnly = false;
this.Domain = null;
this.Path = null;
}
public override string ToString()
{
//Set-Cookie: ckGeneric=CookieBody; expires=Sun, 30-Dec-2001 21:00:00 GMT; domain=.com.au; path=/
//Set-Cookie: SessionID=another; expires=Fri, 29 Jun 2006 20:47:11 UTC; path=/
string Cookie = Name + "=" + Value;
var cookie = Name + "=" + Value;
if (Expires.Ticks != 0)
{
Cookie += "; expires=" + Expires.ToUniversalTime().ToString("ddd, dd MMM yyyy HH:mm:ss") + " GMT";
}
cookie += "; expires=" + Expires.ToUniversalTime().ToString("ddd, dd MMM yyyy HH:mm:ss") + " GMT";
if (Domain != null)
{
Cookie += "; domain=" + Domain;
}
cookie += "; domain=" + Domain;
if (Path != null)
{
Cookie += "; path=" + Path;
}
cookie += "; path=" + Path;
if (HttpOnly)
{
Cookie += "; HttpOnly";
}
cookie += "; HttpOnly";
return Cookie;
return cookie;
}
}
@ -110,15 +122,9 @@ namespace Esyur.Net.Packets
public byte[] Message;
public ResponseCode Number;
public string Text;
//public DStringDictionary Cookies;
public List<HTTPCookie> Cookies = new List<HTTPCookie>();
public bool Handled;
//public bool ResponseHandled; //flag this as true if you are handling it yourself
//private bool createSession;
//private HTTPServer Server;
//public HTTPSession Session;
public override string ToString()
{
@ -129,31 +135,22 @@ namespace Esyur.Net.Packets
+ "\n\tMessage: " + (Message != null ? Message.Length.ToString() : "NULL");
}
private string MakeHeader(ComposeOptions Options)
private string MakeHeader(ComposeOptions options)
{
string header = Version + " " + (int)Number + " " + Text + "\r\n"
+ "Server: Delta Web Server\r\n"
//Fri, 30 Oct 2007 14:19:41 GMT"
+ "Date: " + DateTime.Now.ToUniversalTime().ToString("r") + "\r\n";
string header = $"{Version} {(int)Number} {Text}\r\nServer: Esyur {Global.Version}\r\nDate: {DateTime.Now.ToUniversalTime().ToString("r")}\r\n";
if (Options == ComposeOptions.AllCalculateLength && Message != null)
{
if (options == ComposeOptions.AllCalculateLength && Message != null)
Headers["Content-Length"] = Message.Length.ToString();
}
foreach (var kv in Headers)
{
header += kv.Key + ": " + kv.Value + "\r\n";
}
// Set-Cookie: ckGeneric=CookieBody; expires=Sun, 30-Dec-2007 21:00:00 GMT; path=/
// Set-Cookie: ASPSESSIONIDQABBDSQA=IPDPMMMALDGFLMICEJIOCIPM; path=/
foreach (var Cookie in Cookies)
{
header += "Set-Cookie: " + Cookie.ToString() + "\r\n";
}
header += "\r\n";