private static RootClass CreateMappingClasses()
        {
            var classMapping     = new RootClass();
            var componentMapping = new NHibernate.Mapping.Component(classMapping);

            var componentPropertyMapping = new Property(componentMapping);

            componentPropertyMapping.Name = "ComponentPropertyInClass";
            classMapping.AddProperty(componentPropertyMapping);

            var stringValue = new SimpleValue();

            stringValue.TypeName = typeof(string).FullName;

            var stringPropertyInComponentMapping = new Property(stringValue);

            stringPropertyInComponentMapping.Name = "StringPropertyInComponent";
            componentMapping.AddProperty(stringPropertyInComponentMapping);

            var componentType = (IAbstractComponentType)componentMapping.Type;

            Assume.That(CascadeStyle.None == stringPropertyInComponentMapping.CascadeStyle);
            Assume.That(CascadeStyle.None == componentType.GetCascadeStyle(0));
            Assume.That(CascadeStyle.None == componentPropertyMapping.CascadeStyle);

            return(classMapping);
        }
Ejemplo n.º 2
0
        public void Tests()
        {
            var root = new RootClass();

            Assert.Null(root.Name);
            root.Name = "Root";

            var propertyChanged = 0;

            root.OnNotify.Add(p =>
            {
                propertyChanged++;
            });


            Assert.Equal("Root.NumericClass.IntProperty", root.NumericClass.IntProperty.FullName);

            Assert.NotEmpty(root.ChangedProperties());
            Assert.Equal(4, root.ChangedProperties().Count());

            Assert.Empty(root.ChangedProperties().Where(i => i.TimeStamp != DateTime.MinValue));

            root.NumericClass.DoubleProperty.Value = 4711;
            Assert.Equal(1, propertyChanged);

            Assert.Single(root.ChangedProperties().Where(i => i.TimeStamp != DateTime.MinValue));

            foreach (var item in root.ChangedProperties())
            {
                WriteLine(item.ToChangeString(false));
                WriteLine(item.ToChangeString(true));
            }
        }
        public void GetFieldValue_InferType_Lazy_ReturnsConcrete()
        {
            //Assign
            Item             item     = _db.GetItem(_item2Path);
            SitecoreProperty property = AttributeConfigurationLoader.GetProperty(typeof(RootClass).GetProperty("LazyLoadedInferred"));

            _handler.ConfigureDataHandler(property);
            RootClass root = new RootClass();


            //Act
            var result = _handler.GetFieldValue(
                item.ID.ToString(),
                item,
                _service);

            root.LazyLoadedInferred = result as EmptyTemplate1;

            //Assert
            Assert.IsNotNull(root.LazyLoadedInferred);
            Assert.AreNotEqual(typeof(EmptyTemplate1), root.LazyLoadedInferred.GetType());
            Assert.AreNotEqual(typeof(EmptyTemplate2), root.LazyLoadedInferred.GetType());
            //the type is inferred so should be EmptyTemplate2
            Assert.IsTrue(root.LazyLoadedInferred is EmptyTemplate2);
        }
