Example #1
0
 /// <summary>
 /// Method invoked <i>instead</i> of the <c>Get</c> semantic of the field or property to which the current aspect is applied,
 /// i.e. when the value of this field or property is retrieved.
 /// </summary>
 /// <param name="args">Advice arguments.</param>
 public override void OnGetValue(LocationInterceptionArgs args)
 {
     args.ProceedGetValue();
     if (args.Value == null)
     {
         if (string.IsNullOrEmpty(this.Token))
         {
             if (string.IsNullOrEmpty(this.TokenProperty))
             {
                 args.Value = IoC.Get(args.Location.LocationType);
             }
             else
             {
                 object value = ObjectProxyFactory.Get(args.Instance).GetValue(args.Instance, this.TokenProperty);
                 if (value == null)
                 {
                     args.Value = IoC.Get(args.Location.LocationType);
                 }
                 else
                 {
                     args.Value = IoC.Get(args.Location.LocationType, value.ToString());
                 }
             }
         }
         else
         {
             args.Value = IoC.Get(args.Location.LocationType, this.Token);
         }
         args.ProceedSetValue();
     }
 }
Example #2
0
        public void TestObjectProxyFactoryFromMap()
        {
            // Normal Test
            Dictionary <string, object> map = new Dictionary <string, object>();

            map.Add("Id", 7L);
            map.Add("Name", "test");
            TestClass1 instance = ObjectProxyFactory.FromMap <TestClass1>(map);

            Assert.AreEqual(7L, instance.Id);
            Assert.AreEqual("test", instance.Name);
            // Lower case test
            map = new Dictionary <string, object>();
            map.Add("id", 7L);
            map.Add("name", "test");
            instance = ObjectProxyFactory.FromMap <TestClass1>(map);
            Assert.AreEqual(7L, instance.Id);
            Assert.AreEqual("test", instance.Name);
            // Convert types test
            map = new Dictionary <string, object>();
            map.Add("id", "7");
            map.Add("name", "test");
            instance = ObjectProxyFactory.FromMap <TestClass1>(map);
            Assert.AreEqual(7L, instance.Id);
            Assert.AreEqual("test", instance.Name);
        }
Example #3
0
        public Message Get(Message message)
        {
            MessageInformation information = new MessageInformation(message);

            try
            {
                string           sessionToken    = this.GetSessionToken(information);
                MessagePath      path            = new MessagePath(information);
                ISecurityManager securityManager = IoC.Get <ISecurityManager>();
                object           response;
                if (path.IsByParent)
                {
                    MessagePath parentPath = new MessagePath(information, true);
                    if (!parentPath.HasKeyParameter)
                    {
                        throw new ArgumentException("A link to a parent must have parameter key");
                    }
                    dynamic      bo     = securityManager.DynamicGetBO(parentPath.DtoType, sessionToken);
                    object       parent = bo.GetOne(string.Empty, parentPath.QueryInfo);
                    IObjectProxy proxy  = ObjectProxyFactory.Get(parent);
                    object       value  = proxy.GetValue(parent, path.ParentKeyParameter);
                    QueryInfo    query  = new QueryInfo();
                    query.Equal(path.KeyParameterName, value.ToString());
                    bo       = securityManager.DynamicGetBO(path.DtoType, sessionToken);
                    response = bo.GetOne(string.Empty, query);
                }
                else
                {
                    dynamic bo = securityManager.DynamicGetBO(path.DtoType, sessionToken);
                    if (path.HasKeyParameter)
                    {
                        response = bo.GetOne(string.Empty, path.QueryInfo);
                    }
                    else
                    {
                        response = bo.GetAll(path.QueryInfo);
                    }
                }
                IServiceConfiguration  configuration = IoC.Get <IServiceConfiguration>();
                JsonSerializerSettings settings      = IoC.Get <JsonSerializerSettings>();
                if (configuration.IsHateoas)
                {
                    response = this.ConvertToHateoas(response, configuration, path);
                }
                return(response.ToJsonMessage(settings, configuration.Indented));
            }
            catch (Exception ex)
            {
                if (ex is TargetInvocationException)
                {
                    return(ex.InnerException.Message.ToJsonMessage());
                }
                else
                {
                    return(ex.Message.ToJsonMessage());
                }
            }
        }
