Ejemplo n.º 1
0
        public static string GetDeleteCommands(Type type, object domainObject)
        {
            PersistentClass    persistentClassAttribute = (PersistentClass)type.GetCustomAttribute(typeof(PersistentClass));
            PropertyInfo       primaryKeyProperty       = type.GetProperties().Where(prop => Attribute.IsDefined(prop, typeof(PersistentPrimaryKeyProperty))).Single();
            PersistentProperty persistentProperty       = (PersistentProperty)primaryKeyProperty.GetCustomAttribute(typeof(PersistentProperty));
            string             commandText = "Delete from " + persistentClassAttribute.TableName + " where " + persistentProperty.SqlName + " = '" + primaryKeyProperty.GetValue(domainObject) + "';";

            return(commandText);
        }
Ejemplo n.º 2
0
        public void ZWaveSwitchConstructor()
        {
            ZWaveSwitch zWaveSwitch = new ZWaveSwitch();

            Assert.AreEqual(SwitchType.Misc, zWaveSwitch.Type);
            Assert.AreEqual(2, zWaveSwitch.Properties.Count());
            PersistentProperty prop = zWaveSwitch.Properties.SingleOrDefault(s => s.Name.Equals("Name"));

            Assert.IsNotNull(prop);
        }
Ejemplo n.º 3
0
        public static string GetUpdateCommands(Type type, object domainObject)
        {
            PersistentClass    persistentClassAttribute = (PersistentClass)type.GetCustomAttribute(typeof(PersistentClass));
            PropertyInfo       primaryKeyProperty       = type.GetProperties().Where(prop => Attribute.IsDefined(prop, typeof(PersistentPrimaryKeyProperty))).Single();
            PersistentProperty persistentProperty       = (PersistentProperty)primaryKeyProperty.GetCustomAttribute(typeof(PersistentProperty));

            string commandText = "Update " + persistentClassAttribute.TableName + " set [FIELDLIST] where " + persistentProperty.SqlName + " = '" + primaryKeyProperty.GetValue(domainObject) + "';";

            commandText = commandText.Replace("[FIELDLIST]", GetSqlUpdateFieldList(type, domainObject));
            return(commandText);
        }
        public void PersistentProperties_with_same_name_shall_always_have_the_same_value()
        {
            PersistentPropertyControlTree ControlTree = new PersistentPropertyControlTree();

            PersistentProperty.SetId(ControlTree.DataTemplate, "Three");
            ControlTree.Three.Text = "Hello, world!";

            Assert.AreEqual("Hello, world!", ControlTree.Three.Text);
            Assert.AreEqual("Hello, world!", ControlTree.Three2.Text);
            Assert.AreEqual("Hello, world!", ControlTree.DataTemplate.Text);
        }
Ejemplo n.º 5
0
        public void ZWaveSwitchNameSet()
        {
            ZWaveSwitch        zWaveSwitch = new ZWaveSwitch();
            PersistentProperty prop        = zWaveSwitch.Properties.SingleOrDefault(s => s.Name.Equals("Name"));

            Assert.IsNotNull(prop);

            prop.Setter("Test Name");

            Assert.AreEqual("Test Name", zWaveSwitch.Name);
        }
Ejemplo n.º 6
0
        public static string GetSqlInsertFieldList(Type type)
        {
            string result = "";
            List <PropertyInfo> propertyList = type.GetProperties().Where(prop => Attribute.IsDefined(prop, typeof(PersistentProperty))).ToList();

            foreach (PropertyInfo property in propertyList)
            {
                PersistentProperty persistentProperty = (PersistentProperty)property.GetCustomAttribute(typeof(PersistentProperty));
                result = result + persistentProperty.SqlName + ", ";
            }
            result = result.Substring(0, result.Length - 2);
            return(result);
        }
