예제 #1
0
    async AsyncReply <T> Fetch <T>(string id) where T : IResource
    {
        if (resources.ContainsKey(id) && resources[id].IsAlive)
        {
            if (resources[id].Target is T)
            {
                return((T)resources[id].Target);// new AsyncReply<T>((T)resources[id].Target);
            }
            else
            {
                return(default(T));// new AsyncReply<T>(default(T)); ;
            }
        }

        var filter = Builders <BsonDocument> .Filter.Eq("_id", new BsonObjectId(new ObjectId(id)));

        var list = resourcesCollection.Find(filter).ToList();

        if (list.Count == 0)
        {
            return(default(T));// new AsyncReply<T>(default(T));
        }
        var document = list[0];

        var type = Type.GetType(document["classname"].AsString);

        if (type == null)
        {
            return(default(T));// new AsyncReply<T>(default(T));
        }
        IResource resource = (IResource)Activator.CreateInstance(ResourceProxy.GetProxy(type));

        //var iid = document["_id"].AsObjectId.ToString();
        if (resources.ContainsKey(id))
        {
            resources[id] = new WeakReference(resource);
        }
        else
        {
            resources.Add(id, new WeakReference(resource));
        }

        //@TODO this causes store.put to be invoked, need fix
        await Warehouse.Put(document["name"].AsString, resource, this);


        var parents  = document["parents"].AsBsonArray;
        var children = document["children"].AsBsonArray;
        //var managers = document["managers"].AsBsonArray;

        var attributes = Parse(document["attributes"]).Then(x =>
        {
            resource.Instance.SetAttributes(x as Map <string, object>);
        });

        // var bag = new AsyncBag<object>();

        resource.Instance.Variables.Add("children", children.Select(x => x.AsString).ToArray());
        resource.Instance.Variables.Add("parents", parents.Select(x => x.AsString).ToArray());

        // Apply store managers
        foreach (var m in this.Instance.Managers)
        {
            resource.Instance.Managers.Add(m);
        }

        /*
         * // load managers
         * foreach(var m in managers)
         * {
         *  IPermissionsManager pm = (IPermissionsManager)Activator.CreateInstance(Type.GetType(m["classname"].AsString));
         *  var sr = Parse(m["settings"]);
         *  bag.Add(sr);
         *  sr.Then((x) =>
         *  {
         *      pm.Initialize((Structure)x, resource);
         *      resource.Instance.Managers.Add(pm);
         *  });
         * }
         */

        // Load values
        var values = document["values"].AsBsonDocument;


        foreach (var v in values)
        {
            var valueInfo = v.Value as BsonDocument;

            var x = await Parse(valueInfo["value"]);

            resource.Instance.LoadProperty(v.Name,
                                           (ulong)valueInfo["age"].AsInt64,
                                           valueInfo["modification"].ToUniversalTime(),
                                           x);

            //bag.Add(av);
        }

        if (resource is T)
        {
            return((T)resource);
        }
        else
        {
            return(default(T));
        }
    }
예제 #2
0
    public static async AsyncReply <T> AddResourceAsync <T>(this DbSet <T> dbSet, T resource) where T : class, IResource
    {
        var store = dbSet.GetInfrastructure().GetService <IDbContextOptions>().FindExtension <EsiurExtensionOptions>().Store;

        if (store == null)
        {
            throw new Exception("Store not set, please call 'UseEsiur' on your DbContextOptionsBuilder.");
        }

        if (!store.Initialized)
        {
            throw new Exception("Store not initialized. Make sure the Warehouse is open");
        }

        var manager = store.Instance.Managers.FirstOrDefault();// > 0 ? store.Instance.Managers.First() : null;

        //var db = dbSet.GetService<ICurrentDbContext>().Context;

        //var resource = dbSet.GetInfrastructure().CreateResource<T>(properties);
        //var resource = Warehouse.New<T>("", options.Store, null, null, null, properties);

        var resType   = typeof(T);
        var proxyType = ResourceProxy.GetProxy(resType);


        IResource res;

        if (proxyType == resType)
        {
            res = resource;
        }
        else
        {
            res = Activator.CreateInstance(proxyType) as IResource;
            var ps = Map <string, object> .FromObject(resource);

            foreach (var p in ps)
            {
                var mi = resType.GetMember(p.Key, System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance)
                         .FirstOrDefault();

                if (mi != null)
                {
                    if (mi is PropertyInfo)
                    {
                        var pi = mi as PropertyInfo;
                        if (pi.CanWrite)
                        {
                            try
                            {
                                pi.SetValue(res, p.Value);
                            }
                            catch (Exception ex)
                            {
                                Global.Log(ex);
                            }
                        }
                    }
                    else if (mi is FieldInfo)
                    {
                        try
                        {
                            (mi as FieldInfo).SetValue(res, p.Value);
                        }
                        catch (Exception ex)
                        {
                            Global.Log(ex);
                        }
                    }
                }
            }
        }

        //await Warehouse.Put<T>("", null, null, null, null, properties);
        var entity = dbSet.Add((T)res);
        await entity.Context.SaveChangesAsync();

        var id = store.TypesByType[typeof(T)].PrimaryKey.GetValue(resource);

        await Warehouse.Put(id.ToString(), res, store, null, null, 0, manager);

        return((T)res);
    }
