/// <summary>
        /// Reads all properties from the given profile.
        /// Object's type name ti used as section name.
        /// </summary>
        /// <param name="obj">Object whos properties are to be read</param>
        /// <param name="profile">Profile containing data</param>
        public static void Load(object obj, Profile profile)
        {
            var type       = obj.GetType();
            var iniSection = profile[type.Name];
            var properties = type.GetProperties();

            foreach (var property in properties)
            {
                var value = iniSection.Get <object>(property.Name);
                if (value == null)
                {
                    continue;
                }

                try
                {
                    value = UniversalConverter.ConvertToType(value, property.PropertyType);
                    property.SetValue(obj, value, null);
                }
                catch
                {
                    // ignore
                }
            }
        }
Beispiel #2
0
        public T Get <T>(string key, T defaultValue)
        {
            if (!Keys.Contains(key))
            {
                return(defaultValue);
            }

            return(UniversalConverter.ConvertTo(this[key].ObjectValue, defaultValue));
        }
        public void UniversalConverterShouldConvertElementTypes()
        {
            var intList = new List <int> {
                1, 2, 3, 4, 5
            };
            var stringList = intList.Select(e => e.ToString()).ToList();

            Assert.Equal(stringList, UniversalConverter.ConvertToType(intList, typeof(List <string>)));
        }
        public void UniversalConverterShouldConvertArraysToLists()
        {
            var list = new List <int> {
                1, 2, 3, 4, 5
            };
            var array = list.ToArray();

            Assert.Equal(list, UniversalConverter.ConvertToType(array, typeof(List <int>)));
        }
        public void UniversalConverterShouldConvertStringsToBoolean()
        {
            Assert.False((bool)UniversalConverter.ConvertToType("0", typeof(bool)));
            Assert.False((bool)UniversalConverter.ConvertToType("N", typeof(bool)));
            Assert.False((bool)UniversalConverter.ConvertToType("F", typeof(bool)));
            Assert.False((bool)UniversalConverter.ConvertToType("false", typeof(bool)));
            Assert.False((bool)UniversalConverter.ConvertToType("False", typeof(bool)));
            Assert.False((bool)UniversalConverter.ConvertToType("X", typeof(bool)));
            Assert.False((bool)UniversalConverter.ConvertToType("", typeof(bool)));

            Assert.True((bool)UniversalConverter.ConvertToType("1", typeof(bool)));
            Assert.True((bool)UniversalConverter.ConvertToType("true", typeof(bool)));
            Assert.True((bool)UniversalConverter.ConvertToType("True", typeof(bool)));
            Assert.True((bool)UniversalConverter.ConvertToType("Y", typeof(bool)));
            Assert.True((bool)UniversalConverter.ConvertToType("J", typeof(bool)));
            Assert.True((bool)UniversalConverter.ConvertToType("T", typeof(bool)));
        }
Beispiel #6
0
        void TreeViewExSelectedItemChanged(object sender, RoutedPropertyChangedEventArgs <object> e)
        {
            var newValue = e.NewValue;

            if (!string.IsNullOrEmpty(SelectedItemType))
            {
                var type =
                    AppDomain.CurrentDomain.GetAssemblies()
                    .Where(a => a.GetType(SelectedItemType) != null)
                    .Select(a => a.GetType(SelectedItemType))
                    .FirstOrDefault();
                if (type != null)
                {
                    newValue = UniversalConverter.ConvertToType(newValue, type);
                }
            }
            SelectedItem = newValue;
        }
Beispiel #7
0
        public T GetObject <T>(CultureInfo cultureInfo) where T : new()
        {
            var obj = new T();

            foreach (var propertyInfo in typeof(T).GetProperties())
            {
                var columnIndex = ColumnNames
                                  .FindIndex(c => string.Compare(c, propertyInfo.Name, StringComparison.InvariantCultureIgnoreCase) == 0);
                if (columnIndex == -1)
                {
                    continue;
                }

                var value = UniversalConverter.ConvertToType(GetField(Columns[columnIndex]), propertyInfo.PropertyType, cultureInfo);
                propertyInfo.SetValue(obj, value, null);
            }

            return(obj);
        }