Ejemplo n.º 4
0
        public void Bind(HbmClass classSchema, IDictionary <string, MetaAttribute> inheritedMetas)
        {
            var rootClass = new RootClass();

            BindClass(classSchema, rootClass, inheritedMetas);
            // OPTIMISTIC LOCK MODE
            rootClass.OptimisticLockMode = classSchema.optimisticlock.ToOptimisticLock();

            inheritedMetas = GetMetas(classSchema, inheritedMetas, true);             // get meta's from <class>

            //TABLENAME
            string schema    = classSchema.schema ?? mappings.SchemaName;
            string catalog   = classSchema.catalog ?? mappings.CatalogName;
            string tableName = GetClassTableName(rootClass, classSchema);

            if (string.IsNullOrEmpty(tableName))
            {
                throw new MappingException(
                          string.Format(
                              "Could not determine the name of the table for entity '{0}'; remove the 'table' attribute or assign a value to it.",
                              rootClass.EntityName));
            }

            Table table = mappings.AddTable(schema, catalog, tableName, classSchema.Subselect, rootClass.IsAbstract.GetValueOrDefault(), classSchema.schemaaction);

            ((ITableOwner)rootClass).Table = table;

            log.Info("Mapping class: {0} -> {1}", rootClass.EntityName, rootClass.Table.Name);

            rootClass.IsMutable = classSchema.mutable;
            rootClass.Where     = classSchema.where ?? rootClass.Where;

            if (classSchema.check != null)
            {
                table.AddCheckConstraint(classSchema.check);
            }

            rootClass.IsExplicitPolymorphism = classSchema.polymorphism == HbmPolymorphismType.Explicit;

            BindCache(classSchema.cache, rootClass);
            new ClassIdBinder(Mappings).BindId(classSchema.Id, rootClass, table);
            new ClassCompositeIdBinder(Mappings).BindCompositeId(classSchema.CompositeId, rootClass);
            new ClassDiscriminatorBinder(rootClass, Mappings).BindDiscriminator(classSchema.discriminator, table);
            BindTimestamp(classSchema.Timestamp, rootClass, table, inheritedMetas);
            BindVersion(classSchema.Version, rootClass, table, inheritedMetas);

            rootClass.CreatePrimaryKey();
            BindNaturalId(classSchema.naturalid, rootClass, inheritedMetas);
            new PropertiesBinder(mappings, rootClass).Bind(classSchema.Properties, inheritedMetas);

            BindJoins(classSchema.Joins, rootClass, inheritedMetas);
            BindSubclasses(classSchema.Subclasses, rootClass, inheritedMetas);
            BindJoinedSubclasses(classSchema.JoinedSubclasses, rootClass, inheritedMetas);
            BindUnionSubclasses(classSchema.UnionSubclasses, rootClass, inheritedMetas);

            new FiltersBinder(rootClass, Mappings).Bind(classSchema.filter);

            mappings.AddClass(rootClass);
        }
Ejemplo n.º 5
0
 private static void BindCache(HbmCache cacheSchema, RootClass rootClass)
 {
     if (cacheSchema != null)
     {
         rootClass.CacheConcurrencyStrategy = GetXmlEnumAttribute(cacheSchema.usage);
         rootClass.CacheRegionName          = cacheSchema.region;
     }
 }
Ejemplo n.º 6
0
 private static void BindCache(HbmCache cacheSchema, RootClass rootClass)
 {
     if (cacheSchema != null)
     {
         rootClass.CacheConcurrencyStrategy = cacheSchema.usage.ToCacheConcurrencyStrategy();
         rootClass.CacheRegionName          = cacheSchema.region;
     }
 }
Ejemplo n.º 7
0
 /// <summary>
 /// Creates a tree with its root
 /// </summary>
 /// <param name="id">Id of the root</param>
 /// <param name="title">Title of the node</param>
 /// <param name="data">Data for the node</param>
 public Tree(string id, string title, T data = null)
 {
     Root = new RootClass
     {
         id    = id,
         title = title,
         data  = data
     };
 }
Ejemplo n.º 8
0
 private static void BindCache(HbmCache cacheSchema, RootClass rootClass)
 {
     if (cacheSchema != null)
     {
         rootClass.CacheConcurrencyStrategy = cacheSchema.usage.ToCacheConcurrencyStrategy();
         rootClass.CacheRegionName          = cacheSchema.region;
         rootClass.SetLazyPropertiesCacheable(cacheSchema.include == HbmCacheInclude.All);
     }
 }
Ejemplo n.º 9
0
        public void GetJsonStringTest_Null()
        {
            var obj =
                new
                {
                    X =
                        new RootClass()
                        {
                            A = "Jeffrey",
                            B = 31,
                            C = null,
                            ElementClassA = new ElementClass() { A = "Jeffrey", B = null },
                            ElementClassB = null
                        },
                    Y = new
                    {
                        O = "0",
                        Z = (string)null
                    }
                };

            var obj2 = new RootClass()
            {
                A = "Jeffrey",
                B = 31,
                C = null,
                ElementClassA = new ElementClass() { A = "Jeffrey", B = null },
                ElementClassB = null
            };

            var obj3 = new RootClass()
            {
                A = "Jeffrey",
                B = 31,
                C = null,
                ElementClassA = new ElementClass() { A = "Jeffrey", B = null },
                ElementClassB = null,
                ElementClass2 = new ElementClass2()
                {
                    A = "A"
                }
            };

            DateTime dt1 = DateTime.Now;
            SerializerHelper js = new SerializerHelper();

            var json = js.GetJsonString(obj, new JsonSetting(true, new List<string>(new[] { "Z", "C" })));
            Console.WriteLine(json);

            var json2 = js.GetJsonString(obj2, new JsonSetting(true, new List<string>(new[] { "B" })));
            Console.WriteLine(json2);

            var json3 = js.GetJsonString(obj3, new JsonSetting(true, null, new List<Type>(new[] { typeof(ElementClass2) })));
            Console.WriteLine(json3);

            Console.WriteLine((DateTime.Now - dt1).TotalMilliseconds);
        }
 public void Example1()
 {
     var subscriber = Logger.CreateSubscriber(VerboseLevel.All);
     subscriber.NewLogMessage += subscriber_Log;
     var c = new RootClass();
     c.A.WriteMessage();
     c.B.WriteMessage();
     c.C.WriteMessage();
     c.WriteMessage();
 }
