public void CanRoundtripException()
        {
            // generate "authentic" exception with stack trace and everything :)
            string toSerialize;

            try
            {
                throw new ApplicationException("uh oh, something bad has happened!");
            }
            catch (Exception e)
            {
                toSerialize = e.ToString().Replace(Environment.NewLine, "|");
            }

            var dictionaryWithExceptionMessages = new Dictionary <string, object> {
                { "exception-message", toSerialize }
            };
            var str = serializer.Serialize(dictionaryWithExceptionMessages);

            Console.WriteLine(@"

here it is:

{0}

", str);

            var deserializedDictionary = serializer.Deserialize(str);

            deserializedDictionary.ShouldBe(dictionaryWithExceptionMessages);
        }
        /// <summary>
        /// Reads the configuration from an Stream
        /// </summary>
        /// <param name="strm"></param>
        /// <returns></returns>
        private static Dictionary <String, PLCConnectionConfiguration> LoadConfigFile(TextReader strm)
        {
            Dictionary <String, PLCConnectionConfiguration>           Connections;
            DictionarySerializer <String, PLCConnectionConfiguration> ConnectionsDicSer = new DictionarySerializer <string, PLCConnectionConfiguration>();

            //the idea here is, to try to deserialize the data once, and if it fails,
            //Try to repair it. If it fails also the second time, then give up an throw
            //This is neede to maintain Backwards compatibility with config files that do not use
            //Enumerations.
            try
            {
                Connections = ConnectionsDicSer.Deserialize(strm);
            }
            catch (Exception ex)
            {
                try
                {
                    strm.Close();                                          //Close old stream
                    strm = new StreamReader(ConfigurationPathAndFilename); //Reopen temporary stream
                    string repaired = repairConfig(strm.ReadToEnd());
                    strm.Close();                                          //Close temporary stream
                    strm        = new StringReader(repaired);
                    Connections = ConnectionsDicSer.Deserialize(strm);
                }
                catch
                {
                    throw ex; //Throw orignial Exception
                }
            }
            return(Connections);
        }
        /// <summary>
        /// Associate the settings read from file <paramref name="fileName"/>
        /// with the key <paramref name="key"/>.
        /// </summary>
        /// <param name="storeKey">The key that will allow further access to newly created settings store.</param>
        /// <param name="settingsFileName">Settings file to read.</param>
        public void AddSettingsStore(string storeKey, string settingsFileName)
        {
            if (string.IsNullOrEmpty(settingsFileName))
            {
                throw new ArgumentNullException("settingsFileName");
            }
            if (Stores.ContainsKey(storeKey))
            {
                throw new ArgumentException(string.Format("Settings store {0} already exists.", storeKey), "storeKey");
            }

            var dictionary = new Dictionary <string, string>();

            var doc = new XmlDocument();

            if (!File.Exists(settingsFileName))
            {
                This.Logger.Info(string.Format(SR.SettingsFileNotFound, settingsFileName, storeKey));
            }
            else
            {
                doc.Load(settingsFileName);
            }
            serializer.Deserialize(dictionary, doc);

            Stores.Add(storeKey, new SettingsStore()
            {
                Settings = dictionary,
                FileName = settingsFileName,
                Document = doc
            });
        }
        public static String[] GetConfigurationNames()
        {
#if !IPHONE
            if (File.Exists(ConfigurationPathAndFilename))
            {
                DictionarySerializer <String, PLCConnectionConfiguration> ConnectionsDicSer = new DictionarySerializer <string, PLCConnectionConfiguration>();

                Dictionary <String, PLCConnectionConfiguration> Connections = null;
                StreamReader strm = new StreamReader(ConfigurationPathAndFilename);
                Connections = ConnectionsDicSer.Deserialize(strm);
                //string txt = strm.ReadToEnd();
                strm.Close();
                //Connections = General.SerializeToString<Dictionary<String, PLCConnectionConfiguration>>.DeSerialize(txt);
                if (Connections != null)
                {
                    string[] Names = new string[Connections.Count];
                    Connections.Keys.CopyTo(Names, 0);
                    return(Names);
                }
            }
            return(new string[0]);

            RegistryKey myConnectionKey =
                Registry.CurrentUser.CreateSubKey("Software\\JFKSolutions\\WPFToolboxForSiemensPLCs\\Connections");
            return(myConnectionKey.GetSubKeyNames());
#else
            return(null);
#endif
        }
        public bool LoadMapping()
        {
            try
            {
                if (mapping == null)
                {
                    return(false);
                }

                String mappingFilePath = GetMappingFilePath();
                if (!File.Exists(mappingFilePath))
                {
                    return(false);
                }

                Dictionary <String, String> mappingDictionary = DictionarySerializer.Deserialize(mappingFilePath);

                mapping.CopyMappingsFrom(mappingDictionary);
                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
        }
Beispiel #6
0
        /// <summary>
        /// Decoding of encoded bytes by Huffman algorithm.
        /// </summary>
        /// <param name="bytes"> Encoded bytes</param>
        /// <returns> Decoded bytes</returns>
        public static byte[] Decode(byte[] bytes)
        {
            var result = DictionarySerializer.Deserialize(bytes);

            return(Decode(bytes,
                          result.SizeOfBytes,
                          TreeBuilder.BuildTree(new TreeBuilderQueue(result.Dictionary))));
        }
Beispiel #7
0
 public void DictionaryTest3()
 {
     var a = new TestStruct {
         a = 3, b = "testString"
     };
     var serializedData = DictionarySerializer.Serialize(a);
     var a_deserialized = DictionarySerializer.Deserialize <TestStruct>(serializedData);
 }
 public static Dictionary <Tkey, Tvalue> AsDictionary <Tkey, Tvalue>(this BsonValue bsonValue)
 {
     using (var reader = BsonReader.Create(bsonValue.ToJson()))
     {
         var dictionarySerializer = new DictionarySerializer <Tkey, Tvalue>();
         var result = dictionarySerializer.Deserialize(reader, typeof(Dictionary <Tkey, Tvalue>), new DictionarySerializationOptions());
         return((Dictionary <Tkey, Tvalue>)result);
     }
 }
Beispiel #9
0
        public void DictionaryTest2()
        {
            var a = new DerivedA();

            a.SetValues();

            var serializedData = DictionarySerializer.Serialize(a);
            var a1             = DictionarySerializer.Deserialize <Interface>(serializedData);
        }
Beispiel #10
0
        public void DictionaryDictionaryTest()
        {
            var a = new DictionaryClass();

            a.SetValues();

            var serializedData = DictionarySerializer.Serialize(a);
            var a1             = DictionarySerializer.Deserialize <DictionaryClass>(serializedData);
        }
Beispiel #11
0
        static void Main(string[] args)
        {
            List <string> level1 = new List <string> {
                "Hey",
                "I am",
                "Level One",
            };
            var lstSeri = level1.Serialize();
            var lvl1de  = lstSeri.DeSerialize <string>();

            lvl1de.DoSerializion();


            //Let's create a dummy dictionary with some entities
            Dictionary <string, string> myDictionary = new Dictionary <string, string>();

            myDictionary["HalloWelt"]  = "lola";
            myDictionary["HalloWelt1"] = "lola2";

            //Serialize the dictionary to a byte array
            var serialized = myDictionary.Serialize();
            //Deserialize that byte array to a dictionary<string,string>
            var deseri = serialized.DeSerialize <string, string>();

            Console.WriteLine(deseri["HalloWelt"]);

            //Same, but not as pretty as the previous example
            serialized = DictionarySerializer <string, string> .Serialize(myDictionary);

            deseri = DictionarySerializer <string, string> .Deserialize(serialized);

            var myDictionary1 = new Dictionary <string, Dictionary <string, string> >
            {
                ["HalloWelt"] = new Dictionary <string, string>
                {
                    ["a"] = "b",
                    ["c"] = "ba",
                    ["d"] = "bs",
                    ["e"] = "bfa",
                },
                ["HalloWelt1"] = new Dictionary <string, string>
                {
                    ["xa"] = "xb",
                    ["xc"] = "xba",
                    ["xd"] = "xbs",
                    ["xe"] = "xbfa",
                },
            };

            serialized = myDictionary1.Serialize();
            var deserialized = serialized.DeSerialize <string, Dictionary <string, Dictionary <string, int> > >();

            Console.ReadLine();
        }
Beispiel #12
0
        public void ReadonlyListTest()
        {
            //var lIn = new ListClass();
            var lIn = new ListContainerClassReadonly();

            lIn.list.Add("Hello");
            lIn.list.Add("My name is");
            lIn.list.Add("Bob!");
            var serializedData = DictionarySerializer.Serialize(lIn);
            var lOut           = DictionarySerializer.Deserialize <ListContainerClassReadonly>(serializedData);
        }
Beispiel #13
0
        /// <summary>
        /// Reads the given MSMQ message, wrapping the message in a <see cref="ReceivedTransportMessage"/>
        /// </summary>
        public object Read(Message message)
        {
            var stream = message.BodyStream;

            using (var reader = new BinaryReader(stream))
            {
                return(new ReceivedTransportMessage
                {
                    Id = message.Id,
                    Body = reader.ReadBytes((int)stream.Length),
                    Label = message.Label,
                    Headers = DictionarySerializer.Deserialize(HeaderEcoding.GetString(message.Extension))
                });
            }
        }
Beispiel #14
0
        public void ListTest()
        {
            //var lIn = new ListClass();
            var lIn = new ListContainerClass {
                list = new List <string>()
            };

            lIn.list.Add("Hello");
            lIn.list.Add("My name is");
            lIn.list.Add("Bob!");
            var serializedData = DictionarySerializer.Serialize(lIn);

            DictionarySerializer.DeserializeList <ListClass>(new object[] { serializedData });
            //var lOut = DictionarySerializer.Deserialize<ListClass>(serializedData);
            var lOut = DictionarySerializer.Deserialize <ListContainerClass>(serializedData);
        }
Beispiel #15
0
        public void InterfaceTest()
        {
            var interfaceList = new List <Interface>();

            interfaceList.Add(new DerivedA {
                a = "a1"
            });
            interfaceList.Add(new DerivedA {
                a = "a2"
            });
            interfaceList.Add(new DerivedB {
                b = "b1"
            });
            var serializedData   = DictionarySerializer.Serialize(interfaceList);
            var interfaceListOut = DictionarySerializer.Deserialize <List <Interface> >(serializedData);

            Assert.AreEqual(interfaceList.Count, interfaceListOut.Count);
        }
Beispiel #16
0
        public void DictionaryTest1()
        {
            var a = new TestClassA();

            a.SetValues();

            var serializedData_noMask = DictionarySerializer.Serialize(a);
            var a_NoMask = DictionarySerializer.Deserialize <TestClassA>(serializedData_noMask);

            var serializedData_Mask_1 = DictionarySerializer.Serialize(a, SerializationMaskType.Public);
            var a_Mask_1 = DictionarySerializer.Deserialize <TestClassA>(serializedData_Mask_1);

            var serializedData_Mask_2 = DictionarySerializer.Serialize(a, SerializationMaskType.Private);
            var a_Mask_2 = DictionarySerializer.Deserialize <TestClassA>(serializedData_Mask_2);

            var serializedData_Mask_1_2 = DictionarySerializer.Serialize(a, SerializationMaskType.Public | SerializationMaskType.Private);
            var a_Mask_1_2 = DictionarySerializer.Deserialize <TestClassA>(serializedData_Mask_1_2);
        }
        public static void DeleteConfiguration(string ConnectionName)
        {
#if !IPHONE
            try
            {
                DictionarySerializer <String, PLCConnectionConfiguration> ConnectionsDicSer = new DictionarySerializer <string, PLCConnectionConfiguration>();

                Dictionary <String, PLCConnectionConfiguration> Connections = null;
                if (File.Exists(ConfigurationPathAndFilename))
                {
                    StreamReader strm = new StreamReader(ConfigurationPathAndFilename);
                    Connections = ConnectionsDicSer.Deserialize(strm);
                    //string txt = strm.ReadToEnd();
                    strm.Close();
                    //Connections = General.SerializeToString<Dictionary<String, PLCConnectionConfiguration>>.DeSerialize(txt);
                }
                if (Connections == null)
                {
                    Connections = new Dictionary <string, PLCConnectionConfiguration>();
                }

                if (Connections.ContainsKey(ConnectionName))
                {
                    Connections.Remove(ConnectionName);
                }

                Directory.CreateDirectory(Path.GetDirectoryName(ConfigurationPathAndFilename));
                StreamWriter sstrm = new StreamWriter(ConfigurationPathAndFilename, false);
                ConnectionsDicSer.Serialize(Connections, sstrm);
                //sstrm.Write(stxt);
                //sstrm.Flush();
                sstrm.Close();

                return;

                Registry.CurrentUser.DeleteSubKeyTree(
                    "Software\\JFKSolutions\\WPFToolboxForSiemensPLCs\\Connections\\" + ConnectionName);
            }
            catch (Exception)
            { }
#endif
        }
Beispiel #18
0
        public static void StressTest()
        {
            var dict = new Dictionary <string, string>
            {
                { "Key1", "Value1" },
                { "Key2", "Value2" }
            };

            using var writer = new PooledArrayBufferWriter <byte>();
            // serialize dictionary to memory
            using (var output = StreamSource.AsStream(writer))
            {
                DictionarySerializer.Serialize(dict, output);
            }
            // deserialize from memory
            using (var input = StreamSource.AsStream(writer.WrittenArray))
            {
                Equal(dict, DictionarySerializer.Deserialize(input));
            }
        }
Beispiel #19
0
        public void Serialize()
        {
            Dictionary <string, string> table = new Dictionary <string, string>();

            table["Test"]  = "1";
            table["Test2"] = "2";
            var data = instance.Serialize(table).ToArray();

            Assert.AreEqual(2, data.Length);
            var result = instance.Deserialize(data);

            Assert.AreEqual(2, result.Count);
            Assert.AreEqual("1", result["Test"]);
            Assert.AreEqual("2", result["Test2"]);

            List <KeyValuePair <string, string> > list = new List <KeyValuePair <string, string> >();

            list.AddRange(data);
            list.AddRange(data);
            var stream = instance.DeserializeStream(list).ToArray();

            Assert.AreEqual(2, stream.Length);
        }
        public void SaveConfiguration()
        {
            if (ConfigurationType == LibNodaveConnectionConfigurationType.RegistrySavedConfiguration)
            {
#if !IPHONE
                DictionarySerializer <String, PLCConnectionConfiguration> ConnectionsDicSer = new DictionarySerializer <string, PLCConnectionConfiguration>();

                Dictionary <String, PLCConnectionConfiguration> Connections = null;
                if (File.Exists(ConfigurationPathAndFilename))
                {
                    StreamReader strm = new StreamReader(ConfigurationPathAndFilename);
                    Connections = ConnectionsDicSer.Deserialize(strm);
                    //string txt = strm.ReadToEnd();
                    strm.Close();
                    //Connections = General.SerializeToString<Dictionary<String, PLCConnectionConfiguration>>.DeSerialize(txt);
                }
                if (Connections == null)
                {
                    Connections = new Dictionary <string, PLCConnectionConfiguration>();
                }

                if (Connections.ContainsKey(ConnectionName))
                {
                    Connections.Remove(ConnectionName);
                }

                Connections.Add(ConnectionName, this);

                Directory.CreateDirectory(Path.GetDirectoryName(ConfigurationPathAndFilename));
                StreamWriter sstrm = new StreamWriter(ConfigurationPathAndFilename, false);
                ConnectionsDicSer.Serialize(Connections, sstrm);
                //sstrm.Write(stxt);
                //sstrm.Flush();
                sstrm.Close();

                return;

                RegistryKey myConnectionKey =
                    Registry.CurrentUser.CreateSubKey(
                        "Software\\JFKSolutions\\WPFToolboxForSiemensPLCs\\Connections\\" + ConnectionName);
                if (myConnectionKey != null)
                {
                    myConnectionKey.SetValue("EntryPoint", this.EntryPoint);
                    myConnectionKey.SetValue("CpuRack", this.CpuRack);
                    myConnectionKey.SetValue("CpuSlot", this.CpuSlot);
                    myConnectionKey.SetValue("CpuMpi", this.CpuMpi);
                    myConnectionKey.SetValue("CpuIP", this.CpuIP);
                    myConnectionKey.SetValue("LokalMpi", this.LokalMpi);
                    myConnectionKey.SetValue("ComPort", this.ComPort);
                    myConnectionKey.SetValue("ConnectionType", this.ConnectionType);
                    myConnectionKey.SetValue("BusSpeed", this.BusSpeed);
                    myConnectionKey.SetValue("NetLinkReset", this.NetLinkReset);
                    myConnectionKey.SetValue("ComPortSpeed", this.ComPortSpeed);
                    myConnectionKey.SetValue("ComPortParity", this.ComPortParity);
                    myConnectionKey.SetValue("Routing", this.Routing);
                    myConnectionKey.SetValue("RoutingDestinationRack", this.RoutingDestinationRack);
                    myConnectionKey.SetValue("RoutingDestinationSlot", this.RoutingDestinationSlot);
                    myConnectionKey.SetValue("RoutingSubnet1", this.RoutingSubnet1);
                    myConnectionKey.SetValue("RoutingSubnet2", this.RoutingSubnet2);
                    myConnectionKey.SetValue("RoutingDestination", this.RoutingDestination);
                    myConnectionKey.SetValue("Port", this.Port);
                    myConnectionKey.SetValue("WritePort", this.WritePort);
                    myConnectionKey.SetValue("PLCConnectionType", this.PLCConnectionType);
                    myConnectionKey.SetValue("RoutingPLCConnectionType", this.RoutingPLCConnectionType);
                    myConnectionKey.SetValue("Timeout", this.Timeout);
                    myConnectionKey.SetValue("TimeoutIPConnect", this.TimeoutIPConnect);
                }
#endif
            }
        }
        public void ReloadConfiguration()
        {
            if (ConfigurationType == LibNodaveConnectionConfigurationType.RegistrySavedConfiguration)
            {
#if !IPHONE
                if (File.Exists(ConfigurationPathAndFilename))
                {
                    DictionarySerializer <String, PLCConnectionConfiguration> ConnectionsDicSer = new DictionarySerializer <string, PLCConnectionConfiguration>();

                    Dictionary <String, PLCConnectionConfiguration> Connections = null;
                    StreamReader strm = new StreamReader(ConfigurationPathAndFilename);
                    Connections = ConnectionsDicSer.Deserialize(strm);
                    //string txt = strm.ReadToEnd();
                    strm.Close();
                    //Connections = General.SerializeToString<Dictionary<String, PLCConnectionConfiguration>>.DeSerialize(txt);
                    if (Connections != null && Connections.ContainsKey(ConnectionName))
                    {
                        PLCConnectionConfiguration akConf = Connections[ConnectionName];
                        this.EntryPoint             = akConf.EntryPoint;
                        this.CpuRack                = akConf.CpuRack;
                        this.CpuSlot                = akConf.CpuSlot;
                        this.CpuMpi                 = akConf.CpuMpi;
                        this.CpuIP                  = akConf.CpuIP;
                        this.LokalMpi               = akConf.LokalMpi;
                        this.ComPort                = akConf.ComPort;
                        this.ConnectionType         = akConf.ConnectionType;
                        this.BusSpeed               = akConf.BusSpeed;
                        this.NetLinkReset           = akConf.NetLinkReset;
                        this.ComPortSpeed           = akConf.ComPortSpeed;
                        this.ComPortParity          = akConf.ComPortParity;
                        this.Routing                = akConf.Routing;
                        this.RoutingDestinationRack = akConf.RoutingDestinationRack;
                        this.RoutingDestinationSlot = akConf.RoutingDestinationSlot;
                        this.RoutingSubnet1         = akConf.RoutingSubnet1;
                        this.RoutingSubnet2         = akConf.RoutingSubnet2;
                        this.RoutingDestination     = akConf.RoutingDestination;
                        this.Port      = akConf.Port;
                        this.WritePort = akConf.WritePort;
                        this.UseShortDataBlockRequest = akConf.UseShortDataBlockRequest;

                        this.PLCConnectionType        = akConf.PLCConnectionType;
                        this.RoutingPLCConnectionType = akConf.RoutingPLCConnectionType;

                        this.Timeout          = akConf.Timeout;
                        this.TimeoutIPConnect = akConf.TimeoutIPConnect;
                    }
                }
                return;


                RegistryKey myConnectionKey =
                    Registry.CurrentUser.CreateSubKey(
                        "Software\\JFKSolutions\\WPFToolboxForSiemensPLCs\\Connections\\" + ConnectionName);
                if (myConnectionKey != null)
                {
                    this.EntryPoint             = (String)myConnectionKey.GetValue("EntryPoint", "S7ONLINE");
                    this.CpuRack                = Convert.ToInt32(myConnectionKey.GetValue("CpuRack", "0"));
                    this.CpuSlot                = Convert.ToInt32(myConnectionKey.GetValue("CpuSlot", "2"));
                    this.CpuMpi                 = Convert.ToInt32(myConnectionKey.GetValue("CpuMpi", "2"));
                    this.CpuIP                  = (String)myConnectionKey.GetValue("CpuIP", "192.168.1.1");
                    this.LokalMpi               = Convert.ToInt32(myConnectionKey.GetValue("LokalMpi", "0"));
                    this.ComPort                = (String)myConnectionKey.GetValue("ComPort", "");
                    this.ConnectionType         = Convert.ToInt32(myConnectionKey.GetValue("ConnectionType", "1"));
                    this.BusSpeed               = Convert.ToInt32(myConnectionKey.GetValue("BusSpeed", "2"));
                    this.NetLinkReset           = Convert.ToBoolean(myConnectionKey.GetValue("NetLinkReset", "false"));
                    this.ComPortSpeed           = (String)myConnectionKey.GetValue("ComPortSpeed", "38400");
                    this.ComPortParity          = Convert.ToInt32(myConnectionKey.GetValue("ComPortParity", "1"));
                    this.Routing                = Convert.ToBoolean(myConnectionKey.GetValue("Routing", "false"));
                    this.RoutingDestinationRack =
                        Convert.ToInt32(myConnectionKey.GetValue("RoutingDestinationRack", "0"));
                    this.RoutingDestinationSlot =
                        Convert.ToInt32(myConnectionKey.GetValue("RoutingDestinationSlot", "2"));
                    this.RoutingSubnet1     = Convert.ToInt32(myConnectionKey.GetValue("RoutingSubnet1", "0"));
                    this.RoutingSubnet2     = Convert.ToInt32(myConnectionKey.GetValue("RoutingSubnet2", "0"));
                    this.RoutingDestination = Convert.ToString(myConnectionKey.GetValue("RoutingDestination", "2"));
                    this.Port      = Convert.ToInt32(myConnectionKey.GetValue("Port", "102"));
                    this.WritePort = Convert.ToInt32(myConnectionKey.GetValue("WritePort", "30501"));

                    this.PLCConnectionType        = Convert.ToInt32(myConnectionKey.GetValue("PLCConnectionType", "1"));
                    this.RoutingPLCConnectionType = Convert.ToInt32(myConnectionKey.GetValue("RoutingPLCConnectionType", "1"));

                    this.Timeout          = Convert.ToInt32(myConnectionKey.GetValue("Timeout", "5000000"));
                    this.TimeoutIPConnect = Convert.ToInt32(myConnectionKey.GetValue("TimeoutIPConnect", "5000"));
                }
#endif
            }
            else
            {
                if (!_initDone)
                {
                    this.ConnectionType   = 122;
                    this.CpuMpi           = 2;
                    this.EntryPoint       = "S7ONLINE";
                    this.CpuIP            = "192.168.1.1";
                    this.CpuRack          = 0;
                    this.CpuSlot          = 2;
                    this.Port             = 102;
                    this.TimeoutIPConnect = 5000;
                    this.Timeout          = 5000000;
                    _initDone             = true;
                }
            }
        }
        public void SaveConfiguration()
        {
            if (ConfigurationType == LibNodaveConnectionConfigurationType.RegistrySavedConfiguration)
            {
#if !IPHONE

                DictionarySerializer<String, PLCConnectionConfiguration> ConnectionsDicSer = new DictionarySerializer<string, PLCConnectionConfiguration>();
                    
                Dictionary<String, PLCConnectionConfiguration> Connections = null;
                if (File.Exists(ConfigurationPathAndFilename))
                {
                    StreamReader strm = new StreamReader(ConfigurationPathAndFilename);
                    Connections = ConnectionsDicSer.Deserialize(strm);
                    //string txt = strm.ReadToEnd();
                    strm.Close();
                    //Connections = General.SerializeToString<Dictionary<String, PLCConnectionConfiguration>>.DeSerialize(txt);                    
                }
                if (Connections == null)
                    Connections = new Dictionary<string, PLCConnectionConfiguration>();

                if (Connections.ContainsKey(ConnectionName))
                    Connections.Remove(ConnectionName);

                Connections.Add(ConnectionName, this);

                Directory.CreateDirectory(Path.GetDirectoryName(ConfigurationPathAndFilename));
                StreamWriter sstrm = new StreamWriter(ConfigurationPathAndFilename, false);
                ConnectionsDicSer.Serialize(Connections, sstrm);
                //sstrm.Write(stxt);
                //sstrm.Flush();
                sstrm.Close();

                return;

                RegistryKey myConnectionKey =
                    Registry.CurrentUser.CreateSubKey(
                        "Software\\JFKSolutions\\WPFToolboxForSiemensPLCs\\Connections\\" + ConnectionName);
                if (myConnectionKey != null)
                {
                    myConnectionKey.SetValue("EntryPoint", this.EntryPoint);
                    myConnectionKey.SetValue("CpuRack", this.CpuRack);
                    myConnectionKey.SetValue("CpuSlot", this.CpuSlot);
                    myConnectionKey.SetValue("CpuMpi", this.CpuMpi);
                    myConnectionKey.SetValue("CpuIP", this.CpuIP);
                    myConnectionKey.SetValue("LokalMpi", this.LokalMpi);
                    myConnectionKey.SetValue("ComPort", this.ComPort);
                    myConnectionKey.SetValue("ConnectionType", this.ConnectionType);
                    myConnectionKey.SetValue("BusSpeed", this.BusSpeed);
                    myConnectionKey.SetValue("NetLinkReset", this.NetLinkReset);
                    myConnectionKey.SetValue("ComPortSpeed", this.ComPortSpeed);
                    myConnectionKey.SetValue("ComPortParity", this.ComPortParity);
                    myConnectionKey.SetValue("Routing", this.Routing);
                    myConnectionKey.SetValue("RoutingDestinationRack", this.RoutingDestinationRack);
                    myConnectionKey.SetValue("RoutingDestinationSlot", this.RoutingDestinationSlot);
                    myConnectionKey.SetValue("RoutingSubnet1", this.RoutingSubnet1);
                    myConnectionKey.SetValue("RoutingSubnet2", this.RoutingSubnet2);
                    myConnectionKey.SetValue("RoutingDestination", this.RoutingDestination);
                    myConnectionKey.SetValue("Port", this.Port);
                    myConnectionKey.SetValue("PLCConnectionType", this.PLCConnectionType);
                    myConnectionKey.SetValue("RoutingPLCConnectionType", this.RoutingPLCConnectionType);
                    myConnectionKey.SetValue("Timeout", this.Timeout);
                    myConnectionKey.SetValue("TimeoutIPConnect", this.TimeoutIPConnect);
                }
#endif
            }
        }
        public static void DeleteConfiguration(string ConnectionName)
        {
#if !IPHONE
            try
            {
                DictionarySerializer<String, PLCConnectionConfiguration> ConnectionsDicSer = new DictionarySerializer<string, PLCConnectionConfiguration>();

                Dictionary<String, PLCConnectionConfiguration> Connections = null;
                if (File.Exists(ConfigurationPathAndFilename))
                {
                    StreamReader strm = new StreamReader(ConfigurationPathAndFilename);
                    Connections = ConnectionsDicSer.Deserialize(strm);
                    //string txt = strm.ReadToEnd();
                    strm.Close();
                    //Connections = General.SerializeToString<Dictionary<String, PLCConnectionConfiguration>>.DeSerialize(txt);                    
                }
                if (Connections == null)
                    Connections = new Dictionary<string, PLCConnectionConfiguration>();

                if (Connections.ContainsKey(ConnectionName))
                    Connections.Remove(ConnectionName);

                Directory.CreateDirectory(Path.GetDirectoryName(ConfigurationPathAndFilename));
                StreamWriter sstrm = new StreamWriter(ConfigurationPathAndFilename, false);
                ConnectionsDicSer.Serialize(Connections, sstrm);
                //sstrm.Write(stxt);
                //sstrm.Flush();
                sstrm.Close();

                return;

                Registry.CurrentUser.DeleteSubKeyTree(
                    "Software\\JFKSolutions\\WPFToolboxForSiemensPLCs\\Connections\\" + ConnectionName);
            }
            catch (Exception)
            { }
#endif
        }
        public void ReloadConfiguration()
        {
            if (ConfigurationType == LibNodaveConnectionConfigurationType.RegistrySavedConfiguration)
            {
#if !IPHONE

                if (File.Exists(ConfigurationPathAndFilename))
                {
                    DictionarySerializer<String, PLCConnectionConfiguration> ConnectionsDicSer = new DictionarySerializer<string, PLCConnectionConfiguration>();

                    Dictionary<String, PLCConnectionConfiguration> Connections = null;
                    StreamReader strm = new StreamReader(ConfigurationPathAndFilename);
                    Connections = ConnectionsDicSer.Deserialize(strm);
                    //string txt = strm.ReadToEnd();
                    strm.Close();
                    //Connections = General.SerializeToString<Dictionary<String, PLCConnectionConfiguration>>.DeSerialize(txt);                    
                    if (Connections != null && Connections.ContainsKey(ConnectionName))
                    {
                        PLCConnectionConfiguration akConf = Connections[ConnectionName];
                        this.EntryPoint = akConf.EntryPoint;
                        this.CpuRack = akConf.CpuRack;
                        this.CpuSlot = akConf.CpuSlot;
                        this.CpuMpi = akConf.CpuMpi;
                        this.CpuIP = akConf.CpuIP;
                        this.LokalMpi = akConf.LokalMpi;
                        this.ComPort = akConf.ComPort;
                        this.ConnectionType = akConf.ConnectionType;
                        this.BusSpeed = akConf.BusSpeed;
                        this.NetLinkReset = akConf.NetLinkReset;
                        this.ComPortSpeed = akConf.ComPortSpeed;
                        this.ComPortParity = akConf.ComPortParity;
                        this.Routing = akConf.Routing;
                        this.RoutingDestinationRack = akConf.RoutingDestinationRack;
                        this.RoutingDestinationSlot = akConf.RoutingDestinationSlot;
                        this.RoutingSubnet1 = akConf.RoutingSubnet1;
                        this.RoutingSubnet2 = akConf.RoutingSubnet2;
                        this.RoutingDestination = akConf.RoutingDestination;
                        this.Port = akConf.Port;

                        this.PLCConnectionType = akConf.PLCConnectionType;
                        this.RoutingPLCConnectionType = akConf.RoutingPLCConnectionType;

                        this.Timeout = akConf.Timeout;
                        this.TimeoutIPConnect = akConf.TimeoutIPConnect;
                    }
                }
                return;


                RegistryKey myConnectionKey =
                    Registry.CurrentUser.CreateSubKey(
                        "Software\\JFKSolutions\\WPFToolboxForSiemensPLCs\\Connections\\" + ConnectionName);
                if (myConnectionKey != null)
                {
                    this.EntryPoint = (String)myConnectionKey.GetValue("EntryPoint", "S7ONLINE");
                    this.CpuRack = Convert.ToInt32(myConnectionKey.GetValue("CpuRack", "0"));
                    this.CpuSlot = Convert.ToInt32(myConnectionKey.GetValue("CpuSlot", "2"));
                    this.CpuMpi = Convert.ToInt32(myConnectionKey.GetValue("CpuMpi", "2"));
                    this.CpuIP = (String)myConnectionKey.GetValue("CpuIP", "192.168.1.1");
                    this.LokalMpi = Convert.ToInt32(myConnectionKey.GetValue("LokalMpi", "0"));
                    this.ComPort = (String)myConnectionKey.GetValue("ComPort", "");
                    this.ConnectionType = Convert.ToInt32(myConnectionKey.GetValue("ConnectionType", "1"));
                    this.BusSpeed = Convert.ToInt32(myConnectionKey.GetValue("BusSpeed", "2"));
                    this.NetLinkReset = Convert.ToBoolean(myConnectionKey.GetValue("NetLinkReset", "false"));
                    this.ComPortSpeed = (String)myConnectionKey.GetValue("ComPortSpeed", "38400");
                    this.ComPortParity = Convert.ToInt32(myConnectionKey.GetValue("ComPortParity", "1"));
                    this.Routing = Convert.ToBoolean(myConnectionKey.GetValue("Routing", "false"));
                    this.RoutingDestinationRack =
                        Convert.ToInt32(myConnectionKey.GetValue("RoutingDestinationRack", "0"));
                    this.RoutingDestinationSlot =
                        Convert.ToInt32(myConnectionKey.GetValue("RoutingDestinationSlot", "2"));
                    this.RoutingSubnet1 = Convert.ToInt32(myConnectionKey.GetValue("RoutingSubnet1", "0"));
                    this.RoutingSubnet2 = Convert.ToInt32(myConnectionKey.GetValue("RoutingSubnet2", "0"));
                    this.RoutingDestination = Convert.ToString(myConnectionKey.GetValue("RoutingDestination", "2"));
                    this.Port = Convert.ToInt32(myConnectionKey.GetValue("Port", "102"));

                    this.PLCConnectionType = Convert.ToInt32(myConnectionKey.GetValue("PLCConnectionType", "1"));
                    this.RoutingPLCConnectionType = Convert.ToInt32(myConnectionKey.GetValue("RoutingPLCConnectionType", "1"));

                    this.Timeout = Convert.ToInt32(myConnectionKey.GetValue("Timeout", "5000000"));
                    this.TimeoutIPConnect = Convert.ToInt32(myConnectionKey.GetValue("TimeoutIPConnect", "5000"));
                }
#endif
            }
            else
            {
                if (!_initDone)
                {
                    this.ConnectionType = 122;
                    this.CpuMpi = 2;
                    this.EntryPoint = "S7ONLINE";
                    this.CpuIP = "192.168.1.1";
                    this.CpuRack = 0;
                    this.CpuSlot = 2;
                    this.Port = 102;
                    this.TimeoutIPConnect = 5000;
                    this.Timeout = 5000000;
                    _initDone = true;
                }
            }
        }
        public static String[] GetConfigurationNames()
        {
#if !IPHONE
            if (File.Exists(ConfigurationPathAndFilename))
            {
                DictionarySerializer<String, PLCConnectionConfiguration> ConnectionsDicSer = new DictionarySerializer<string, PLCConnectionConfiguration>();
                
                Dictionary<String, PLCConnectionConfiguration> Connections = null;
                    StreamReader strm = new StreamReader(ConfigurationPathAndFilename);
                    Connections = ConnectionsDicSer.Deserialize(strm);
                    //string txt = strm.ReadToEnd();
                    strm.Close();
                    //Connections = General.SerializeToString<Dictionary<String, PLCConnectionConfiguration>>.DeSerialize(txt);                    
                    if (Connections != null)
                    {
                        string[] Names = new string[Connections.Count];
                        Connections.Keys.CopyTo(Names, 0);
                        return Names;
                    }
            }
            return new string[0];

            RegistryKey myConnectionKey =
                Registry.CurrentUser.CreateSubKey("Software\\JFKSolutions\\WPFToolboxForSiemensPLCs\\Connections");
            return myConnectionKey.GetSubKeyNames();
#else
			return null;
#endif
        }
Beispiel #26
0
        /// <summary>
        /// Receives a message from the logical queue specified as this instance's input queue. What actually
        /// happens, is that a row is read and locked in the messages table, whereafter it is deleted.
        /// </summary>
        public ReceivedTransportMessage ReceiveMessage(ITransactionContext context)
        {
            try
            {
                AssertNotInOneWayClientMode();

                var connection = GetConnectionPossiblyFromContext(context);

                try
                {
                    ReceivedTransportMessage receivedTransportMessage = null;

                    using (var selectCommand = connection.Connection.CreateCommand())
                    {
                        selectCommand.Transaction = connection.Transaction;

                        //                    selectCommand.CommandText =
                        //                        string.Format(
                        //                            @"
                        //                                ;with msg as (
                        //	                                select top 1 [seq], [headers], [label], [body]
                        //		                                from [{0}]
                        //                                        with (updlock, readpast, rowlock)
                        //		                                where [recipient] = @recipient
                        //		                                order by [seq] asc
                        //	                                )
                        //                                delete msg
                        //                                output deleted.seq, deleted.headers, deleted.body, deleted.label
                        //",
                        //                            messageTableName);

                        selectCommand.CommandText =
                            string.Format(@"
                                    select top 1 [seq], [headers], [label], [body], [priority]
		                                from [{0}]
                                        with (updlock, readpast, rowlock)
		                                where [recipient] = @recipient
		                                order by [priority] asc, [seq] asc
", messageTableName);

                        //                    selectCommand.CommandText =
                        //                        string.Format(@"
                        //delete top(1) from [{0}]
                        //output deleted.seq, deleted.headers, deleted.body, deleted.label
                        //where [seq] = (
                        //    select min([seq]) from [{0}] with (readpast, holdlock) where recipient = @recipient
                        //)
                        //", messageTableName);

                        selectCommand.Parameters.Add("recipient", SqlDbType.NVarChar, 200)
                        .Value = inputQueueName;

                        var seq      = 0L;
                        var priority = -1;

                        using (var reader = selectCommand.ExecuteReader())
                        {
                            if (reader.Read())
                            {
                                var headers = reader["headers"];
                                var label   = reader["label"];
                                var body    = reader["body"];
                                seq      = (long)reader["seq"];
                                priority = (byte)reader["priority"];

                                var headersDictionary = DictionarySerializer.Deserialize((string)headers);
                                var messageId         = seq.ToString(CultureInfo.InvariantCulture);

                                receivedTransportMessage =
                                    new ReceivedTransportMessage
                                {
                                    Id      = messageId,
                                    Label   = (string)label,
                                    Headers = headersDictionary,
                                    Body    = (byte[])body,
                                };

                                log.Debug("Received message with ID {0} from logical queue {1}.{2}",
                                          messageId, messageTableName, inputQueueName);
                            }
                        }

                        if (receivedTransportMessage != null)
                        {
                            using (var deleteCommand = connection.Connection.CreateCommand())
                            {
                                deleteCommand.Transaction = connection.Transaction;

                                deleteCommand.CommandText =
                                    string.Format(
                                        "delete from [{0}] where [recipient] = @recipient and [priority] = @priority and [seq] = @seq",
                                        messageTableName);

                                deleteCommand.Parameters.Add("recipient", SqlDbType.NVarChar, 200)
                                .Value = inputQueueName;
                                deleteCommand.Parameters.Add("seq", SqlDbType.BigInt, 8)
                                .Value = seq;
                                deleteCommand.Parameters.Add("priority", SqlDbType.TinyInt, 1)
                                .Value = priority;

                                var rowsAffected = deleteCommand.ExecuteNonQuery();

                                if (rowsAffected != 1)
                                {
                                    throw new ApplicationException(
                                              string.Format(
                                                  "Attempted to delete message with recipient = '{0}' and seq = {1}, but {2} rows were affected!",
                                                  inputQueueName, seq, rowsAffected));
                                }
                            }
                        }
                    }

                    if (!context.IsTransactional)
                    {
                        commitAction(connection);
                    }

                    return(receivedTransportMessage);
                }
                finally
                {
                    if (!context.IsTransactional)
                    {
                        releaseConnection(connection);
                    }
                }
            }
            catch (Exception exception)
            {
                // if we end up here, something bas has happened - no need to hurry, so we sleep
                Thread.Sleep(2000);

                throw new ApplicationException(
                          string.Format("An error occurred while receiving message from {0}", inputQueueName),
                          exception);
            }
        }