Beispiel #8
0
        private void AddPoints(string indent, IEnumerable <XmlNode> points)
        {
            foreach (XmlNode point in points)
            {
                if (point == null)
                {
                    continue;
                }

                var name        = point.Attributes["id"].InnerText;
                var sunSpecType = point.Attributes["type"].InnerText;
                var typeName    = SunSpecType.ToSystemType(sunSpecType).Name;

                if (sunSpecType.StartsWith("enum") || sunSpecType.StartsWith("bitfield"))
                {
                    var flags = sunSpecType.StartsWith("bitfield");
                    AddEnum(indent, point, typeName, flags);
                    typeName = "E_" + name;
                }

                var offset    = UniversalConverter.ConvertTo <long>(point.Attributes["offset"].InnerText);
                var length    = UniversalConverter.ConvertTo <long>(point.Attributes["len"]?.InnerText ?? "1");
                var access    = point.Attributes["access"]?.InnerText ?? "rw";
                var mandatory = UniversalConverter.ConvertTo <bool>(point.Attributes["mandatory"]?.InnerText) ? "" : "?";
                var units     = point.Attributes["units"]?.InnerText;

                if (!string.IsNullOrEmpty(units))
                {
                    _codeText.AppendLine($"{indent}/// [{units}]");
                }
                AddComment(indent, name);
                _codeText.AppendLine($"{indent}[SunSpecProperty(offset: {offset}, length: {length})]");
                _codeText.Append($"{indent}public {typeName}{mandatory} {name} {{ get; ");
                if (access == "r")
                {
                    _codeText.Append("private ");
                }
                _codeText.AppendLine("set; }");
            }
        }
        public void SetProperties(IPropertyProvider propertyValues, IFormatProvider provider)
        {
            var properties = _type.GetProperties();

            foreach (var property in properties)
            {
                var value = propertyValues.Get <object>(property.Name);
                if (value != null)
                {
                    // for array and list properties - split value on ';'s
                    if (property.PropertyType.IsArray ||
                        (property.PropertyType.IsGenericType &&
                         property.PropertyType.GenericTypeArguments.Length == 1 &&
                         property.PropertyType == typeof(List <>).MakeGenericType(property.PropertyType.GenericTypeArguments)))
                    {
                        value = value.ToString().Split(';').ToList();
                    }
                    value = UniversalConverter.ConvertToType(value, property.PropertyType, provider);
                    property.SetValue(_targetObject, value, null);
                    Trace.TraceInformation($"Set({_type.Name}) {property.Name} = {property.GetValue(_targetObject, null)}");
                }
            }
        }
Beispiel #10
0
        public static CsvData FromObject(object obj, CultureInfo cultureInfo)
        {
            var columns = obj.GetType().GetProperties()
                          .Select(prop => prop.Name)
                          .ToList();

            var csvData = new CsvData(-1, columns, "");

            foreach (var propertyInfo in obj.GetType().GetProperties())
            {
                var columnIndex = csvData.ColumnNames
                                  .FindIndex(c => string.Compare(c, propertyInfo.Name, StringComparison.InvariantCultureIgnoreCase) == 0);
                if (columnIndex == -1)
                {
                    continue;
                }

                var value = UniversalConverter.ConvertToType(propertyInfo.GetValue(obj), typeof(string), cultureInfo)?.ToString() ?? "";
                csvData.Fields.Add(value);
            }

            return(csvData);
        }