Example #4
0
        public void TestObjectProxyFactoryToStringMap()
        {
            TestClass1 instance             = new TestClass1(7L, "test");
            Dictionary <string, string> map = ObjectProxyFactory.ToStringMap(instance);

            Assert.IsNotNull(map);
            Assert.AreEqual(2, map.Count);
            Assert.AreEqual("7", map["Id"]);
            Assert.AreEqual("test", map["Name"]);
        }
Example #5
0
        /// <summary>
        /// Fills target object from source object, taking into account th fields to be avoided.
        /// </summary>
        /// <param name="source">The source.</param>
        /// <param name="target">The target.</param>
        public void FillUpdate(object source, object target)
        {
            IObjectProxy proxy = ObjectProxyFactory.GetByType(this.EntityType);

            foreach (IMetamodelField field in this.Fields)
            {
                if (!field.AvoidUpdate)
                {
                    proxy.SetValue(target, field.Name, proxy.GetValue(source, field.Name));
                }
            }
        }
Example #6
0
        public static void ClassInit(TestContext context)
        {
            ObjectProxyFactory.ConfigureMappers();
            IList <string> sourceNames = new List <string>();
            IList <string> targetNames = new List <string>();

            sourceNames.Add("Id");
            sourceNames.Add("Name");
            targetNames.Add("ObjectId");
            targetNames.Add("NameTxt");
            ObjectProxyFactory.CreateMap(typeof(TestClass1), typeof(TestClass3), sourceNames, targetNames);
        }
Example #7
0
        public void TestObjectProxyFactoryMap()
        {
            TestClass1 source = new TestClass1(7L, "hola");
            TestClass3 target = ObjectProxyFactory.MapTo <TestClass3>(source);

            Assert.AreEqual(source.Id, target.ObjectId);
            Assert.AreEqual(source.Name, target.NameTxt);
            TestClass1 newSource = ObjectProxyFactory.MapTo <TestClass1>(target);

            Assert.AreEqual(source.Id, newSource.Id);
            Assert.AreEqual(source.Name, newSource.Name);
        }
        public void FactoryCreatesAnObjectOfTheOnlineProxyType()
        {
            Request request = new Request();

            request.OnlineProxyType = typeof(MockProxy);

            ObjectProxyFactory factory = new ObjectProxyFactory();


            object proxy = factory.GetOnlineProxy(request, "Network");

            Assert.IsNotNull(proxy);
            Assert.AreEqual(typeof(MockProxy), proxy.GetType());
        }
Example #9
0
        /// <summary>
        /// Gets one DTO.
        /// </summary>
        /// <param name="pk">The pk.</param>
        /// <param name="info"></param>
        /// <returns></returns>
        public TDto GetOne(string pk, QueryInfo info)
        {
            if (this.BeforeGetOne != null)
            {
                this.BeforeGetOne(this, new BOEventArgs <TDto>(pk, info, default(TDto), default(TDto), null, null));
            }
            TDto result = ObjectProxyFactory.MapTo <TDto>(this.GetEntityOne(pk, info));

            if (this.AfterGetOne != null)
            {
                this.AfterGetOne(this, new BOEventArgs <TDto>(pk, info, default(TDto), result, null, null));
            }
            return(result);
        }
Example #10
0
        /// <summary>
        /// Given a source type, clones the type but only the common type properties.
        /// </summary>
        /// <param name="sourceType">Type of the source.</param>
        /// <param name="domain">The domain.</param>
        /// <param name="assemblyNameStr">The assembly name string.</param>
        /// <param name="dynamicModuleName">Name of the dynamic module.</param>
        /// <param name="typeName">Name of the type.</param>
        /// <returns></returns>
        public static Type CloneCommonType(Type sourceType, AppDomain domain, string assemblyNameStr, string dynamicModuleName, string typeName)
        {
            TypeBuilder  typeBuilder = TypeBuilderHelper.GetClassTypeBuilder(domain, assemblyNameStr, dynamicModuleName, typeName);
            IObjectProxy entityProxy = ObjectProxyFactory.GetByType(sourceType);

            foreach (PropertyInfo propertyInfo in entityProxy.Properties)
            {
                if (TypesManager.IsCommonType(propertyInfo.PropertyType))
                {
                    TypeBuilderHelper.AddProperty(typeBuilder, propertyInfo.Name, propertyInfo.PropertyType);
                }
            }
            return(typeBuilder.CreateType());
        }