Ejemplo n.º 11
0
    public void DeepCloneTest(DeepCloneMethod method)
    {
        Where();

        DeepClone_ConstructorCount = 0;

        RootClass a = new RootClass();

        a.Int1 = Util.RandSInt31();
        a.Str1 = a.Int1.ToString();

        a.Test1 = new ElementClass2("Hello");
        a.Test2 = new ElementClass2("Hello");
        a.Test3 = a.Test2;

        a.Test1.TestList = new List <ElementClass2>();
        a.Test1.TestList.Add(a.Test2);

        a.Test2.TestList = new List <ElementClass2>();
        a.Test2.TestList.Add(a.Test1);

        int tmp = Util.RandSInt31();

        a._GetFieldReaderWriter(true).SetValue(a, "Int2", tmp);
        a._GetFieldReaderWriter(true).SetValue(a, "Str2", tmp.ToString());

        a.Dict = new Dictionary <int, ElementClass>();

        a.Element = new ElementClass {
            Int1 = 1, Str1 = "Hello", Root = null
        };

        a.Element.Element2 = new ElementClass2("Neko");

        for (int i = 0; i < 1000; i++)
        {
            ElementClass e = new ElementClass();
            e.Int1 = Util.RandSInt31();
            e.Str1 = e.Int1.ToString();

            e._GetFieldReaderWriter(true).SetValue(e, "Int2", tmp);
            e._GetFieldReaderWriter(true).SetValue(e, "Str2", tmp.ToString());

            e.Root = a;

            a.Dict.Add(i, e);
        }

        DeepClone_ConstructorCount = 0;

        RootClass b = a._CloneDeep(method);

        Assert.False(object.ReferenceEquals(b.Test1, b.Test2));
        Assert.True(object.ReferenceEquals(b.Test2, b.Test3));
        Assert.True(object.ReferenceEquals(b.Test1 !.TestList ![0], b.Test2));
Ejemplo n.º 12
0
        public void Example1()
        {
            var subscriber = Logger.CreateSubscriber(VerboseLevel.All);

            subscriber.NewLogMessage += subscriber_Log;
            var c = new RootClass();

            c.A.WriteMessage();
            c.B.WriteMessage();
            c.C.WriteMessage();
            c.WriteMessage();
        }
    public string GetResourceFilePath()
    {
        string assemblyName = Assembly.GetExecutingAssembly().FullName;

        assemblyName = assemblyName.Substring(0, assemblyName.IndexOf(','));
        string myFilePath = GetRealClassPath();
        //If base class is in the root directory, this could just be replaced by string projectFolder = GetFilePathLoc();
        string projectFolder = RootClass.GetPath();

        //Remove the "absolute part" of the path
        myFilePath = myFilePath.Substring(projectFolder.Length);
        return("/" + assemblyName + ",component/" + myFilePath);
    }
        private static void AssertDeserializedMappingClasses(RootClass deserializedClassMapping)
        {
            var deserializedComponentPropertyMapping         = deserializedClassMapping.GetProperty("ComponentPropertyInClass");
            var deserializedComponentMapping                 = (NHibernate.Mapping.Component)deserializedComponentPropertyMapping.Value;
            var deserializedComponentType                    = (IAbstractComponentType)deserializedComponentMapping.Type;
            var deserializedStringPropertyInComponentMapping = deserializedComponentMapping.GetProperty("StringPropertyInComponent");

            // Must be all the same objects since CascadeStyles are singletons and are
            // compared with "==" and "!=" operators.
            Assert.AreSame(CascadeStyle.None, deserializedStringPropertyInComponentMapping.CascadeStyle);
            Assert.AreSame(CascadeStyle.None, deserializedComponentType.GetCascadeStyle(0));
            Assert.AreSame(CascadeStyle.None, deserializedComponentPropertyMapping.CascadeStyle);
        }
Ejemplo n.º 15
0
 public static void SetGuidToUniqueWithDefaultValue(NHibernate.Cfg.Configuration config)
 {
     foreach (PersistentClass @class in config.ClassMappings)
     {
         RootClass rootClass = @class.RootClazz;
         Table     table     = rootClass.Table;
         foreach (Column column in table.ColumnIterator.Where(column => column.Name == "Guid"))
         {
             column.IsUnique     = true;
             column.DefaultValue = "newid()";
         }
     }
 }
Ejemplo n.º 16
0
        public string Translate(string from, string to, string source)
        {
            String    currentUrl = String.Format(TRANSLATE_URL, languageMapDict[from], languageMapDict[to], source);
            WebClient webClient  = new WebClient();
            String    ret        = webClient.DownloadString(currentUrl);
            RootClass obj        = Newtonsoft.Json.JsonConvert.DeserializeObject <RootClass>(ret);

            if (obj == null || obj.trans_result == null || obj.trans_result.data == null)
            {
                return(null);
            }
            return(obj.trans_result.data[0].dst);
        }
 public static String getAddressfromGoogle(double lat, double lon)
 {
     try
     {
         WebClient webClient            = new WebClient();
         var       jsonData             = webClient.DownloadData("http://maps.googleapis.com/maps/api/geocode/json?latlng=" + lat + "," + lon + "&sensor=true");
         DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(RootClass));
         RootClass rootObject           = (RootClass)ser.ReadObject(new MemoryStream(jsonData));
         return(rootObject.results[0].formatted_address);
     } catch (InvalidPluginExecutionException ex)
     {
         throw new Exception("GetAddress.getAddressfromGoogle()" + ex.Message + ex.StackTrace + ex.Source);
     }
 }