Beispiel #11
0
        private void CreateModelFile(string fileName, string structName, XmlNode model)
        {
            var id     = UniversalConverter.ConvertTo <long>(model.Attributes["id"].InnerText);
            var length = UniversalConverter.ConvertTo <long>(model.Attributes["len"].InnerText);

            if (structName == "Common" && id != 1)
            {
                // Test Model
                return;
            }

            Console.WriteLine($"Generating struct {structName}");

            foreach (var @using in GeneratorSettings.Usings)
            {
                _codeText.AppendLine($"using {@using};");
            }
            _codeText.AppendLine();

            _codeText.AppendLine("// ReSharper disable InconsistentNaming");
            _codeText.AppendLine("// ReSharper disable IdentifierTypo");
            _codeText.AppendLine("// ReSharper disable CommentTypo");
            _codeText.AppendLine("// ReSharper disable UnusedType.Global");
            _codeText.AppendLine("// ReSharper disable UnusedMember.Global");
            _codeText.AppendLine("// ReSharper disable MemberCanBePrivate.Global");
            _codeText.AppendLine("// ReSharper disable UnusedAutoPropertyAccessor.Local");
            _codeText.AppendLine("// ReSharper disable ArgumentsStyleLiteral");
            _codeText.AppendLine("// ReSharper disable BuiltInTypeReferenceStyle");
            _codeText.AppendLine();

            _codeText.AppendLine($"namespace {GeneratorSettings.Namespace}");
            _codeText.AppendLine("{");
            {
                AddComment("  ", null);

                _codeText.AppendLine($"  [SunSpecModel(id: {id}, length: {length})]");
                _codeText.AppendLine($"  public struct {structName}");
                _codeText.AppendLine("  {");
                {
                    var repeating = 1;
                    var blocks    = model.ChildNodes
                                    .Cast <XmlNode>()
                                    .Where(n => n.Name == "block")
                                    .ToArray();

                    foreach (var block in blocks)
                    {
                        var blockName = block.Attributes["name"]?.InnerText ?? $"Block{repeating++}";
                        var blockType = block.Attributes["type"]?.InnerText ?? "fixed";
                        var points    = block
                                        .ChildNodes
                                        .Cast <XmlNode>();

                        blockName = blockName.Trim()
                                    .Replace(" ", "_")
                                    .Replace("-", "_");


                        if (blockType == "fixed")
                        {
                            AddPoints("    ", points);
                        }
                        else
                        {
                            blockName = NamingConverter.SnakeToPascalCase(blockName);
                            _codeText.AppendLine($"    public struct S_{blockName}");
                            _codeText.AppendLine("    {");
                            AddPoints("      ", points);
                            _codeText.AppendLine("    };");
                            _codeText.AppendLine($"    public S_{blockName}[] {blockName};");
                        }
                    }
                }
                _codeText.AppendLine("  }");
            }
            _codeText.AppendLine("}");
            File.WriteAllText(fileName, _codeText.ToString());
        }
        private bool WriteValue(object value)
        {
            var client = _connection?.PlcClient;

            if (client == null)
            {
                return(false);
            }

            if (!client.Connected)
            {
                return(false);
            }

            var buffer = new byte[_info.ByteCount + 64];

            _value = value ?? throw new ArgumentNullException(nameof(value));

            try
            {
                switch (_info.PlcDataType)
                {
                case PlcDataTypes.X:
                    S7.SetBitAt(ref buffer, 0, _info.Bit, UniversalConverter.ConvertTo <bool>(_value));
                    break;

                case PlcDataTypes.B:
                    S7.SetByteAt(buffer, 0, UniversalConverter.ConvertTo <byte>(_value));
                    break;

                case PlcDataTypes.INT:
                    S7.SetIntAt(buffer, 0, UniversalConverter.ConvertTo <short>(_value));
                    break;

                case PlcDataTypes.DINT:
                    S7.SetDIntAt(buffer, 0, UniversalConverter.ConvertTo <int>(_value));
                    break;

                case PlcDataTypes.DT:
                    S7.SetDateTimeAt(buffer, 0, UniversalConverter.ConvertTo <DateTime>(_value));
                    break;

                case PlcDataTypes.STRING:
                    var text = UniversalConverter.ConvertTo <string>(_value);
                    if (text.Length > _info.MaxStringLength)
                    {
                        text = text.Substring(0, _info.MaxStringLength);
                    }
                    S7.SetStringAt(buffer, 0, _info.MaxStringLength, text);
                    break;
                }

                var result = (_info.PlcDataType == PlcDataTypes.X)
                                    ? client.WriteArea(_info.PlcArea, _info.DbNumber, _info.Offset, _info.ByteCount, _info.PlcWordLen, buffer)
                                    : client.DBWrite(_info.DbNumber, _info.Offset, _info.ByteCount, buffer);
                if (result == 0)
                {
                    return(true);
                }

                TronTrace.TraceError($"PlcItem.DBWrite({_info.DbNumber}, {_info.Offset}) failed - {result} {PlcResult.GetResultText(result)}");
            }
            catch (Exception ex)
            {
                TronTrace.TraceError($"PlcItem.DBWrite({_info.DbNumber}, {_info.Offset}) failed - {ex.Message}");
            }
            return(false);
        }
 public void UniversalConverterShouldConvertIntegersToEnums()
 {
     Assert.Equal(TestEnum.Three, UniversalConverter.ConvertToType(3, typeof(TestEnum)));
 }
 public void UniversalConverterShouldConvertIntegersToBoolean()
 {
     Assert.False((bool)UniversalConverter.ConvertToType(0, typeof(bool)));
     Assert.True((bool)UniversalConverter.ConvertToType(1, typeof(bool)));
 }