Example #11
0
        /// <summary>
        /// Gets all the DTOs.
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        public IList <TDto> GetAll(QueryInfo info)
        {
            if (this.BeforeGetAll != null)
            {
                this.BeforeGetAll(this, new BOEventArgs <TDto>(null, info, default(TDto), default(TDto), null, null));
            }
            IList <TDto> result = ObjectProxyFactory.MapToList <TDto>(this.GetEntityAll(info));

            if (this.AfterGetAll != null)
            {
                this.AfterGetAll(this, new BOEventArgs <TDto>(null, info, default(TDto), default(TDto), result, null));
            }
            return(result);
        }
Example #12
0
        /// <summary>
        /// Gets the object key.
        /// </summary>
        /// <param name="entity">The entity.</param>
        /// <returns></returns>
        public ObjectKey GetObjectKey(object entity)
        {
            List <KeyValuePair <string, object> > keyPairs = new List <KeyValuePair <string, object> >();
            IObjectProxy proxy = ObjectProxyFactory.GetByType(this.EntityType);

            foreach (IMetamodelField field in this.Fields)
            {
                if (field.IsPrimaryKey)
                {
                    keyPairs.Add(new KeyValuePair <string, object>(field.Name, proxy.GetValue(entity, field.Name)));
                }
            }
            return(new ObjectKey(this.EntityType.Name, keyPairs));
        }
Example #13
0
        public void TestObjectProxyFactoryGetProxy()
        {
            IObjectProxy proxy1 = ObjectProxyFactory.Get <TestClass1>();

            Assert.IsNotNull(proxy1);
            Assert.AreEqual(typeof(TestClass1), proxy1.ProxyType);
            IObjectProxy proxy2 = ObjectProxyFactory.GetByType(typeof(TestClass1));

            Assert.AreSame(proxy1, proxy2);
            TestClass1   instance = new TestClass1();
            IObjectProxy proxy3   = ObjectProxyFactory.Get(instance);

            Assert.AreSame(proxy1, proxy3);
        }
Example #14
0
 /// <summary>
 /// Adds from object.
 /// </summary>
 /// <param name="instance">The instance.</param>
 public void AddFromObject(object instance)
 {
     if (instance != null)
     {
         IObjectProxy proxy = ObjectProxyFactory.Get(instance);
         foreach (string propertyName in proxy.PropertyNames)
         {
             object value = proxy.GetValue(instance, propertyName);
             if (value != null)
             {
                 this.AddAttribute(propertyName, value);
             }
         }
     }
 }
Example #15
0
        /// <summary>
        /// Updates one DTO.
        /// </summary>
        /// <param name="src">The source.</param>
        /// <returns></returns>
        public TDto Update(TDto src)
        {
            object entity = ObjectProxyFactory.MapTo(this.EntityType, src);

            if (this.BeforeUpdate != null)
            {
                this.BeforeUpdate(this, new BOEventArgs <TDto>(null, null, src, default(TDto), null, entity));
            }
            TDto result = ObjectProxyFactory.MapTo <TDto>(this.UpdateEntity(entity));

            if (this.AfterUpdate != null)
            {
                this.AfterUpdate(this, new BOEventArgs <TDto>(null, null, src, result, null, entity));
            }
            return(result);
        }