Ejemplo n.º 18
0
        public static object DefaultRootClassHashInput(RootClass rootClass)
        {
            // This is the standard enumeration done for the EntityMetamodel
            // constructor to build *all* properties (including properties that
            // refer to collections).
            var serialized = new List <Tuple <string, string> >(rootClass.PropertyClosureSpan);

            foreach (var property in rootClass.PropertyClosureIterator)
            {
                serialized.Add(Tuple.Create(property.Name, property.Type.ToString()));
            }

            return(serialized);
        }
Ejemplo n.º 19
0
        public void Bind(XmlNode node, HbmClass classSchema, IDictionary <string, MetaAttribute> inheritedMetas)
        {
            RootClass rootClass = new RootClass();

            BindClass(node, classSchema, rootClass, inheritedMetas);
            inheritedMetas = GetMetas(classSchema, inheritedMetas, true);             // get meta's from <class>

            //TABLENAME
            string schema    = classSchema.schema ?? mappings.SchemaName;
            string catalog   = classSchema.catalog ?? mappings.CatalogName;
            string tableName = GetClassTableName(rootClass, classSchema);

            if (string.IsNullOrEmpty(tableName))
            {
                throw new MappingException(
                          string.Format(
                              "Could not determine the name of the table for entity '{0}'; remove the 'table' attribute or assign a value to it.",
                              rootClass.EntityName));
            }

            Table table = mappings.AddTable(schema, catalog, tableName, null, rootClass.IsAbstract.GetValueOrDefault(), classSchema.schemaaction);

            ((ITableOwner)rootClass).Table = table;

            log.InfoFormat("Mapping class: {0} -> {1}", rootClass.EntityName, rootClass.Table.Name);

            rootClass.IsMutable = classSchema.mutable;
            rootClass.Where     = classSchema.where ?? rootClass.Where;

            if (classSchema.check != null)
            {
                table.AddCheckConstraint(classSchema.check);
            }

            rootClass.IsExplicitPolymorphism = classSchema.polymorphism == HbmPolymorphismType.Explicit;

            BindCache(classSchema.cache, rootClass);
            new ClassIdBinder(this).BindId(classSchema.Id, rootClass, table);
            new ClassCompositeIdBinder(this).BindCompositeId(classSchema.CompositeId, rootClass);
            new ClassDiscriminatorBinder(this).BindDiscriminator(classSchema.discriminator, rootClass, table);
            BindTimestamp(classSchema.Timestamp, rootClass, table, inheritedMetas);
            BindVersion(classSchema.Version, rootClass, table, inheritedMetas);

            rootClass.CreatePrimaryKey(dialect);

            PropertiesFromXML(node, rootClass, inheritedMetas);
            mappings.AddClass(rootClass);
        }