Ejemplo n.º 7
0
        public void ZWaveNodeProperties()
        {
            Mock <IZWaveController> controller = new Mock <IZWaveController>(MockBehavior.Strict);

            controller.Setup(s => s.IsInitialized).Returns(false);
            ZWaveNode.SetController(controller.Object);
            Mock <IInternalConfigurationManager> configManager = new Mock <IInternalConfigurationManager>();
            MockZWaveNode node = new MockZWaveNode();

            Assert.AreEqual(1, node.Properties.Count());
            PersistentProperty prop = node.Properties.Single();

            Assert.AreEqual("NodeId", prop.Name);
            prop.Setter("100");
            Assert.AreEqual(100, node.NodeId);
            Assert.AreEqual("100", prop.Getter());
        }
Ejemplo n.º 8
0
        private IParseable ParseComponent(XmlNode componentNode, ParseableElementType typeToLookFor)
        {
            Lazy <IParseable, IParseableMetadata> parseable;

            try
            {
                parseable = _compositionContainer.GetExport <IParseable, IParseableMetadata>(componentNode.Name);
            }
            catch (ImportCardinalityMismatchException)
            {
                throw new InvalidOperationException(String.Format("Could not find any components with the name {0}.", componentNode.Name));
            }
            if (parseable.Metadata.Type != typeToLookFor)
            {
                switch (parseable.Metadata.Type)
                {
                case ParseableElementType.App:
                    throw new InvalidOperationException(String.Format("There was an error while processing a declaration for the app {0}. Ensure that {0} is declared at the top level of the Apps tag in the configuration file.", componentNode.Name));

                case ParseableElementType.IOInterface:
                    throw new InvalidOperationException(String.Format("There was an error while processing a declaration for the IO interface {0}. Ensure that {0} is declared at the top level of the IO Interfaces tag in the configuration file.", componentNode.Name));

                case ParseableElementType.Support:
                    throw new InvalidOperationException(String.Format("There was an error while processing a declaration for the support component {0}. Ensure that {0} is declared underneath an app or an IO interface.", componentNode.Name));

                default:
                    throw new NotImplementedException(String.Format("The component type {0} is not supported!", typeToLookFor.ToString()));
                }
            }
            IParseable component = parseable.Value;

            foreach (XmlAttribute attr in componentNode.Attributes)
            {
                PersistentProperty prop = component.Properties.Single(p => p.Name.Equals(attr.Name));
                prop.Setter(attr.Value);
            }
            foreach (IParseable childComponent in ParseChildrenComponents(componentNode, ParseableElementType.Support))
            {
                component.AddChild(childComponent);
            }
            return(component);
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Saves all generic lists and dictionaries of the object and all inlined classes. The object already has to have an id!
        /// </summary>
        /// <param name="o">Object of which to save lists and dictionaries</param>
        /// <param name="parent">Parent (not inlined) Type</param>
        /// <param name="id">Id of the object</param>
        /// <param name="embeddedPrefix">Prefix used to create unique mn table names for all inlined lists and dictionaries</param>
        private static void SaveEnumerations(object o, Type parent, string id, string embeddedPrefix = "")
        {
            if (o == null)
            {
                return;
            }

            // Save all scalar and inline types first, so we have the new entry id for our mn-table later
            foreach (var property in PersistentProperty.GetPersistentProperties(o.GetType(), embeddedPrefix, parent))
            {
                if (property.IsInlinedType)
                {
                    SaveEnumerations(property.Property.GetValue(o, null), parent == null ? o.GetType() : parent, id, property.ColumnName + "_");
                }

                if (property.IsGenericList)
                {
                    IList list = (IList)property.Property.GetValue(o, null);

                    foreach (var item in list)
                    {
                        string newId = Save(item, null, new Dictionary <string, string>(), "");

                        using (var cmd = new SQLiteCommand(String.Format(
                                                               "INSERT INTO {4} ({0}Id, {1}Id) VALUES ({2}, {3})",
                                                               parent == null ? o.GetType().Name : parent.Name,
                                                               property.ListType.Name,
                                                               id,
                                                               newId,
                                                               property.RelationTableName
                                                               ), DBManager.MPQMirror))
                        {
                            cmd.ExecuteNonQuery();
                        }
                    }
                }

                if (property.IsGenericDictionary)
                {
                    IDictionary dictionary = (IDictionary)property.Property.GetValue(o, null);

                    foreach (var item in dictionary.Keys)
                    {
                        string newId = Save(dictionary[item], null, new Dictionary <string, string>(), "");

                        using (var cmd = new SQLiteCommand(String.Format(
                                                               "INSERT INTO {4} ({0}Id, {1}Id, Key) VALUES ({2}, {3}, {5})",
                                                               parent == null ? o.GetType().Name : parent.Name,
                                                               property.ListType.Name,
                                                               id,
                                                               newId,
                                                               property.RelationTableName,
                                                               item
                                                               ), DBManager.MPQMirror))
                        {
                            cmd.ExecuteNonQuery();
                        }
                    }
                }
            }
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Save object with all inlined classes to table
        /// </summary>
        /// <param name="o">Object to save</param>
        /// <param name="parent">Parent type (Type of outmost, not inlined object)</param>
        /// <param name="id">Id to use to save or null to create a new</param>
        /// <param name="values">Dictionary in wich inlined classes write their property values</param>
        /// <param name="embeddedPrefix">Prefix to use in inlined classes so all inlined properties have unique column names</param>
        /// <returns>Id used to save the object</returns>
        private static string SaveBasic(object o, Type parent, string id, Dictionary <string, string> values, string embeddedPrefix = "")
        {
            if (o == null)
            {
                return("");
            }

            // save scalar types
            if (o.GetType().Namespace != "System" && !o.GetType().IsEnum)
            {
                // Save all scalar and inline types first, so we have the new entry id for our mn-table later
                foreach (var property in PersistentProperty.GetPersistentProperties(o.GetType(), embeddedPrefix, parent))
                {
                    if (property.IsSimpleType)
                    {
                        if (property.Type.IsArray)
                        {
                            if (property.ArrayCount == -1)
                            {
                                values.Add(property.ColumnName, "'" + BitConverter.ToString((byte[])property.Property.GetValue(o, null)) + "'");
                            }
                            else
                            {
                                for (int i = 0; i < property.ArrayCount; i++)
                                {
                                    values.Add(property.ColumnName + "_" + i, "'" + (property.Property.GetValue(o, null) as Array).GetValue(i).ToString() + "'");
                                }
                            }
                        }
                        else
                        {
                            values.Add(property.ColumnName, "'" + property.Property.GetValue(o, null).ToString() + "'");
                        }
                    }

                    // save complex object as inlined class
                    if (property.IsInlinedType)
                    {
                        values.Add(property.ColumnName + "_", "'" + (property.Property.GetValue(o, null) != null).ToString() + "'");
                        SaveBasic(property.Property.GetValue(o, null), parent == null ? o.GetType() : parent, id, values, property.ColumnName + "_");
                    }
                }
            }
            else
            {
                values.Add("Value", o.ToString());
            }

            // No parent means this class is not inlined. Add a new entry with all saved values in the class table
            if (parent == null)
            {
                if (id != null)
                {
                    values.Add("Id", id);
                }

                string cnames  = String.Join(",", (new List <string>(values.Keys).ToArray()));
                string cvalues = String.Join(",", (new List <string>(values.Values).ToArray()));

                using (var cmd = new SQLiteCommand(String.Format("INSERT INTO {0} ({1}) VALUES ({2})", o.GetType().Name, cnames, cvalues), DBManager.MPQMirror))
                {
                    cmd.ExecuteNonQuery();

                    using (var last = new SQLiteCommand("SELECT last_insert_rowid()", DBManager.MPQMirror))
                    {
                        id = last.ExecuteScalar().ToString();
                    }
                }
            }

            return(id);
        }
Ejemplo n.º 11
0
        private static void CreateTableForType(Type type, Type parent, Dictionary <string, Type> values, string embeddedPrefix = "")
        {
            // Save all scalar and inline types first, so we have the new entry id for our mn-table later
            foreach (var property in PersistentProperty.GetPersistentProperties(type, embeddedPrefix, parent))
            {
                if (property.IsSimpleType)
                {
                    // save array of basic types
                    if (property.Type.IsArray && property.ArrayCount != -1)
                    {
                        for (int i = 0; i < property.ArrayCount; i++)
                        {
                            values.Add(property.ColumnName + "_" + i, property.Property.PropertyType);
                        }
                    }
                    else
                    {
                        values.Add(property.ColumnName, property.Type);
                    }
                    continue;
                }

                if (property.IsGenericList || property.IsGenericDictionary)
                {
                    string query = "";

                    if (property.IsGenericList)
                    {
                        query = "CREATE TABLE {0} ({1}Id NUMERIC, {2}Id NUMERIC)";
                    }

                    if (property.IsGenericDictionary)
                    {
                        query = "CREATE TABLE {0} ({1}Id NUMERIC, {2}Id NUMERIC, Key TEXT)";
                    }

                    query = String.Format(query, property.RelationTableName, parent == null ? type.Name : parent.Name, property.ListType.Name);

                    using (var cmd = new SQLiteCommand(query, DBManager.MPQMirror))
                    {
                        cmd.ExecuteNonQuery();
                    }

                    CreateTableForType(property.ListType, null, new Dictionary <string, Type>());
                    continue;
                }

                values.Add(property.ColumnName + "_", typeof(string));
                CreateTableForType(property.Type, parent == null ? type : parent, values, property.ColumnName + "_");
            }

            // Only create tables for parent classes
            if (parent == null && !tableExists(type.Name))
            {
                if (type.Namespace == "System")
                {
                    values.Add("Value", typeof(string));
                }

                var columnDefinitions = values.Select(v => v.Key + " " + ((v.Value == typeof(String) || v.Value == typeof(byte[])) ? "TEXT" : "NUMERIC")).ToList <string>();
                columnDefinitions.Add("Id INTEGER PRIMARY KEY");
                var tableDefinition = String.Join(",", columnDefinitions.ToArray <string>());

                using (var cmd = new SQLiteCommand(String.Format("CREATE TABLE {0} ({1})", type.Name, tableDefinition), DBManager.MPQMirror))
                {
                    cmd.ExecuteNonQuery();
                }
            }
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Loads properties of an object from the passed reader. For inlined properties, the parent reader is passed
        /// </summary>
        /// <param name="o">Object to be filled with data</param>
        /// <param name="parent">Parent type that has the id for inlined classes</param>
        /// <param name="reader">Reader from which to take the data</param>
        /// <param name="embeddedPrefix">Prefix for 'inlined' properties (complex types)</param>
        private static void Load(object o, Type parent, SQLiteDataReader reader, string embeddedPrefix = "")
        {
            foreach (var property in PersistentProperty.GetPersistentProperties(o.GetType(), embeddedPrefix, parent))
            {
                string entryId = reader["Id"].ToString();

                // Load generic lists by finding the mn-mapping table and loading every entry recursivly
                if (property.IsGenericList)
                {
                    using (var cmd = new SQLiteCommand(String.Format(genericListsql, property.RelationTableName, property.ListType.Name, parent == null ? o.GetType().Name : parent.Name, entryId), DBManager.MPQMirror))
                    {
                        var itemReader = cmd.ExecuteReader();
                        var list       = Activator.CreateInstance(property.Type);

                        if (itemReader.HasRows)
                        {
                            while (itemReader.Read())
                            {
                                var item = Activator.CreateInstance(property.ListType);
                                Load(item, null, itemReader);
                                (list as IList).Add(item);
                            }
                        }
                        property.Property.SetValue(o, list, null);
                    }
                    continue;
                }

                // Load generic dictionaires by finding the mn-mapping table and loading every entry recursivly
                if (property.IsGenericDictionary)
                {
                    using (var cmd = new SQLiteCommand(String.Format(genericListsql, property.RelationTableName, property.ListType.Name, parent == null ? o.GetType().Name : parent.Name, entryId), DBManager.MPQMirror))
                    {
                        var itemReader = cmd.ExecuteReader();
                        var dictionary = Activator.CreateInstance(property.Type);

                        if (itemReader.HasRows)
                        {
                            while (itemReader.Read())
                            {
                                var item = Activator.CreateInstance(property.ListType);
                                Load(item, null, itemReader);
                                (dictionary as IDictionary).Add(Convert.ChangeType(itemReader["Key"], property.Type.GetGenericArguments()[0]), item);
                            }
                        }
                        property.Property.SetValue(o, dictionary, null);
                    }
                    continue;
                }

                // load scalar types
                if (property.Type.Namespace == "System")
                {
                    // load array of scalar types. The column name of the i-th array entry is "columnName_i"
                    if (property.Type.IsArray)
                    {
                        if (property.ArrayCount == -1)
                        {
                            byte[] blob = StringToByteArray(reader[property.ColumnName].ToString().Replace("-", ""));
                            property.Property.SetValue(o, blob, null);
                        }
                        else
                        {
                            Array vals = (Array)Activator.CreateInstance(property.Type, property.ArrayCount);
                            for (int i = 0; i < vals.Length; i++)
                            {
                                vals.SetValue(Convert.ChangeType(reader[property.ColumnName + "_" + i.ToString()], property.Type.GetElementType()), i);
                            }

                            property.Property.SetValue(o, vals, null);
                        }
                    }
                    else
                    {
                        property.Property.SetValue(o, Convert.ChangeType(reader[property.ColumnName], property.Type), null);
                    }
                    continue;
                }

                // load enums
                if (property.Type.IsEnum)
                {
                    property.Property.SetValue(o, Enum.Parse(property.Type, reader[property.ColumnName].ToString(), true), null);
                    continue;
                }

                // if its none of the earlier types, its a inlined class. class properties
                if (Convert.ToBoolean(reader[property.ColumnName + "_"]))
                {
                    var embedded = Activator.CreateInstance(property.Type);
                    Load(embedded, o.GetType(), reader, property.ColumnName + "_");
                    property.Property.SetValue(o, embedded, null);
                }
            }
        }
Ejemplo n.º 13
0
        public static string GetSqlUpdateFieldList(Type type, object domainObject)
        {
            string              result             = "";
            PropertyInfo        primaryKeyProperty = type.GetProperties().Where(prop => Attribute.IsDefined(prop, typeof(PersistentPrimaryKeyProperty))).Single();
            List <PropertyInfo> propertyList       = type.GetProperties().Where(prop => Attribute.IsDefined(prop, typeof(PersistentProperty))).ToList();

            foreach (PropertyInfo property in propertyList)
            {
                if (property.Name != primaryKeyProperty.Name)
                {
                    PersistentProperty persistentProperty = (PersistentProperty)property.GetCustomAttribute(typeof(PersistentProperty));
                    switch (property.PropertyType.Name)
                    {
                    case "Nullable`1":
                        Type nullableType = property.PropertyType.GetGenericArguments()[0];
                        switch (nullableType.Name)
                        {
                        case "Int32":
                            if (property.GetValue(domainObject) == null)
                            {
                                result = result + persistentProperty.SqlName + "=null, ";
                            }
                            else
                            {
                                Int32 nullableInt32 = Int32.Parse(property.GetValue(domainObject).ToString());
                                result = result + persistentProperty.SqlName + "= " + nullableInt32 + ", ";
                            }
                            break;

                        case "DateTime":
                            if (property.GetValue(domainObject) == null)
                            {
                                result = result + persistentProperty.SqlName + "=null, ";
                            }
                            else
                            {
                                DateTime nullableDateTime = DateTime.Parse(property.GetValue(domainObject).ToString());
                                result = result + persistentProperty.SqlName + "='" + nullableDateTime.ToString("yyyy-MM-dd HH:mm:ss") + "', ";
                            }
                            break;

                        default:
                            throw new Exception("Nullable type not implemented yet.");
                        }

                        break;

                    case "Boolean":
                        result = result + persistentProperty.SqlName + " = '" + Convert.ToInt32(property.GetValue(domainObject)) + "', ";
                        break;

                    case "DateTime":
                        DateTime dateTime = (DateTime)property.GetValue(domainObject);
                        result = result + persistentProperty.SqlName + " = '" + dateTime.ToString("yyyy-MM-dd HH:mm:ss") + "', ";
                        break;

                    default:
                        if (property.GetValue(domainObject) == null || property.GetValue(domainObject).ToString() == "")
                        {
                            result = result + persistentProperty.SqlName + "=null, ";
                        }
                        else
                        {
                            result = result + persistentProperty.SqlName + " = '" + property.GetValue(domainObject).ToString().Replace("'", "''") + "', ";
                        }
                        break;
                    }
                }
            }
            result = result.Substring(0, result.Length - 2);
            return(result);
        }
Ejemplo n.º 14
0
        public static void WriteFromSql(Type type, JObject jObject, Object obj)
        {
            List <PropertyInfo> propertyList = type.GetProperties().Where(prop => Attribute.IsDefined(prop, typeof(PersistentProperty))).ToList();

            foreach (PropertyInfo property in propertyList)
            {
                PersistentProperty persistentProperty = (PersistentProperty)property.GetCustomAttributes(typeof(PersistentProperty), false)[0];
                if (jObject[persistentProperty.SqlName] != null)
                {
                    switch (property.PropertyType.Name)
                    {
                    case "String":
                        property.SetValue(obj, jObject[persistentProperty.SqlName].ToString());
                        break;

                    case "Int32":
                        property.SetValue(obj, Convert.ToInt32(jObject[persistentProperty.SqlName].ToString()));
                        break;

                    case "JObject":
                        if (jObject[persistentProperty.SqlName].ToString() != "")
                        {
                            property.SetValue(obj, JObject.Parse(jObject[persistentProperty.SqlName].ToString()));
                        }
                        break;

                    case "Boolean":
                        property.SetValue(obj, Convert.ToBoolean(Convert.ToInt32(jObject[persistentProperty.SqlName].ToString())));
                        break;

                    case "DateTime":
                        System.Globalization.CultureInfo provider = System.Globalization.CultureInfo.InvariantCulture;
                        property.SetValue(obj, DateTime.Parse(jObject[persistentProperty.SqlName].ToString()));
                        break;

                    case "Nullable`1":
                        Type nullableType = property.PropertyType.GetGenericArguments()[0];
                        switch (nullableType.Name)
                        {
                        case "Int32":
                            if (jObject[persistentProperty.SqlName].ToString() != "")
                            {
                                property.SetValue(obj, Int32.Parse(jObject[persistentProperty.SqlName].ToString()));
                            }
                            break;

                        case "DateTime":
                            if (jObject[persistentProperty.SqlName].ToString() != "")
                            {
                                property.SetValue(obj, DateTime.Parse(jObject[persistentProperty.SqlName].ToString()));
                            }
                            break;

                        default:
                            throw new Exception("Nullable type not implemented yet.");
                        }
                        break;

                    default:
                        throw new Exception("Data Type not handled in JSON Object Writer");
                    }
                }
            }
        }