예제 #3
0
    public void ProcessModelFinalizing(IConventionModelBuilder modelBuilder, IConventionContext <IConventionModelBuilder> context)
    {
        foreach (var entityType in modelBuilder.Metadata.GetEntityTypes())
        {
            if (!Codec.ImplementsInterface(entityType.ClrType, typeof(IResource)))
            {
                continue;
            }

            var proxyType = ResourceProxy.GetProxy(entityType.ClrType);

            // var ann = entityType.GetAnnotation(CoreAnnotationNames.ConstructorBinding);

#pragma warning disable EF1001                                         // Internal EF Core API usage.
            var binding = ((EntityType)entityType).ConstructorBinding; // (InstantiationBinding)entityType[CoreAnnotationNames.ConstructorBinding];
#pragma warning restore EF1001                                         // Internal EF Core API usage.
            if (binding == null)
            {
                _directBindingConvention.ProcessModelFinalizing(modelBuilder, context);

#pragma warning disable EF1001                                         // Internal EF Core API usage.
                binding = ((EntityType)entityType).ConstructorBinding; // (InstantiationBinding)entityType[CoreAnnotationNames.ConstructorBinding];
#pragma warning restore EF1001                                         // Internal EF Core API usage.
            }

            try
            {
                var key = entityType.FindPrimaryKey().Properties.First();
                if (key == null)
                {
                    continue;
                }


                ((EntityType)entityType).SetConstructorBinding(
                    UpdateConstructorBindings(key, proxyType),
                    ConfigurationSource.Convention);

                binding = ((EntityType)entityType).ServiceOnlyConstructorBinding;
                if (binding != null)
                {
                    ((EntityType)entityType).SetServiceOnlyConstructorBinding(
                        UpdateConstructorBindings(key, proxyType),
                        ConfigurationSource.Convention);
                }


                //                entityType.SetAnnotation(
                //#pragma warning disable EF1001 // Internal EF Core API usage.
                //                        CoreAnnotationNames.ConstructorBinding,
                //#pragma warning restore EF1001 // Internal EF Core API usage.
                //                        new FactoryMethodBinding(
                //                        _createInstance,
                //                        new List<ParameterBinding>
                //                            {
                //                                new DependencyInjectionParameterBinding(typeof(IDbContextOptions), typeof(IDbContextOptions)),
                //                                new EntityTypeParameterBinding(),
                //                                //new PropertyParameterBinding(key)
                //                                // constructor arguments
                //                                //new ObjectArrayParameterBinding(binding.ParameterBindings),
                //                                 //new ContextParameterBinding(typeof(DbContext)),
                //                                 //new ObjectArrayParameterBinding(entityType.FindPrimaryKey().Properties.Select(x=>new PropertyParameterBinding(x)).ToArray())
                //                                 new ObjectArrayParameterBinding(new ParameterBinding[]{
                //                                            new PropertyParameterBinding(key) })
                //                            //})
                //                            // new Microsoft.EntityFrameworkCore.Metadata.ObjectArrayParameterBinding(),
                //                            //new ObjectArrayParameterBinding()

                //                        },
                //                        proxyType));
            }
            catch
            {
            }
        }
    }
예제 #4
0
    public static async AsyncReply <IResource> New(Type type, string name = null, IStore store = null, IResource parent = null, IPermissionsManager manager = null, object attributes = null, object properties = null)
    {
        type = ResourceProxy.GetProxy(type);


        /*
         * if (arguments != null)
         * {
         *  var constructors = type.GetConstructors(System.Reflection.BindingFlags.Public);
         *
         *  foreach(var constructor in constructors)
         *  {
         *      var pi = constructor.GetParameters();
         *      if (pi.Length == constructor.le)
         *  }
         *
         *  // cast arguments
         *  ParameterInfo[] pi = fi.GetParameters();
         *
         *  object[] args = new object[pi.Length];
         *
         *  for (var i = 0; i < pi.Length; i++)
         *  {
         *      if (pi[i].ParameterType == typeof(DistributedConnection))
         *      {
         *          args[i] = this;
         *      }
         *      else if (namedArgs.ContainsKey(pi[i].Name))
         *      {
         *          args[i] = DC.CastConvert(namedArgs[pi[i].Name], pi[i].ParameterType);
         *      }
         *  }
         *
         *  constructors[0].
         * }
         */
        var res = Activator.CreateInstance(type) as IResource;


        if (properties != null)
        {
            var ps = Map <string, object> .FromObject(properties);

            foreach (var p in ps)
            {
                var pi = type.GetProperty(p.Key, System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);
                if (pi != null)
                {
                    if (pi.CanWrite)
                    {
                        try
                        {
                            pi.SetValue(res, p.Value);
                        }
                        catch (Exception ex)
                        {
                            Global.Log(ex);
                        }
                    }
                }
                else
                {
                    var fi = type.GetField(p.Key, System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);
                    if (fi != null)
                    {
                        try
                        {
                            fi.SetValue(res, p.Value);
                        }
                        catch (Exception ex)
                        {
                            Global.Log(ex);
                        }
                    }
                }
            }
        }

        if (store != null || parent != null || res is IStore)
        {
            //if (!await Put(name, res, store, parent, null, 0, manager, attributes))
            //    return null;

            await Put(name, res, store, parent, null, 0, manager, attributes);
        }

        return(res);
    }