Ejemplo n.º 20
0
        static void Main(string[] args)
        {
            string      path;
            string      inputPath  = "../../Config/";
            string      outputPath = "../../Output/";
            XmlDocument doc        = new XmlDocument();

            string[] files = Directory.GetFiles(inputPath);
            for (int i = 0; i < files.Length; ++i)
            {
                path = files[i];
                doc.Load(path);

                RootClass data = RootClassParser.Parse(doc.FirstChild);
                break; //!!!
            }
        }
Ejemplo n.º 21
0
        private static RootClass GetTestObject()
        {
            var @object = new RootClass
            {
                StringProperty = "Root String Value",
                DateProperty   = new DateTime(2012, 3, 31, 16, 27, 55),
                Child          = new ChildClass
                {
                    IntegerProperty = 23,
                    StringProperty  = "Child String Value",
                    DecimalProperty = 12.5m,
                    DoubleProperty  = 23.45,
                    BooleanProperty = false
                }
            };

            return(@object);
        }
        public void ValidatesObjectRecursively()
        {
            var root = new RootClass();
            var validationContext = new ValidationContext(root);
            var validationResults = new List <ValidationResult>();

            // Validate recursively
            Assert.False(RecursiveValidator.TryValidateObject(root, validationContext, validationResults));
            Assert.Equal(6, validationResults.Count);
            Assert.Contains(validationResults, r => r.MemberNames.FirstOrDefault() == nameof(RootClass.SomeString));
            Assert.Contains(validationResults, r => r.MemberNames.FirstOrDefault() == $"{nameof(RootClass.SingleChild)}.{nameof(ChildClass.SomeOtherString)}");
            Assert.Contains(validationResults,
                            r => r.MemberNames.FirstOrDefault() == $"{nameof(RootClass.SingleChild)}.{nameof(ChildClass.NestedItems)}[0].{nameof(ChildItem.SomeOtherOtherString)}");
            Assert.Contains(validationResults,
                            r => r.MemberNames.FirstOrDefault() == $"{nameof(RootClass.SingleChild)}.{nameof(ChildClass.NestedItems)}[1].{nameof(ChildItem.SomeOtherOtherString)}");
            Assert.Contains(validationResults, r => r.MemberNames.FirstOrDefault() == $"{nameof(RootClass.Items)}[0].{nameof(ChildItem.SomeOtherOtherString)}");
            Assert.Contains(validationResults, r => r.MemberNames.FirstOrDefault() == $"{nameof(RootClass.Items)}[1].{nameof(ChildItem.SomeOtherOtherString)}");
        }
Ejemplo n.º 23
0
        public void Execute()
        {
            var rt = RuntimeTypeModel.Create();

            rt.Add(typeof(IEnumerableClass), true);
            rt.Add(typeof(RootClass), true);
            rt.Compile();
            var c1 = new IEnumerableClass()
            {
                Prop1 = 1, Prop2 = "a"
            };
            var i1 = new RootClass()
            {
                Prop1 = 1, Prop2 = "blabla", Prop3 = c1
            };
            var cloned = rt.DeepClone(i1) as RootClass;

            Assert.Equal(1, cloned.Prop3.Prop1);
        }