Example #16
0
        /// <summary>
        /// Registers a pair entity and dto.
        /// </summary>
        /// <param name="entityType">Type of the entity.</param>
        /// <param name="dtoType">Type of the dto.</param>
        public IMetamodelEntity RegisterEntity(Type entityType, Type dtoType)
        {
            IMetamodelEntity metamodelEntity = this.GetEntity(entityType);

            if (metamodelEntity == null)
            {
                metamodelEntity = new MetamodelEntity(entityType);
                this.RegisterEntity(metamodelEntity);
            }
            metamodelEntity.AddDto(dtoType);
            if (this.dtoMap.ContainsKey(dtoType))
            {
                this.dtoMap[dtoType] = metamodelEntity;
            }
            else
            {
                this.dtoMap.Add(dtoType, metamodelEntity);
            }
            string lowname = dtoType.Name.ToLower();

            if (this.dtoNameMap.ContainsKey(lowname))
            {
                this.dtoNameMap[lowname] = metamodelEntity;
            }
            else
            {
                this.dtoNameMap.Add(lowname, metamodelEntity);
            }
            IObjectProxy   proxy       = ObjectProxyFactory.GetByType(dtoType);
            IList <string> sourceNames = new List <string>();
            IList <string> targetNames = new List <string>();

            foreach (PropertyInfo property in proxy.Properties)
            {
                DtoFieldAttribute attribute = property.GetCustomAttribute <DtoFieldAttribute>();
                if (attribute != null)
                {
                    metamodelEntity.AddFieldMap(dtoType, attribute.Name, property.Name);
                    sourceNames.Add(attribute.Name);
                    targetNames.Add(property.Name);
                }
            }

            ObjectProxyFactory.CreateMap(entityType, dtoType, sourceNames, targetNames);
            return(metamodelEntity);
        }
Example #17
0
 /// <summary>
 /// Logins a user into the system.
 /// </summary>
 /// <param name="login">The login.</param>
 /// <param name="password">The password.</param>
 /// <returns></returns>
 /// <exception cref="System.ArgumentException">Login invalid</exception>
 public IUserDto Login(string login, string password)
 {
     using (OpenAccessContext context = this.NewContext())
     {
         object user = this.GetUserByLoginPass(context, login, password);
         if (user == null)
         {
             throw new ArgumentException("Login invalid");
         }
         IUserDto result = (IUserDto)ObjectProxyFactory.MapTo(this.UserDtoType, user);
         result.Password     = null;
         result.SessionToken = this.SessionManager.NewSessionToken();
         this.SessionManager.AddSessionForUser(context, result.UserId.Value, result.SessionToken);
         context.SaveChanges();
         return(result);
     }
 }
        public void FactoryCallTheSpecifiedMethod()
        {
            Request request = new Request();

            request.MethodName      = "CalledMethod";
            request.OnlineProxyType = typeof(MockProxy);


            ObjectProxyFactory factory = new ObjectProxyFactory();

            MockProxy proxy = (MockProxy)factory.GetOnlineProxy(request, "Network");

            Exception exception = null;

            factory.CallOnlineProxyMethod(proxy, request, ref exception);

            Assert.IsTrue(proxy.MethodCalled);
        }
Example #19
0
        public void TestObjectProxyFactoryToListStringMap()
        {
            IList <TestClass1> list1 = new List <TestClass1>();

            list1.Add(new TestClass1(1L, "name1"));
            list1.Add(new TestClass1(2L, "name2"));
            list1.Add(new TestClass1(3L, "name3"));

            IList <Dictionary <string, string> > table = ObjectProxyFactory.ToListStringMap(list1);

            Assert.IsNotNull(table);
            for (int i = 1; i <= 3; i++)
            {
                Dictionary <string, string> row = table[i - 1];
                Assert.IsNotNull(row);
                Assert.AreEqual(2, row.Count);
                Assert.AreEqual(i.ToString(), row["Id"]);
                Assert.AreEqual("name" + i.ToString(), row["Name"]);
            }
        }
Example #20
0
 /// <summary>
 /// Initializes a new instance of the <see cref="BaseSecurityManager"/> class.
 /// </summary>
 /// <param name="contextType">Type of the context.</param>
 /// <param name="userDtoType">Type of the user dto.</param>
 /// <param name="fileName">Name of the file.</param>
 public BaseSecurityManager(Type contextType, Type userDtoType, Type entityType)
 {
     this.ContextType = contextType;
     this.UserDtoType = userDtoType;
     ObjectProxyFactory.CreateMap(userDtoType, entityType);
     this.SessionManager = IoC.Get <ISessionManager>();
     if (this.SessionManager == null)
     {
         this.SessionManager = new MemorySessionManager();
         IoC.Register <ISessionManager>(this.SessionManager);
     }
     this.AuditManager = IoC.Get <IAuditManager>();
     if (this.AuditManager == null)
     {
         this.AuditManager = new EmptyAuditManager();
         IoC.Register <IAuditManager>(this.AuditManager);
     }
     this.BOManager        = new BOManager();
     this.MetamodelManager = new MetamodelManager();
 }
Example #21
0
        /// <summary>
        /// Gets the string key.
        /// </summary>
        /// <param name="entity">The entity.</param>
        /// <returns></returns>
        public string GetStringKey(object entity)
        {
            IObjectProxy  proxy = ObjectProxyFactory.GetByType(this.EntityType);
            int           i     = 0;
            StringBuilder sb    = new StringBuilder();

            foreach (IMetamodelField field in this.Fields)
            {
                if (field.IsPrimaryKey)
                {
                    if (i > 0)
                    {
                        sb.Append("!");
                    }
                    sb.Append(proxy.GetValue(entity, field.Name).ToString());
                    i++;
                }
            }
            return(sb.ToString());
        }
Example #22
0
        /// <summary>
        /// Gets the user information.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="sessionToken">The session token.</param>
        /// <returns></returns>
        protected virtual IUserDto GetUserInfo(OpenAccessContext context, string sessionToken)
        {
            ISessionDto sessionData = this.SessionManager.GetSessionData(context, sessionToken);

            if (sessionData == null)
            {
                return(null);
            }
            object user = this.GetUserById(context, sessionData.UserId);

            if (user == null)
            {
                this.SessionManager.RemoveSession(context, sessionToken);
                context.SaveChanges();
                return(null);
            }
            IUserDto result = (IUserDto)ObjectProxyFactory.MapTo(this.UserDtoType, user);

            result.Password     = null;
            result.SessionToken = sessionData.SessionToken;
            return(result);
        }
Example #23
0
        /// <summary>
        /// Configures the Security Manager from a file.
        /// </summary>
        /// <param name="fileName">Name of the file.</param>
        public virtual void Configure(string fileName)
        {
            MetadataContainer metadata = this.GetOpenAccessMetadata();
            Dictionary <string, MetaPersistentType> metatables = this.GetMetaTables(metadata);
            XmlDocument document = null;

            if (!string.IsNullOrEmpty(fileName))
            {
                document = XmlResources.GetFromResource(fileName);
                if (document == null)
                {
                    document = XmlResources.GetFromEmbeddedResource(fileName);
                }
            }
            if (document != null)
            {
                ObjectProxyFactory.ConfigureMappers(document);
                XmlNode rootNode = document.SelectSingleNode("configuration/entities");
                if (rootNode != null)
                {
                    this.ConfigureEntities(rootNode, metatables);
                }
            }
            else
            {
                this.Scanner = new SecurityScanner(this);
                this.Scanner.EntityPreffix = string.Empty;
                this.Scanner.EntitySuffix  = string.Empty;
                this.Scanner.DtoPreffix    = string.Empty;
                this.Scanner.DtoSuffix     = "Dto";
                this.Scanner.FilterPreffix = string.Empty;
                this.Scanner.FilterSuffix  = "Filter";
                this.Scanner.BOPreffix     = string.Empty;
                this.Scanner.BOSuffix      = "BO";
                this.Scanner.Metatables    = metatables;
                this.Scanner.ScanNamespace(string.Empty);
            }
        }
Example #24
0
        public void ShoulInterceptOnlyPrivateMethod()
        {
            var privateMethodName = ObjectProxyHelper.GetMethodNames <IPrivateMethod>(i => i.SaveChanges())[0];

            var proxy = ObjectProxyFactory
                        .Configure <IPrivateMethod>(new DbFileContext()) //initialize fluent config, with given interface and instance
                        .FilterMethods(privateMethodName)                //only intercept methods with the given name
                        .AddPreDecoration(ctx =>
            {
                Debug.Assert(ctx.CallCtx.MethodName == privateMethodName);
                Console.Write("Saving Changes");
            })
                        .AddPostDecoration(ctx =>
            {
                Console.Write("Saved Changes");
                Debug.Assert(ctx.CallCtx.MethodName == privateMethodName);
            })
                                        //.SetParameters(new object())
                        .CreateProxy(); //finally create and return the proxy


            proxy.SaveChanges();
        }