Ejemplo n.º 24
0
        private void AppendComputedVersion(RootClass rootClass, HashAlgorithm hashAlgorithm, Queue <Action> actionQueue)
        {
            var isCacheDisabled = String.IsNullOrEmpty(rootClass.CacheConcurrencyStrategy);

            if (isCacheDisabled)
            {
                return;
            }

            var hashInput = getRootClassHashInput(rootClass);
            var hash      = Hash(hashAlgorithm, hashInput);

            actionQueue.Enqueue(() =>
            {
                var oldCacheRegionName = rootClass.CacheRegionName;
                var newCacheRegionName = formatRegionName(oldCacheRegionName, hash);
                onChanges.ForEach(x => x(oldCacheRegionName, newCacheRegionName, hash));

                rootClass.CacheRegionName = newCacheRegionName;
            });
        }
        public void GetFieldValue_InvalidData_ReturnsNull()
        {
            //Assign
            //Assign
            Item             item     = _db.GetItem(_item1Path);
            SitecoreProperty property = AttributeConfigurationLoader.GetProperty(typeof(RootClass).GetProperty("LazyLoaded"));

            _handler.ConfigureDataHandler(property);
            RootClass root = new RootClass();

            //Act
            var result = _handler.GetFieldValue(
                "random value",
                item,
                _service);

            root.LazyLoaded = result as EmptyTemplate1;

            //Assert
            Assert.IsNull(root.LazyLoaded);
        }
        public void GetFieldValue_IsLazyFalse_ReturnsConcrete()
        {
            //Assign
            Item             item     = _db.GetItem(_item1Path);
            SitecoreProperty property = AttributeConfigurationLoader.GetProperty(typeof(RootClass).GetProperty("NotLazyLoaded"));

            _handler.ConfigureDataHandler(property);
            RootClass root = new RootClass();


            //Act
            var result = _handler.GetFieldValue(
                item.ID.ToString(),
                item,
                _service);

            root.LazyLoaded = result as EmptyTemplate1;

            //Assert
            Assert.IsNotNull(root.LazyLoaded);
            //should not be equal because of proxy class
            Assert.AreEqual(typeof(EmptyTemplate1), root.LazyLoaded.GetType());
        }
Ejemplo n.º 27
0
 public static object DefaultRootClassSerializer(RootClass rootClass)
 {
     return(DefaultRootClassHashInput(rootClass));
 }
        private static RootClass GetTestObject()
        {
            var @object = new RootClass
            {
                StringProperty = "Root String Value",
                DateProperty = new DateTime(2012, 3, 31, 16, 27, 55),
                Child = new ChildClass
                {
                    IntegerProperty = 23,
                    StringProperty = "Child String Value",
                    DecimalProperty = 12.5m,
                    DoubleProperty = 23.45,
                    BooleanProperty = false
                }

            };
            return @object;
        }
Ejemplo n.º 29
0
        public void GetJsonStringTest_Null()
        {
            var obj =
                new
            {
                X =
                    new RootClass()
                {
                    A             = "Jeffrey",
                    B             = 31,
                    C             = null,
                    ElementClassA = new ElementClass()
                    {
                        A = "Jeffrey", B = null
                    },
                    ElementClassB = null
                },
                Y = new
                {
                    O = "0",
                    Z = (string)null
                }
            };

            var obj2 = new RootClass()
            {
                A             = "Jeffrey",
                B             = 31,
                C             = null,
                ElementClassA = new ElementClass()
                {
                    A = "Jeffrey", B = null
                },
                ElementClassB = null
            };

            var obj3 = new RootClass()
            {
                A             = "Jeffrey",
                B             = 31,
                C             = null,
                ElementClassA = new ElementClass()
                {
                    A = "Jeffrey", B = null
                },
                ElementClassB = null,
                ElementClass2 = new ElementClass2()
                {
                    A = "A"
                }
            };

            DateTime         dt1 = DateTime.Now;
            SerializerHelper js  = new SerializerHelper();

            var json = js.GetJsonString(obj, new JsonSetting(true, new List <string>(new[] { "Z", "C" })));

            Console.WriteLine(json);

            var json2 = js.GetJsonString(obj2, new JsonSetting(true, new List <string>(new[] { "B" })));

            Console.WriteLine(json2);

            var json3 = js.GetJsonString(obj3, new JsonSetting(true, null, new List <Type>(new[] { typeof(ElementClass2) })));

            Console.WriteLine(json3);

            Console.WriteLine((DateTime.Now - dt1).TotalMilliseconds);
        }
Ejemplo n.º 30
0
        public void Bind(System.Type entity)
        {
            var rootClass = new RootClass();

            BindClass(entity, rootClass);
        }
        public void GetFieldValue_IsLazyFalse_ReturnsConcrete()
        {
            //Assign
            Item item = _db.GetItem(_item1Path);
            SitecoreProperty property = AttributeConfigurationLoader.GetProperty(typeof(RootClass).GetProperty("NotLazyLoaded"));

            _handler.ConfigureDataHandler(property);
            RootClass root = new RootClass();


            //Act
            var result = _handler.GetFieldValue(
                item.ID.ToString(),
                item,
                _service);

            root.LazyLoaded = result as EmptyTemplate1;

            //Assert
            Assert.IsNotNull(root.LazyLoaded);
            //should not be equal because of proxy class
            Assert.AreEqual(typeof(EmptyTemplate1), root.LazyLoaded.GetType());
        }
        public void GetFieldValue_InvalidData_ReturnsNull()
        {
            //Assign
            //Assign
            Item item = _db.GetItem(_item1Path);
            SitecoreProperty property = AttributeConfigurationLoader.GetProperty(typeof(RootClass).GetProperty("LazyLoaded"));

            _handler.ConfigureDataHandler(property);
            RootClass root = new RootClass();
            
            //Act
            var result = _handler.GetFieldValue(
                "random value",
                item,               
                _service);

            root.LazyLoaded = result as EmptyTemplate1;

            //Assert
            Assert.IsNull(root.LazyLoaded);
        }