Example #25
0
 /// <summary>
 /// Gets the object key by pk.
 /// </summary>
 /// <param name="pk">The pk.</param>
 /// <returns></returns>
 public ObjectKey GetObjectKeyByPk(string pk)
 {
     string[] tokens = pk.Split('!');
     if (tokens.Length == 1)
     {
         return(new ObjectKey(this.EntityType.Name, pk));
     }
     else
     {
         List <KeyValuePair <string, object> > keyPairs = new List <KeyValuePair <string, object> >();
         int          i     = 0;
         IObjectProxy proxy = ObjectProxyFactory.GetByType(this.EntityType);
         foreach (IMetamodelField field in this.Fields)
         {
             if (field.IsPrimaryKey)
             {
                 keyPairs.Add(new KeyValuePair <string, object>(field.Name, this.ChangeType(tokens[i], proxy.GetPropertyType(field.Name))));
                 i++;
             }
         }
         return(new ObjectKey(this.EntityType.Name, keyPairs));
     }
 }
Example #26
0
        private static void Main()
        {
            IEmployee employee = new Employee(1, "John", "Smith", new DateTime(1990, 4, 1));

            var tpCheckRight = ObjectProxyFactory.CreateProxy(
                employee, new[] { "Salary" }, new Decoration(UserRightCheck), null);
            var tpLogCheckRight = ObjectProxyFactory.CreateProxy(
                tpCheckRight, new[] { "Salary", "FullName" }, new Decoration(EnterLog), new Decoration(ExitLog));

            // Используем отражение для декорации всех методов: var ifaceMethods = typeof (IEmployee).GetMethods().Select(info => info.Name);

            try
            {
                tpLogCheckRight.FullName();
                Console.WriteLine();
                tpLogCheckRight.Salary();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            Console.Read();
        }
Example #27
0
        public void RunLoopProxyfied()
        {
            var dbContext = new DbFileContext();

            var privateMethodName = ObjectProxyHelper.GetMethodNames <IPrivateMethod>(j => j.SaveChanges())[0];


            var proxy = ObjectProxyFactory
                        .Configure <IPrivateMethod>(dbContext) //initialize fluent config, with given interface and instance
                        .FilterMethods(privateMethodName)      //only intercept methods with the given name
                        .CreateProxy();                        //finally create and return the proxy

            var sw = Stopwatch.StartNew();

            for (int i = 0; i < 1000; i++)
            {
                int i1 = i;
                Console.Write(i1);
                proxy.SaveChanges();
            }

            Console.WriteLine("took {0}", sw.Elapsed.ToString("g"));
            Console.ReadLine();
        }
Example #28
0
        public void TestObjectProxyFactoryFromListStringMap()
        {
            IList <Dictionary <string, string> > table = new List <Dictionary <string, string> >();

            for (int i = 1; i <= 3; i++)
            {
                Dictionary <string, string> item = new Dictionary <string, string>();
                item.Add("Id", i.ToString());
                item.Add("Name", "name" + i.ToString());
                table.Add(item);
            }

            IList <TestClass1> list = ObjectProxyFactory.FromListStringMap <TestClass1>(table);

            Assert.IsNotNull(list);
            Assert.AreEqual(3, list.Count);
            for (int i = 1; i <= 3; i++)
            {
                TestClass1 item = list[i - 1];
                Assert.IsNotNull(item);
                Assert.AreEqual(i, item.Id);
                Assert.AreEqual("name" + i.ToString(), item.Name);
            }
        }
Example #29
0
 /// <summary>
 /// Initializes a new instance of the <see cref="BaseSessionManager"/> class.
 /// </summary>
 /// <param name="entityType">Type of the entity.</param>
 /// <param name="sessionDtoType">Type of the session dto.</param>
 public BaseSessionManager(Type entityType, Type sessionDtoType)
 {
     this.sessionDtoType = sessionDtoType;
     ObjectProxyFactory.CreateMap(entityType, this.sessionDtoType);
 }
Example #30
0
        /// <summary>
        /// Gets the session data.
        /// </summary>
        /// <param name="context">The database context.</param>
        /// <param name="sessionToken">The session token.</param>
        /// <returns></returns>
        /// <exception cref="System.NotImplementedException"></exception>
        public ISessionDto GetSessionData(OpenAccessContext context, string sessionToken)
        {
            object session = this.GetSessionByToken(context, sessionToken);

            return(session == null ? null : (ISessionDto)ObjectProxyFactory.MapTo(this.sessionDtoType, session));
        }