Ejemplo n.º 33
0
 public CtrDependentChildClass(RootClass x) : base(x)
 {
     Xs.Add(x);
 }
        public void GetJsonStringTest_Null()
        {
            var obj =
                new
            {
                X =
                    new RootClass()
                {
                    A             = "Jeffrey",
                    B             = 31,
                    C             = null,
                    ElementClassA = new ElementClass()
                    {
                        A = "Jeffrey", B = null
                    },
                    ElementClassB = null
                },
                Y = new
                {
                    O = "0",
                    Z = (string)null
                }
            };


            DateTime dt1 = SystemTime.Now;

            {
                //不进行任何设置,返回原始JSON
                var json = SerializerHelper.GetJsonString(obj, jsonSetting: null);
                Console.WriteLine(json);
                var exceptedJson = "{\"X\":{\"A\":\"Jeffrey\",\"B\":31,\"C\":null,\"ElementClassA\":{\"A\":\"Jeffrey\",\"B\":null,\"RootClass\":null},\"ElementClassB\":null,\"ElementClass2\":null},\"Y\":{\"O\":\"0\",\"Z\":null}}";
                Assert.AreEqual(exceptedJson, json);
            }


            {
                //不忽略任何属性
                var json = SerializerHelper.GetJsonString(obj, new JsonSetting(false));
                Console.WriteLine(json);
                var exceptedJson = "{\"X\":{\"A\":\"Jeffrey\",\"B\":31,\"ElementClassA\":{\"A\":\"Jeffrey\",\"B\":null,\"RootClass\":null},\"ElementClassB\":null,\"ElementClass2\":null},\"Y\":{\"O\":\"0\",\"Z\":null}}";
                Assert.AreEqual(exceptedJson, json);
            }

            {
                //忽略所有为null的属性
                var json = SerializerHelper.GetJsonString(obj, new JsonSetting(true));
                Console.WriteLine(json);
                var exceptedJson = "{\"X\":{\"A\":\"Jeffrey\",\"B\":31,\"ElementClassA\":{\"A\":\"Jeffrey\"}},\"Y\":{\"O\":\"0\"}}";
                Assert.AreEqual(exceptedJson, json);


                var obj2 = new RootClass()
                {
                    A             = "Jeffrey",
                    B             = 31,
                    C             = null,
                    ElementClassA = new ElementClass()
                    {
                        A = "Jeffrey", B = null
                    },
                    ElementClassB = null
                };

                var json2 = SerializerHelper.GetJsonString(obj2,
                                                           new JsonSetting(true, new List <string>(new[] { "B" })));

                var exceptedJson2 = "{\"A\":\"Jeffrey\",\"B\":31,\"ElementClassA\":{\"A\":\"Jeffrey\"}}";
                Console.WriteLine(json2);
                Assert.AreEqual(exceptedJson2, json2);
            }

            {
                //忽略特定为null的属性
                var json = SerializerHelper.GetJsonString(obj,
                                                          new JsonSetting(false, new List <string>(new[] { "Z" })));//Z属性会被忽略
                Console.WriteLine(json);
                var exceptedJson = "{\"X\":{\"A\":\"Jeffrey\",\"B\":31,\"ElementClassA\":{\"A\":\"Jeffrey\",\"B\":null,\"RootClass\":null},\"ElementClassB\":null,\"ElementClass2\":null},\"Y\":{\"O\":\"0\"}}";
                Assert.AreEqual(exceptedJson, json);
            }

            {
                //忽略特定值测试(忽略特定值,以及忽略null)
                var obj4 = new RootClass()
                {
                    A             = "IGNORE",//会被忽略
                    B             = 31,
                    C             = null,
                    ElementClassA = null,
                    ElementClassB = null,
                    ElementClass2 = null
                };
                var json = SerializerHelper.GetJsonString(obj4, new JsonSetting(true));//Z属性会被忽略
                Console.WriteLine(json);
                var exceptedJson = "{\"B\":31}";
                Assert.AreEqual(exceptedJson, json);
            }

            {
                //忽略特定值测试(只忽略特定值,不忽略null)
                var obj4 = new RootClass()
                {
                    A             = "IGNORE",//会被忽略
                    B             = 31,
                    C             = null,
                    ElementClassA = null,
                    ElementClassB = null,
                    ElementClass2 = null
                };
                var json = SerializerHelper.GetJsonString(obj4, new JsonSetting(false));//Z属性会被忽略
                Console.WriteLine(json);
                var exceptedJson = "{\"B\":31,\"ElementClassA\":null,\"ElementClassB\":null,\"ElementClass2\":null}";
                Assert.AreEqual(exceptedJson, json);
            }

            {
                //忽略特定值测试(不匹配,因此不忽略)
                var obj4 = new RootClass()
                {
                    A             = "DO NET IGNORE",//不会被忽略
                    B             = 31,
                    C             = null,
                    ElementClassA = null,
                    ElementClassB = null,
                    ElementClass2 = null
                };
                var json = SerializerHelper.GetJsonString(obj4, new JsonSetting(true));//Z属性会被忽略
                Console.WriteLine(json);
                var exceptedJson = "{\"A\":\"DO NET IGNORE\",\"B\":31}";
                Assert.AreEqual(exceptedJson, json);
            }

            {
                //忽略特定类型为null的属性
                var obj3 = new RootClass()
                {
                    A             = "Jeffrey",
                    B             = 31,
                    C             = null,
                    ElementClassA = new ElementClass()
                    {
                        A = "Jeffrey", B = null
                    },
                    ElementClassB = null,
                    ElementClass2 = null//将会被忽略
                };

                var json3 = SerializerHelper.GetJsonString(obj3,
                                                           new JsonSetting(false, null, new List <Type>(new[] { typeof(ElementClass), typeof(ElementClass2) })));
                Console.WriteLine(json3);
                var exceptedJson3 = "{\"A\":\"Jeffrey\",\"B\":31,\"ElementClassA\":{\"A\":\"Jeffrey\",\"B\":null,\"RootClass\":null}}";
                Assert.AreEqual(exceptedJson3, json3);
            }



            Console.WriteLine((SystemTime.Now - dt1).TotalMilliseconds);
        }
Ejemplo n.º 35
0
 public MainWindow()
 {
     InitializeComponent();
     DataContext = new RootClass();
 }
        public void GetFieldValue_InferType_Lazy_ReturnsConcrete()
        {
            //Assign
            Item item = _db.GetItem(_item2Path);
            SitecoreProperty property = AttributeConfigurationLoader.GetProperty(typeof(RootClass).GetProperty("LazyLoadedInferred"));

            _handler.ConfigureDataHandler(property);
            RootClass root = new RootClass();


            //Act
            var result = _handler.GetFieldValue(
                item.ID.ToString(),
                item,
                _service);

            root.LazyLoadedInferred = result as EmptyTemplate1;

            //Assert
            Assert.IsNotNull(root.LazyLoadedInferred);
            Assert.AreNotEqual(typeof(EmptyTemplate1), root.LazyLoadedInferred.GetType());
            Assert.AreNotEqual(typeof(EmptyTemplate2), root.LazyLoadedInferred.GetType());
            //the type is inferred so should be EmptyTemplate2
            Assert.IsTrue(root.LazyLoadedInferred is EmptyTemplate2);
        }