示例#1
0
        private void InitializeObject()
        {
            GameObject targetObject = new GameObject();

            gen2 = targetObject.AddComponent <Gen2>();
            UnityEngine.Object.DontDestroyOnLoad(targetObject);
        }
示例#2
0
    public static int Main()
    {
        Gen <string>          gs   = new Gen <string> ();
        Gen2 <string, object> g2so = new Gen2 <string, object> ();
        Gen2 <string, string> g2ss = new Gen2 <string, string> ();
        Gen2 <string, ClassA> g2sa = new Gen2 <string, ClassA> ();
        Gen2 <string, int>    g2si = new Gen2 <string, int> ();

        if (g2so.makeDict(gs).GetType() != typeof(Dictionary <string, object>))
        {
            return(1);
        }
        if (g2ss.makeDict(gs).GetType() != typeof(Dictionary <string, string>))
        {
            return(1);
        }
        if (g2sa.makeDict(gs).GetType() != typeof(Dictionary <string, ClassA>))
        {
            return(1);
        }
        if (g2si.makeDict(gs).GetType() != typeof(Dictionary <string, int>))
        {
            return(1);
        }

        return(0);
    }
示例#3
0
    public static void Main()
    {
        Gen2 <string, int> x = new Gen2 <string, int>("Value is: ", 99);

        Console.Write(x.getob());
        Console.WriteLine(x.getob2());
    }
        public void LoadUserMemory(Reader reader, uint address, Gen2.Bank selectedBank, TagReadRecord selectedTagRed, string readerModel)
        {
            objReader = reader;
            startAddress = address;
            model = readerModel;
            spUserMemory.IsEnabled = true;
            rbFirstTagUserMemTb.IsEnabled = true;
            rbSelectedTagUserMemTb.IsChecked = true;
            rbSelectedTagUserMemTb.IsEnabled = true;

            lblUserMemoryError.Content = "";
            lblErrorAddAsciiEdtr.Content = "";
            lblErrorAddHexEdtr.Content = "";
            
            btnRead.Content = "Refresh";
            selectedTagReadRecord = selectedTagRed;
            antenna = selectedTagRed.Antenna;
            selectMemBank = selectedBank;
            //txtEPCData.Text = selectedTagRed.EPC;
            string[] stringData = selectedTagRed.Data.Split(' ');
            txtEpc.Text = selectedTagRed.EPC;
            currentEPC = txtEpc.Text;
            txtData.Text = string.Join("", stringData);
            Window mainWindow = App.Current.MainWindow;
            ucTagResults tagResults = (ucTagResults)mainWindow.FindName("TagResults");
            switch (selectedBank)
            {
                case Gen2.Bank.EPC:
                    if (tagResults.txtSelectedCell.Text == "Data")
                    {
                        lblSelectFilter.Content = "Showing tag: EPC data at decimal address " + address.ToString() + "  = " + txtData.Text;
                    }
                    else
                    {
                        lblSelectFilter.Content = "Showing tag: EPC ID = " + selectedTagRed.EPC;
                    }
                    break;
                case Gen2.Bank.TID:
                    if (tagResults.txtSelectedCell.Text == "Data")
                    {
                        lblSelectFilter.Content = "Showing tag: TID data at decimal address " + address.ToString() + " = " + txtData.Text;
                    }
                    else
                    {
                        lblSelectFilter.Content = "Showing tag: EPC ID = " + selectedTagRed.EPC;
                    }
                    break;
                case Gen2.Bank.USER:
                    if (tagResults.txtSelectedCell.Text == "Data")
                    {
                        lblSelectFilter.Content = "Showing tag: User data at decimal address " + address.ToString() + " = " + txtData.Text;
                    }
                    else
                    {
                        lblSelectFilter.Content = "Showing tag: EPC ID = " + selectedTagRed.EPC;
                    }
                    break;
            }
            PopulateUserData();
        }
示例#5
0
 /// <summary>
 /// Gets the Generation the <see cref="GameVersion"/> belongs to.
 /// </summary>
 /// <param name="game">Game to retrieve the generation for</param>
 /// <returns>Generation ID</returns>
 public static int GetGeneration(this GameVersion game)
 {
     if (Gen1.Contains(game))
     {
         return(1);
     }
     if (Gen2.Contains(game))
     {
         return(2);
     }
     if (Gen3.Contains(game))
     {
         return(3);
     }
     if (Gen4.Contains(game))
     {
         return(4);
     }
     if (Gen5.Contains(game))
     {
         return(5);
     }
     if (Gen6.Contains(game))
     {
         return(6);
     }
     if (Gen7.Contains(game))
     {
         return(7);
     }
     return(-1);
 }
示例#6
0
    static void Main()
    {
        // Create a Gen2 object for string and int.
        Gen2 <string, int> x = new Gen2 <string, int>("Value is: ", 99);

        Console.Write(x.GetOb());
        Console.WriteLine(x.GetObj2());
    }
    public static void goGen2()
    {
        Gen2 <int> gen2 = new Gen2 <int>();

        gen2.t = 5;

        Console.WriteLine("Gen2: FAIL");
    }
    public static void Main()
    {
        Gen <int> iOb = new Gen <int>(88);

        Console.WriteLine(iOb.getob());

        iOb = new Gen2 <int>(99);

        Console.WriteLine(iOb.getob());
    }
        public void Load(Reader reader,uint address, int length, Gen2.Bank selectedBank,TagReadRecord selectedTagRed)
        {
            InitializeComponent();
            objReader = reader;
            startAddress = address;
            dataLength = length;
            selectMemBank = selectedBank;

            spWriteEPC.IsEnabled = true;
            rbSelectedTag.IsChecked = true;
            rbSelectedTag.IsEnabled = true;
            
            string[] stringData = selectedTagRed.Data.Split(' ');
            txtEpc.Text = selectedTagRed.EPC;
            txtData.Text = string.Join("", stringData);
            Window mainWindow = App.Current.MainWindow;
            ucTagResults tagResults = (ucTagResults)mainWindow.FindName("TagResults");
            switch(selectedBank)
            {
                case Gen2.Bank.EPC:                    
                    if (tagResults.txtSelectedCell.Text == "Data")
                    {
                        lblSelectFilter.Content = "EPC Memory, Decimal Address = " + address.ToString() + " and Data = " + txtData.Text;
                    }
                    else
                    {
                        lblSelectFilter.Content = "EPC ID = " + selectedTagRed.EPC;
                    }
                    break;
                case Gen2.Bank.TID:
                    if (tagResults.txtSelectedCell.Text == "Data")
                    {
                        lblSelectFilter.Content = "TID Memory, Decimal Address = " + address.ToString() + " and Data = " + txtData.Text;
                    }
                    else
                    {
                        lblSelectFilter.Content = "EPC ID = " + selectedTagRed.EPC;
                    }
                    break;
                case Gen2.Bank.USER:
                    if (tagResults.txtSelectedCell.Text == "Data")
                    {
                        lblSelectFilter.Content = "User Memory, Decimal Address = " + address.ToString() + " and Data = " + txtData.Text;
                    }
                    else
                    {
                        lblSelectFilter.Content = "EPC ID = " + selectedTagRed.EPC;
                    }                    
                    break;
            }            
            txtCurrentEpc.Text = selectedTagRed.EPC;
            currentEpc = txtCurrentEpc.Text;
            antenna = selectedTagRed.Antenna;
        }
示例#10
0
        public static void Run()
        {
            if (Gen2 <string> .GetFromClassParam() != "Hello")
            {
                throw new Exception();
            }

            if (Gen2 <string> .GetFromMethodParam() != "World")
            {
                throw new Exception();
            }
        }
示例#11
0
    public static void TestMain()
    {
        Gen4 <A, B> ab = new Gen4 <A, B>();
        Gen4 <A, A> aa = new Gen4 <A, A>();

        XY <int>    xy  = new XY <int>(11, 22);
        XY <double> xyD = new XY <double>(3.4, 4.3);

        System.Console.WriteLine(xy.x + " " + xy.y);
        System.Console.WriteLine(xyD.x + " " + xyD.y);

        Gen2 <string, int> gen2 = new Gen2 <string, int>("New value: ", 99);

        System.Console.WriteLine(gen2.GetObj() + " " + gen2.GetObj2());
    }
示例#12
0
    static void Main()
    {
        // Create a Gen object for int.
        Gen <int> iOb = new Gen <int>(88);

        // This calls Gen’s version of GetOb().
        Console.WriteLine(iOb.GetOb());

        // Now, create a Gen2 object and assign its
        // reference to iOb (which is a Gen<int> variable).
        iOb = new Gen2 <int>(99);

        // This calls Gen2’s version of GetOb().
        Console.WriteLine(iOb.GetOb());
    }
示例#13
0
        public static void Run()
        {
            if (Gen2 <string> .GetFromClassParam() != "Hello")
            {
                throw new Exception();
            }

            if (Gen2 <string> .GetFromMethodParam() != "World")
            {
                throw new Exception();
            }

            if (NonGeneric.Get <object>(new object[0]) != "Hi there")
            {
                throw new Exception();
            }
        }
示例#14
0
 /// <summary>
 /// Gets the Generation the <see cref="GameVersion"/> belongs to.
 /// </summary>
 /// <param name="game">Game to retrieve the generation for</param>
 /// <returns>Generation ID</returns>
 public static int GetMaxSpeciesID(this GameVersion game)
 {
     if (Gen1.Contains(game))
     {
         return(Legal.MaxSpeciesID_1);
     }
     if (Gen2.Contains(game))
     {
         return(Legal.MaxSpeciesID_2);
     }
     if (Gen3.Contains(game))
     {
         return(Legal.MaxSpeciesID_3);
     }
     if (Gen4.Contains(game))
     {
         return(Legal.MaxSpeciesID_4);
     }
     if (Gen5.Contains(game))
     {
         return(Legal.MaxSpeciesID_5);
     }
     if (Gen6.Contains(game))
     {
         return(Legal.MaxSpeciesID_6);
     }
     if (Gen7.Contains(game))
     {
         if (SM.Contains(game))
         {
             return(Legal.MaxSpeciesID_7);
         }
         if (USUM.Contains(game))
         {
             return(Legal.MaxSpeciesID_7_USUM);
         }
         if (GG.Contains(game))
         {
             return(Legal.MaxSpeciesID_7b);
         }
         return(Legal.MaxSpeciesID_7_USUM);
     }
     return(-1);
 }
示例#15
0
文件: GameUtil.cs 项目: wooddice/pkNX
 /// <summary>
 /// Gets the Generation the <see cref="GameVersion"/> belongs to.
 /// </summary>
 /// <param name="game">Game to retrieve the generation for</param>
 /// <returns>Generation ID</returns>
 public static int GetMaxSpeciesID(this GameVersion game)
 {
     if (Gen1.Contains(game))
     {
         return(151);
     }
     if (Gen2.Contains(game))
     {
         return(251);
     }
     if (Gen3.Contains(game))
     {
         return(384);
     }
     if (Gen4.Contains(game))
     {
         return(493);
     }
     if (Gen5.Contains(game))
     {
         return(649);
     }
     if (Gen6.Contains(game))
     {
         return(Legal.MaxSpeciesID_6);
     }
     if (Gen7.Contains(game))
     {
         if (SM.Contains(game))
         {
             return(802);
         }
         if (USUM.Contains(game))
         {
             return(807);
         }
         return(Legal.MaxSpeciesID_7_GG);
     }
     return(-1);
 }
示例#16
0
        private void EnterKeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                e.SuppressKeyPress = true;
                switch (this.ActiveControl.Name)
                {
                case "Gen1":
                    Gen2.Focus();
                    break;

                case "Gen2":
                    generClick();
                    textBox1.Focus();
                    break;

                case "textBox1":
                    if (fwdClicksCount != everything.Length - 1)
                    {
                        button1_Click(button1, new EventArgs());
                    }
                    else
                    {
                        generateButton_Click(generateButton, new EventArgs());
                        genLabel.Focus();
                    }
                    break;

                case "searchTB":
                    button3_Click(button3, new EventArgs());
                    break;

                default:

                    MessageBox.Show("Не жми на Enter просто так", "Avtor dodik", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    break;
                }
            }
        }
示例#17
0
 /// <summary>
 /// Constructor to initialize the parameters of NxpEasAlarm
 /// </summary>
 /// <param name="dr">Gen2 divide ratio to use</param>
 /// <param name="m">Gen2 M parameter to use</param>
 /// <param name="trExt">Gen2 TrExt value to use</param>
 public EasAlarm(Gen2.DivideRatio dr, Gen2.TagEncoding m, Gen2.TrExt trExt)
 {
     this.DivideRatio = dr;
     this.TagEncoding = m;
     this.TrExt = trExt;
 }
示例#18
0
            /// <summary>
            /// Constructor to initialize the parameters of BlockPermaLock
            /// </summary>
            /// <param name="readLock">Read or Lock?</param>
            /// <param name="bank">Gen2 Memory Bank to perform Lock</param>
            /// <param name="blockPtr">starting address of the blocks to operate</param>
            /// <param name="blockRange">number of 16 blocks</param>
            /// <param name="mask">mask</param>
         
            public BlockPermaLock(byte readLock,Gen2.Bank bank, uint blockPtr, byte blockRange, ushort[] mask)
            {
                this.ReadLock = readLock;
                this.Bank = bank;
                this.BlockPtr = blockPtr;
                this.BlockRange = blockRange;
                this.Mask = mask;

            }
示例#19
0
 /// <summary>
 /// Constructor to initialize the parameters of SecureReadData
 /// </summary>
 /// <param name="bank">The memory bank to read</param>
 /// <param name="wordAddress">Read starting address</param>
 /// <param name="length">The length of data to read</param>
 /// <param name="type">Secure tag type</param>
 /// <param name="password">Password</param>
 public SecureReadData(Gen2.Bank bank, UInt32 wordAddress, byte length, SecureTagType type, TagAuthentication password) : base (bank,wordAddress,length)
 {
     this.type = type;
     this.password = password;
 }
示例#20
0
 public static void Main()
 {
     Gen1.Example();
     Gen2.Example();
 }
示例#21
0
        private PARAM_ThingMagicDenatranIAVOBUReadFromMemMap BuildIAVOBUReadFromMemMap(Gen2.Denatran.IAV.OBUReadFromMemMap tagOp)
        {
            PARAM_ThingMagicDenatranIAVOBUReadFromMemMap readFromMemMap = new PARAM_ThingMagicDenatranIAVOBUReadFromMemMap();

            //Set IAVCommandRequest
            readFromMemMap.ThingMagicDenatranIAVCommandRequest = BuildInitIAVCommandRequest(tagOp);

            return readFromMemMap;
        }
示例#22
0
    static void Main()
    {
        Gen2 <string> g2 = new Gen2 <string>("Hello");

        Console.WriteLine(g2.GetOb());
    }
 /// <summary>
 /// Read reserved memory of the tag
 /// </summary>
 /// <param name="bank"></param>
 /// <param name="filter"></param>
 /// <param name="data"></param>
 private void ReadData(Gen2.Bank bank, TagFilter filter, out ushort[] data)
 {
     data = null;
     int words = 1;
     TagOp op;
     while (true)
     {
         try
         {
             op = new Gen2.ReadData(bank, 2, Convert.ToByte(words));
             data = (ushort[])objReader.ExecuteTagOp(op, filter);
             words++;
         }
         catch (Exception ex)
         {
             if (ex is FAULT_GEN2_PROTOCOL_MEMORY_OVERRUN_BAD_PC_Exception || (-1 != ex.Message.IndexOf("Non-specific reader error")) || (-1 != ex.Message.IndexOf("Tag data access failed")))
             {
                 if (null != data)
                 {
                     // Just skip the exception and move on. So as not to lose the already read data.
                     break;
                 }
                 else
                 {
                     // throw the exception if the data received is null for the first iteration itself
                     throw;
                 }
             }
             else
             {
                 throw ex;
             }
         }
     }
 }
示例#24
0
        static void Main(string[] args)
        {
#if !UNITY_5_3_OR_NEWER
            var rootFolder = Directory.GetCurrentDirectory();

            string rootPath = Path.Combine(Path.Combine(rootFolder, "../../../../../"));

            if (args.Length == 2)
            {
                rootPath = args[1];
            }

            string clientPath = Path.Combine(rootPath, "src/Client.App");
            string serverPath = Path.Combine(rootPath, "src/Server.App");

            string sharedClientPath = Path.GetFullPath(Path.Combine(rootPath, "src/Client.App/Gen"));
            string sharedServerPath = Path.GetFullPath(Path.Combine(rootPath, "src/Server.App/Gen"));

            if (args.Length != 2 || args.First() == "-r")
            {
                var asmRuntime = Assembly.LoadFrom(Path.Combine(rootPath, "bin/netcoreapp3.1/Fenix.Runtime.dll"));
                Gen.AutogenHost(asmRuntime, Path.Combine(rootPath, "src/Fenix.Runtime/Common"),
                                Path.Combine(rootPath, "src/Client.App"),
                                Path.Combine(rootPath, "src/Server.App"));
            }
            else if (args.Length != 2 || args.First() == "-c")
            {
                var resolver = new DefaultAssemblyResolver();
                resolver.AddSearchDirectory(Path.Combine(rootPath, @"src/Client.App/bin/Debug/netcoreapp3.1/Client.App/netcoreapp3.1/"));
                //Assembly asmClientApp = Assembly.LoadFrom(Path.Combine(rootPath, @"src\Client.App\bin\Debug\netcoreapp3.1\Client.App\netcoreapp3.1\Client.App.dll"));
                var ad = AssemblyDefinition.ReadAssembly(
                    Path.Combine(rootPath, @"src/Client.App/bin/Debug/netcoreapp3.1/Client.App/netcoreapp3.1/Client.App.dll"),
                    new ReaderParameters()
                {
                    AssemblyResolver = resolver
                });
                //Gen.AutogenActor(asmClientApp, false, sharedClientPath, sharedServerPath, clientPath, serverPath);
                Gen2.AutogenActor(ad, false, sharedClientPath, sharedServerPath, clientPath, serverPath);
            }
            else if (args.Length != 2 || args.First() == "-s")
            {
                Assembly asmServerApp = Assembly.LoadFrom(Path.Combine(rootPath, "bin/netcoreapp3.1/Server.App.dll"));
                Gen.AutogenActor(asmServerApp, true, sharedClientPath, sharedServerPath, clientPath, serverPath);
            }

            //var p = new ProtocolCode();
            //p.Validate();
#else
            var rootFolder = Directory.GetCurrentDirectory();

            string rootPath  = Path.Combine(Path.Combine(rootFolder, "../../../../../../../"));
            string unityPath = Path.Combine(rootPath, "Unity");

            var asmClientApp = Assembly.LoadFrom(Path.Combine(unityPath, "Assets/Plugins/Fenix/Client.App.dll"));
            var asmServerApp = Assembly.LoadFrom(Path.Combine(rootPath, "bin/netcoreapp3.1/Server.App.dll"));
            var asmRuntime   = Assembly.LoadFrom(Path.Combine(rootPath, "bin/netcoreapp3.1/Fenix.Runtime.dll"));

            string sharedClientPath = Path.GetFullPath(Path.Combine(unityPath, "Assets/Scripts/Client/Gen"));
            string sharedServerPath = Path.GetFullPath(Path.Combine(rootPath, "src/Server.App/Gen"));

            string clientPath = Path.GetFullPath(Path.Combine(unityPath, "Assets/Scripts/Client"));
            string serverPath = Path.GetFullPath(Path.Combine(rootPath, "src/Server.App"));

            Gen.AutogenHost(asmRuntime, Path.GetFullPath(Path.Combine(rootPath, "src/Fenix.Runtime/Common")), clientPath, serverPath);

            Gen.AutogenActor(asmServerApp, true, sharedClientPath, sharedServerPath, clientPath, serverPath);

            Assembly.LoadFrom(Path.Combine(unityPath, "Assets/Plugins/Fenix/Fenix.Runtime.Unity.dll"));
            Assembly.LoadFrom(Path.Combine(unityPath, "Assets/Plugins/Fenix/Shared.Unity.dll"));

            Gen.AutogenActor(asmClientApp, false, sharedClientPath, sharedServerPath, clientPath, serverPath);

            //var p = new ProtocolCode();
            //p.Validate();
#endif
        }
示例#25
0
文件: Program.cs 项目: sekkit/Fenix
        static void Main(string[] args)
        {
#if !UNITY_5_3_OR_NEWER
            var rootFolder = Directory.GetCurrentDirectory();

            string rootPath = Path.Combine(Path.Combine(rootFolder, "../../../"));

            if (args.Length == 2)
            {
                rootPath = args[1];
            }

            string clientPath = Path.Combine(rootPath, "src/Client.App");
            string serverPath = Path.Combine(rootPath, "src/Server.App");

            string sharedClientPath = Path.GetFullPath(Path.Combine(rootPath, "src/Client.App/Gen"));
            string sharedServerPath = Path.GetFullPath(Path.Combine(rootPath, "src/Server.App/Gen"));

            if (args.Length != 2 || args.First() == "-r")
            {
                var asmRuntime = Assembly.LoadFrom(Path.Combine(rootPath, "bin/Server.App/net5.0/Fenix.Runtime.dll"));
                Gen.AutogenHost(asmRuntime, Path.Combine(rootPath, "src/Fenix.Runtime/Common"),
                                Path.Combine(rootPath, "src/Client.App"),
                                Path.Combine(rootPath, "src/Server.App"));
            }

            if (args.Length != 2 || args.First() == "-c")
            {
                var resolver = new DefaultAssemblyResolver();
                resolver.AddSearchDirectory(Path.Combine(rootPath, @"bin/Client.App/net5.0/"));
                //Assembly asmClientApp = Assembly.LoadFrom(Path.Combine(rootPath, @"src\Client.App\bin\Debug\net5.0\Client.App\net5.0\Client.App.dll"));
                var ad = AssemblyDefinition.ReadAssembly(
                    Path.Combine(rootPath, @"bin/Client.App/net5.0/Client.App.dll"),
                    new ReaderParameters()
                {
                    AssemblyResolver = resolver
                });
                //Gen.AutogenActor(asmClientApp, false, sharedClientPath, sharedServerPath, clientPath, serverPath);
                Gen2.AutogenActor(ad, false, sharedClientPath, sharedServerPath, clientPath, serverPath);
            }

            if (args.Length != 2 || args.First() == "-s")
            {
                Assembly asmServerApp = Assembly.LoadFrom(Path.Combine(rootPath, "bin/Server.App/net5.0/Server.App.dll"));
                Gen.AutogenActor(asmServerApp, true, sharedClientPath, sharedServerPath, clientPath, serverPath);
            }

            //var p = new ProtocolCode();
            //p.Validate();
#else
            var rootFolder = Directory.GetCurrentDirectory();

            //if (args.Length != 2)
            //   return;
            string rootPath = Path.Combine(Path.Combine(rootFolder, "../../"));
            if (args.Length >= 2)
            {
                rootPath = args[1];
            }
            string unityPath        = Path.Combine(rootPath, "Unity");
            string sharedClientPath = Path.GetFullPath(Path.Combine(unityPath, "Assets/Client.App/Gen"));
            string sharedServerPath = Path.GetFullPath(Path.Combine(rootPath, "src/Server.App/Gen"));

            string clientPath = Path.GetFullPath(Path.Combine(unityPath, "Assets/Client.App/"));
            string serverPath = Path.GetFullPath(Path.Combine(rootPath, "src/Server.App"));

            var resolver = new DefaultAssemblyResolver();
            resolver.AddSearchDirectory(Path.Combine(rootPath, @"Libs/Unity/"));
            resolver.AddSearchDirectory(Path.Combine(unityPath, @"Library/ScriptAssemblies/"));
            resolver.AddSearchDirectory(Path.Combine(rootPath, @"bin/Server.App/net5.0/"));

            AssemblyDefinition adClient = AssemblyDefinition.ReadAssembly(
                Path.Combine(unityPath, @"Library/ScriptAssemblies/Assembly-CSharp.dll"),
                new ReaderParameters {
                AssemblyResolver = resolver
            });

            if (args.Length == 0 || (args.Length >= 2 && args.First() == "-c"))
            {
                //Assembly.LoadFrom(Path.Combine(rootPath, @"Libs/Unity/Fenix.Runtime.Unity.dll"));
                //var asmClientApp = Assembly.LoadFrom(Path.Combine(rootPath, @"Libs/Unity/Assembly-CSharp.dll"));
                //Gen.AutogenActor(asmClientApp, false, sharedClientPath, sharedServerPath, clientPath, serverPath);
                Gen2.AutogenActor(adClient, false, sharedClientPath, sharedServerPath, clientPath, serverPath);
            }

            if (args.Length == 0 || (args.Length >= 2 && args.First() == "-r"))
            {
                Assembly.LoadFrom(Path.Combine(rootPath, "bin/net5.0/MessagePack.dll"));
                var asmRuntime = Assembly.LoadFrom(Path.Combine(rootPath, "bin/Server.App/net5.0/Fenix.Runtime.dll"));
                Gen.AutogenHost(asmRuntime, Path.GetFullPath(Path.Combine(rootPath, "src/Fenix.Runtime/Common")), clientPath, serverPath);
            }

            if (args.Length == 0 || (args.Length >= 2 && args.First() == "-s"))
            {
                AssemblyDefinition adServerApp = AssemblyDefinition.ReadAssembly(
                    Path.Combine(rootPath, @"bin/Server.App/net5.0/Server.App.dll"),
                    new ReaderParameters {
                    AssemblyResolver = resolver
                });

                //Gen2.AutogenActor(adServerApp, true, sharedClientPath, sharedServerPath, clientPath, serverPath);

                var asmServerApp = Assembly.LoadFrom(Path.Combine(rootPath, "bin/Server.App/net5.0/Server.App.dll"));
                Gen.AutogenActor(asmServerApp, true, sharedClientPath, sharedServerPath, clientPath, serverPath);
            }

            //var p = new ProtocolCode();
            //p.Validate();
#endif
        }
示例#26
0
文件: Program.cs 项目: returnres/exam
        static void Main(string[] args)
        {
            testa te = new testa();

            te.faccio(3);

            #region opertori
            PippoTest pippoTest  = new PippoTest(1);
            PippoTest pippoTest1 = new PippoTest(2);
            PippoTest pippoTest2 = new PippoTest(2);
            //implicit
            int testt = pippoTest2;
            //explicit
            PippoTest testtt = (PippoTest)3;

            //somma tra pippotest
            var rrrr = pippoTest1 + pippoTest;
            var ssss = pippoTest2++;

            //somma tra int e pippotest
            var ressss = 3 + testtt;
            #endregion

            #region TraceSource

            /*
             * LISTNER
             *
             * ConsoleTraceListener	Standard output or error stream
             * DelimitedListTraceListener	TextWriter
             * EventLogTraceListener	EventLog
             * EventSchemaTraceListener	XML-encoded, schema-compliant log file
             * TextWriterTraceListener	TextWriter
             * XmlWriterTraceListener	XML-encoded data to a TextWriter or stream.
             */
            //configuro da codice
            Stream outfile = File.Create("log.txt");
            //creo listner
            TextWriterTraceListener textWriterTraceListener = new TextWriterTraceListener(outfile);
            TraceSource             traceSource             = new TraceSource("myT", SourceLevels.All);

            //cancello quello di default
            traceSource.Listeners.Clear();
            //aggiungo mio
            traceSource.Listeners.Add(textWriterTraceListener);

            traceSource.TraceInformation("");
            traceSource.TraceEvent(TraceEventType.Critical, 0, "");
            traceSource.TraceData(TraceEventType.Information, 1, "");
            traceSource.Flush();
            traceSource.Close();

            //TraceSource configuro da appsetting
            mySource.TraceEvent(TraceEventType.Error, 1,
                                "Error message.");
            mySource.TraceEvent(TraceEventType.Warning, 2,
                                "Warning message.");

            #endregion

            #region BooleanSwitch
            var sw = new System.Diagnostics.BooleanSwitch("QueryLogger", "QueryLogger");
            if (sw.Enabled)
            {
                Console.WriteLine("Booleanswitchenabled");
            }
            #endregion

            #region TraceSwitch

            /*
             * SourceSwitch e TraceSwitch sono altri due tipi di switch che servono a controllare
             * la verbosità del trace e la “sorgente” del trace.
             * Ovvero, se usi il tracing in maniera seria puoi, grazie al SourceSwitch,
             * definire varie sorgenti di tracing e regolarle a tua discrezione con il TraceSwitch.
             */
            ////Define this in the web config
            TraceSwitch generalSwitch = new TraceSwitch("General",
                                                        "Entire Application");

            string msgText = "1";

            // Write INFO type message, if switch is set to Verbose, type 4
            Trace.WriteIf(generalSwitch.TraceVerbose, msgText);

            msgText = "A2MC";

            // Write INFO type message, if switch is set to Verbose or Warning 4 0r 2
            Trace.WriteIf(generalSwitch.TraceWarning, msgText);

            // Write ERROR type message, if switch is set to Verbose, Warning, info or Error
            // 0 (off), 1 (error), 2 (warning), 3 (info), OR 4 (verbose)
            //If General switch in WEB CONFIG = 0 then it will not get into the if below
            if (generalSwitch.TraceError)
            {
                //Trace type, inthis case error will define how it will appear in the event log
                Trace.TraceError("Error");
                //Use your imagination to switch it on and off properly.
                //You can really imagine and apply.
            }
            #endregion

            #region EventLog
            if (!EventLog.SourceExists("Mysource"))
            {
                EventLog.CreateEventSource("MySource", "MyLog");
            }

            EventLog eventLog = new EventLog();
            eventLog.Source = "MySource";
            eventLog.WriteEntry("Ciao J0n");
            #endregion

            #region PerformanceCounter

            /* CounterCreationDataCollection
             * CounterCreationData (PerformanceCounterType)
             * PerformanceCounterCategory (si prende il collection che si prende il data) (PerformanceCounterCategoryType)
             * PerformanceCounter
             */

            var performanceCounterCategories = PerformanceCounterCategory.GetCategories();
            var first = performanceCounterCategories.FirstOrDefault(category => category.CategoryName == "Processor");

            var performanceCounters = first.GetCounters("_Total");

            Console.WriteLine("Displaying performance counters for Processor category:--\n");

            foreach (PerformanceCounter performanceCounter in performanceCounters)
            {
                Console.WriteLine(performanceCounter.CounterName);
            }

            //v2custom
            String customCategoryName = "Custom Performance Counter Category";
            string counterNameCustom  = "pippo";
            if (!PerformanceCounterCategory.Exists(customCategoryName))
            {
                CounterCreationDataCollection counterCreationDataCollection = new CounterCreationDataCollection();
                counterCreationDataCollection.Add(new CounterCreationData(counterNameCustom, "Sample Counter 1", PerformanceCounterType.ElapsedTime));
                //counterCreationDataCollection.Add(new CounterCreationData("Counter 2", "Sample Counter 2", PerformanceCounterType.SampleCounter));
                PerformanceCounterCategory.Create(customCategoryName, "This is just an example", PerformanceCounterCategoryType.SingleInstance, counterCreationDataCollection);
                var counter = new PerformanceCounter(customCategoryName, counterNameCustom, false);
                counter.Increment();
            }
            using (var counter = new PerformanceCounter(customCategoryName, counterNameCustom, false))
            {
                counter.Increment();
            }

            //v2custom
            string counterName  = "countername";
            string categoryName = "categoryname";
            if (!PerformanceCounterCategory.Exists("categoryname"))
            {
                CounterCreationDataCollection datacollection = new CounterCreationDataCollection();

                CounterCreationData numberOfItems = new CounterCreationData();
                numberOfItems.CounterType = PerformanceCounterType.NumberOfItems32;
                numberOfItems.CounterName = counterName;
                datacollection.Add(numberOfItems);

                // Create the category.
                PerformanceCounterCategory.Create(categoryName,
                                                  "Demonstrates usage of the AverageTimer32 performance counter type",
                                                  PerformanceCounterCategoryType.SingleInstance, datacollection);

                var counter = new PerformanceCounter(categoryName, counterName, false);

                counter.RawValue = 0;
                counter.Increment();
            }
            using (var counter = new PerformanceCounter(categoryName, counterName, false))
            {
                counter.Increment();
            }
            #endregion

            #region  OOP
            MyMethodCond();

            string main = "Main";
            Trace.Write("trace");
            Debug.Write("debug");
            Debug.Assert(main == "Main");

            Ciccio c = new Ciccio();
            c.Prova();
            ICiccio s = (ICiccio)c;
            s.Prova();
            ICiccio1 s1 = (ICiccio1)c;
            s1.Prova();
            c.Nano();

            double xxx = 0.0;
            double yyy = 0.0;
            //var reszzzz = xxx / yyy;NAN
            IIbabbo babbo11 = new Figliolo();
            babbo11.MioMetodo();

            Mio("ciao");
            Mio("ciao", paperino: 1);
            Mio("ciao", pluto: true, paperino: 1);
            //Mio("ciao",pluto:false,1);ERRORE
            //Pippo pippos = new Pippo();
            //pippos.DoSOmething();

            #endregion

            #region  GENERZIONE DINAMICA CODICE

            /*
             *
             * //System.Reflection.Emit
             * //creazione , lancio e salvataggoi IL a runtime
             * AssemblyName nameAss = new AssemblyName("DynamicAss");
             * AssemblyBuilder assemblyBuilder =
             *  AppDomain.CurrentDomain.DefineDynamicAssembly(nameAss, AssemblyBuilderAccess.RunAndSave);
             * ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("DynamicMod", "DynamicAss.dll");
             * //classe
             * TypeBuilder tb = moduleBuilder.DefineType("HelloClass", TypeAttributes.Class | TypeAttributes.Public);
             * //metodo
             * MethodBuilder mb =
             *  tb.DefineMethod("PrintHello", MethodAttributes.Public, null, new Type[] { typeof(string) });
             * ILGenerator myGenerator = mb.GetILGenerator();
             * myGenerator.Emit(OpCodes.Ldstr, "Hello");
             * myGenerator.Emit(OpCodes.Ldarg_1);
             * MethodInfo concatMetod = typeof(String).GetMethod("Concat", new Type[] { typeof(string), typeof(string) });
             * myGenerator.Emit(OpCodes.Call, concatMetod);
             * MethodInfo wrMethodInfo = typeof(Console).GetMethod("Write", new Type[] { typeof(string) });
             * myGenerator.Emit(OpCodes.Call, wrMethodInfo);
             * myGenerator.Emit(OpCodes.Ret);
             *
             * //istanzio ogetto
             * Type helloType = tb.CreateType();
             * object helloobj = Activator.CreateInstance(helloType);
             * MethodInfo hellMethodInfo = helloType.GetMethod("PrintHello", new[] { typeof(string) });
             *
             * //invoco metodo passando parametro
             * hellMethodInfo.Invoke(helloobj, new object[] { "J0n" });
             *
             * //salvo dll
             * assemblyBuilder.Save("DynamicAss.dll");
             #endregion
             *
             * HelloClass  helloClass = new HelloClass();
             * helloClass.PrintHello("ciao");
             */


            //System.CodeDom
            //creare  salvare e compilare  codice sorgente e runtime
            CodeCompileUnit codeCompileUnit = new CodeCompileUnit();
            CodeNamespace   codeNamespace   = new CodeNamespace("CodeDOM");
            codeNamespace.Imports.Add(new CodeNamespaceImport("System"));
            //classe
            CodeTypeDeclaration myclass = new CodeTypeDeclaration("Pippo");

            //metodo
            CodeMemberMethod codeMemberMethod = new CodeMemberMethod();
            codeMemberMethod.Name       = "DoSOmething";
            codeMemberMethod.Attributes = MemberAttributes.Public;
            CodeMethodInvokeExpression codeMethodInvokeExpression = new CodeMethodInvokeExpression(
                new CodeTypeReferenceExpression("Console"), "WriteLine", new CodePrimitiveExpression("Ciao Ciccio"));
            CodeMethodInvokeExpression codeMethodInvokeExpression1 = new CodeMethodInvokeExpression(
                new CodeTypeReferenceExpression("Console"), "ReadLine");
            codeCompileUnit.Namespaces.Add(codeNamespace);
            codeNamespace.Types.Add(myclass);
            myclass.Members.Add(codeMemberMethod);
            codeMemberMethod.Statements.Add(codeMethodInvokeExpression);
            codeMemberMethod.Statements.Add(codeMethodInvokeExpression1);

            //salva codice sorgente
            CSharpCodeProvider provider = new CSharpCodeProvider();

            string pathSource = @"../../bin/Debug/Pippo.cs";
            string pathOut    = @"../../bin/Debug/Pippos.dll";

            //string pathSource = @"../../autogenerated/Pippo.cs";
            //string pathOut = @"../../autogenerated/Pippos.exe";
            using (StreamWriter stream = new StreamWriter(pathSource, false))
            {
                IndentedTextWriter tw = new IndentedTextWriter(stream, "   ");
                provider.GenerateCodeFromCompileUnit(codeCompileUnit, tw, new CodeGeneratorOptions());
                tw.Close();
            }

            CompileCSharpCode(pathSource, pathOut);

            #endregion

            #region reflection
            //REFLECTION System.Assembly
            //assembly (IL codice compilato) exe/dll
            //carico in memoria assembly

            //PLUGIN
            //caricamento dinamico  assembly da path
            Assembly assm = Assembly.LoadFrom(@"C:\Users\rob\source\repos\Exam\Plugin1\bin\Debug\Plugin1.dll");
            Type[]   tips = assm.GetTypes();
            foreach (var item in tips)
            {
                //var objectType = Type.GetType(objectToInstantiate);
                Type objectType         = assm.GetType(item.FullName);
                var  instantiatedObject = Activator.CreateInstance(objectType);
            }
            //carica solo metadati dei tipi SENZA instanziare i tipi
            Assembly ass2 = Assembly.ReflectionOnlyLoadFrom("ClassLibrary1.dll");

            //var instantiatedObject1 = Activator.CreateInstance(typeof(Tipo));
            //var instantiatedObject2 = Activator.CreateInstance<Tipo>;
            string sss = new String(new char[3]);
            //assembly attualmente in esecuzione
            Assembly ass             = Assembly.GetExecutingAssembly();
            Assembly ass1            = Assembly.GetAssembly(typeof(string));
            Assembly ass12           = Assembly.GetAssembly(sss.GetType());
            var      mytype          = ass.GetType("ConsoleApp1.Program");
            var      fullname        = ass.FullName;
            var      nome            = mytype.Name;
            var      mytypeNamespace = mytype.Namespace;

            var typeinfo = typeof(MiaclasseProva).GetTypeInfo();
            var name     = typeinfo.FullName;

            //ottengo tipo classe
            MiaclasseProva miaclasseProva = new MiaclasseProva();

            var typeinfo1 = miaclasseProva.GetType().GetTypeInfo();

            //ottengo interafccia
            var interfaccie = typeinfo1.GetInterfaces();

            //ottengo metodi e parametri
            MethodInfo[] metodi = typeinfo1.GetMethods(BindingFlags.Instance);
            foreach (var metodo in metodi)
            {
                var pi = metodo.GetParameters();
                foreach (var parinfo in pi)
                {
                    Console.WriteLine($" parametro : {parinfo.ParameterType.Name}");
                }
            }

            //ottengo membri
            MemberInfo[] membri = typeinfo1.GetMembers(BindingFlags.Public | BindingFlags.NonPublic);
            foreach (var mambro in membri)
            {
                var mi = mambro.MemberType;
            }
            #endregion

            #region IComparable
            //confrontare oggetti
            ComparableMoto comparableMoto = new ComparableMoto();
            comparableMoto.Targa = "pippo";
            ComparableMoto comparableMoto1 = new ComparableMoto();
            comparableMoto1.Targa = "pluto";

            int ord = comparableMoto.CompareTo(comparableMoto1);

            List <ComparableMoto> comparableMotos = new List <ComparableMoto>();
            comparableMotos.Add(new ComparableMoto()
            {
                Targa = "A"
            });
            comparableMotos.Add(new ComparableMoto()
            {
                Targa = "B"
            });
            comparableMotos.Add(new ComparableMoto()
            {
                Targa = "C"
            });
            comparableMotos.Sort();

            //AppDomain.CurrentDomain.UnhandledException += OnUnhandleException;
            //ManageException manage = new ManageException();
            //manage.GeneroEccezioneNonGestita();
            #endregion

            #region ref out static class
            Figlio   figlio1  = new Figlio();
            Figlio   figlio   = new Figlio("as");
            Macchina macchina = new Macchina("320", "bmw");
            macchina.Parti();
            SmartPhone.Battery     battery = new SmartPhone.Battery();
            ConstructorStaticClass constructorStaticClass = new ConstructorStaticClass();
            ConstructorStaticClass miaclasse2             = new ConstructorStaticClass();
            Console.WriteLine(ConstructorStaticClass.contatore);
            ClassTest1 babbo   = new ClassTest1();
            var        testref = 0;
            double     resp2;
            double     resp3;

            //ref
            babbo.cambiaNumero(ref testref);
            //out scarta valore resp3
            babbo.potenza(2, out resp2, out _);
            var media = babbo.CalcolaMedia(18, 27, 27, 27);
            babbo.ParametriNome(nome: "rob", anni: 43);

            //c#7
            //double xresp2;
            //double xresp3;
            //babbo.potenza1(2,  xresp2,  xresp3);

            int x1 = 0;
            //block
            if (x1 == 0)//expression
            {
                //codice
            }

            int?    nullable = null;
            var     cliente  = new { nome = "rob" };
            Mesi    giorno   = Mesi.febbraio;
            int     mese     = (int)Mesi.febbraio;
            Mesi    mese1    = (Mesi)1;
            Pippolo pippo;
            pippo.a = 1;


            #endregion

            #region cast box unbox
            //cast
            int     i     = 123;
            object  box   = i;
            int     n     = (int)box;//unbox
            dynamic dd    = 1;
            int     inc   = dd + 1;
            var     ssss1 = Convert.ToString(1);
            dynamic dy    = new ExpandoObject();
            #endregion

            #region type

            //OTTENGO IL TIPO
            //GetType
            var  ti = typeof(string).GetTypeInfo();
            Type ts = Type.GetType("System.String");//se si trova in Mscorelib.dll

            TestClass tc   = new TestClass();
            Type      tipo = tc.GetType();

            //typeof
            Type type = typeof(Type);

            //CONTROLLO IL TIPO
            //is tipo | as tipo
            string obj = "";
            if (obj is string)
            {
                //cast ()
                string a  = (string)obj;   //se obj non è compatibile con string cast exception
                string a1 = obj as string; //se obj non compatobole con string ritorna null
            }


            #endregion

            #region array
            Console.WriteLine($"metodo {nameof(Main)}");

            /*
             * stack => vet
             * heap 1
             * heap 2
             * heap 3
             *
             * ARRAY MULTID:
             * -array rettangoli
             * 1234
             * 1234
             *
             * -array jagged (irregolare)
             * 123456
             * 234
             * 2343434343
             */

            //array
            int[] vet = new[] { 1, 2, 3 };

            //array regolari matrici
            int[,] matrix = new int[3, 4];
            matrix[0, 0]  = 1;

            int[,] matrix1 =
            {
                { 1, 2, 3, 4 },
                { 5, 6, 7, 8 }
            };

            //jagged array irregolari
            int[][] jagged = new int[3][];
            jagged[0] = new int[2] {
                1, 2
            };
            jagged[1] = new int[4] {
                1, 2, 3, 4
            };
            #endregion

            #region c7 PATTERN MATCHING

            /*
             * type => espr is tipo v
             * const => espr is constante
             * var
             *
             * */

            //type
            object obj1 = "";
            if (obj1 is string str)
            {
                Console.WriteLine(str);
            }

            //invece che

            if (obj1 is string)
            {
                string str1 = (string)obj;
                Console.WriteLine(str1);
            }

            //const
            Mesi giornomese = Mesi.febbraio;
            bool feb        = giornomese is Mesi.febbraio;//true se giorno di febbraio

            #endregion

            #region  Event
            //Event
            Pub pub = new Pub();
            //mi iscrivo e gli dico di fare questo quando viene sollevato evento evento
            pub.OnChange += () => Console.WriteLine("lambda");
            pub.OnChange += delegate { Console.WriteLine("delegate"); };

            //sollevo evento
            pub.Raise();

            Pub1 p1 = new Pub1();
            p1.OnChange += () => Console.WriteLine("lambda");
            p1.Raise();

            Pub2 p2 = new Pub2();
            p2.CreateAndRaise();

            Car        car = new Car();
            CarMonitor cm  = new CarMonitor(car);

            car.Decelerate();

            #endregion

            #region Expression Tree
            //Expression Tree
            Expression <Func <int, bool> > exp1 = x => x % 2 == 0;
            Func <int, bool> isPari             = exp1.Compile();//dopo che l'ho compliat posso eseguirla, prima era solo un albero di espressopmo
            if (isPari(4))
            {
                Console.WriteLine("pari");
            }
            #endregion

            #region delegate

            //assegno lambda (anonyous method)
            myDelegate myd = (x) => 1;
            Console.WriteLine(myd("0ciao"));

            //assegno metodo
            myDelegate myd1 = MethodForDel;
            Console.WriteLine(myd1("1ciao"));

            //assegno delegate
            myDelegate myd2 = delegate { return(1); };
            Console.WriteLine(myd2("2ciao"));
            #endregion

            #region VARIANZA
            //COVARIANZA OUT
            //ti faccio assegnare sia metodo che ritorna stringa
            //ma anche metodo che torna object perchè stringa deriva
            //da object (è piu specifica)
            Del          d1   = new Del();
            Cov <string> cov  = d1.Cov1;
            Cov <object> cov1 = d1.Cov2;
            Cov <object> cov3 = d1.Cov2;
            //Cov<string> cov2 = d1.Cov2;//no object non deriva da stringa

            //CONTROVARIANZA IN
            //ti faccio assegnare sia metodo che prende ingresso
            //classe piu generica object  ma ache classe piu specifica string
            Con <object> con  = d1.Con1;
            Con <string> con3 = d1.Con1;
            Con <string> con1 = d1.Con2;
            //Con<object> con2 = d1.Con2;//no

            var res3 = d1.MyCon(Convert.ToInt32, "5");
            var res4 = d1.MyCon1(Convert.ToInt32, "5");
            var res5 = d1.MyConGen(Convert.ToInt32, "5");
            var res6 = d1.MyConGen(Convert.ToBoolean, 0);
            var res7 = d1.MyConGen(Convert.ToString, 5);
            Console.WriteLine(res3);
            Console.WriteLine(res4);

            d1.UseMulticast();

            #endregion

            #region generics
            Task tx1 = Task.Run(() =>
            {
                Console.WriteLine("ciao");
            });
            Task[] tasksarr = new Task[1];
            tasksarr[0] = tx1;

            Gen1 gen1 = new Gen1();

            if (gen1.GetDefault <ConstructorStaticClass, Task>(tx1) != null)
            {
                gen1.ContinueTaskOrDefault(tx1, Console.WriteLine);
                Console.WriteLine("start task generic");
            }

            var mytaskList = gen1.ContinueTasksOrDefault(tasksarr, Console.WriteLine);


            if (mytaskList != null)
            {
                Console.WriteLine("starts tasks generic");
            }


            Gen2 <Constructor>             gen2       = new Gen2 <Constructor>();
            Gen2Figlia <Constructor>       gen2figlia = new Gen2Figlia <Constructor>();
            Gen1Figlia <Constructor, Task> tesFiglia  = new Gen1Figlia <Constructor, Task>();

            //variabile statico è diverso per tipo
            TestStaticGen <string> .Status = "rob";
            TestStaticGen <int> .Status    = 1;
            Console.WriteLine(TestStaticGen <string> .Status);
            Console.WriteLine(TestStaticGen <int> .Status);

            TestStatic.Status = "ciao";
            TestStatic.Status = "ciau";
            Console.WriteLine(TestStatic.Status);
            //

            Generica <string, int, DateTime, bool> gen = new Generica <string, int, DateTime, bool>();


            List <Lista <string> > genericiInnestati = new List <Lista <string> >();
            genericiInnestati.Add(new Lista <string>(5));
            genericiInnestati[0][0] = "ciao";
            genericiInnestati[0][1] = "come ";
            genericiInnestati[0][2] = "stai";
            genericiInnestati[0][3] = "rob";
            genericiInnestati[0][4] = "?";

            foreach (var item in genericiInnestati)
            {
                for (int j = 0; j < 5; j++)
                {
                    Console.WriteLine(item[j]);
                }
            }

            Lista <string> lista = new Lista <string>(5);
            lista[0] = "";
            #endregion

            #region programmazione parallela
            //PLINQ solo linq to onject NO linq to sql
            //prende base dati la divide in segmenti e fa query in parallelo su questi segmentie  pio unisce iriaultati
            // se i lavori nonn sono complessi e la base dati è minima la programmazione parallela non da buoni risultati
            var qy = from num in Enumerable.Range(1, 8).AsParallel()
                     select Math.Pow(2, num);

            //stampa da 1 a 9 (9 numeri NON in ordine)
            //iterazioni indipendenti l'una dall altra quindi per tutti e due ordine non è sequnziale
            Parallel.For(1, 10, g => Console.WriteLine("g-{0}", g));
            var result = Parallel.For(0, 50, (g, parallelLoopState) =>
            {
                if (g > 5)
                {
                    parallelLoopState.Break();
                }
            });

            if (!result.IsCompleted)
            {
                var o = result.LowestBreakIteration;
            }

            //non è sequnziale
            List <string> list = new List <string>()
            {
                "ciao", "come", "va?"
            };
            Parallel.ForEach(list, word => Console.WriteLine("{0}", word, word.Length));
            #endregion

            #region async await

            var res1 = DoCurlAsync();

            //net 4.5
            //await salva lo stato del contesto del caller e quando il metodo await si conclude
            //il contesto ritorna allo stato del chimante che puo eseguire il codice successivo
            //questo nel caso di ui permette di modiicare la ui che  proprieta nella app gui del thread
            //della ui e viene eseguito nel ui syncronization context (dispatchercontext nella ui)
            //DAL C#7 TUTTO PUO ESSERE AWAITABLE ED ESEGUITO AINCRONO E NON  SOLO ISTANZA DI TASK
            //QUALSIAIS OGGETTO CHE ESPONE METODO GETAWAITER INFATTI LA CLASSE TASK ESPONE METODO GETAWAITER
            //await non puo essere usato su unsafe, lock, main
            MetodoAsyn();
            Console.WriteLine("codice prima fine await)");

            Task <string> res = GetAsync();

            List <string> files = new List <string>()
            {
                "pippo.txt", "pippo1.txt"
            };
            files.ForEach(async file => await ReadFileAsync(file));

            //all block
            //.Wait()
            //.Result
            //.GetAwaiter()
            //.GetResult()

            #endregion

            #region task tpl

            //manca continuewhenall
            //continuewheany
            //task figli innestati

            //Task.WaitAll blocks the current thread until everything has completed.
            //Task.WhenAll returns a task which represents the action of waiting until everything has completed.
            //That means that from an async method, you can use:
            // A DIFFERENZA DI WAIT ALL TORNA SOLO LA PRIMA ECCEZIONE NON AGGREGATE
            Task[] tasksArray = new Task[3];
            tasksArray[0] = Task.Run(() => { Thread.Sleep(4000); });
            tasksArray[1] = Task.Run(() => { Thread.Sleep(4000); });
            tasksArray[2] = Task.Run(() => { Thread.Sleep(4000); });
            var ry = MyAsyncWhenAll(tasksArray);
            Console.WriteLine("tornato da MyAsyncWhenAll");


            Task tx = Task.Run(() =>
            {
                Thread.Sleep(1000);
            });
            Task ty = Task.Run(() =>
            {
                Thread.Sleep(1000);
            });

            Task taskall = Task.WhenAll((new Task[] { tx, ty }));

            //Task taskall = Task.WhenAny((new Task[] { t1, t2 }));
            taskall.Wait();

            Task <String> webtask = Task.Run(() =>
            {
                string url   = "http://www.google.it";
                WebClient wc = new WebClient();
                return(wc.DownloadString(url));
            });

            Task <String> headhtml = webtask.ContinueWith <string>(x =>
            {
                var res2 = x.Result;
                //fai qualcosa con res
                return(res2);
            });

            var tokenSource         = new CancellationTokenSource();
            CancellationToken token = tokenSource.Token;

            Task cancellabletask = null;
            try
            {
                cancellabletask = Task.Run(() =>
                {
                    token.ThrowIfCancellationRequested();
                    for (int d = 0; d < 2; d++)
                    {
                        Thread.Sleep(100);
                        if (token.IsCancellationRequested)
                        {
                            //eseguo altre cose
                            token.ThrowIfCancellationRequested();
                        }
                    }
                }, token);

                tokenSource.CancelAfter(1000);
                cancellabletask.Wait();
            }
            catch (AggregateException aggregateException)
            {
                if (aggregateException.InnerException is OperationCanceledException)
                {
                    Console.WriteLine("OperationCanceledException£");
                }
                if (cancellabletask != null && (cancellabletask.IsCanceled && cancellabletask.Status == TaskStatus.Canceled))
                {
                    Console.WriteLine(aggregateException.ToString());
                }
            }


            Task <String> task = Task.Run(() =>
            {
                string url   = "http://www.google.it";
                WebClient wc = new WebClient();
                return(wc.DownloadString(url));
            });
            var htmlUrl = task.Result;//blocco

            List <Task> tasks = new List <Task>();
            for (int r = 0; r < 5; r++)
            {
                int number = r;
                tasks.Add(
                    Task.Run(() =>
                {
                    Console.WriteLine(number);
                    Thread.Sleep(1000);
                }));
            }

            //Task.WaitAll(tasks.ToArray());
            Task.WaitAny(tasks.ToArray());
            Console.WriteLine("all task complete");

            Task longtask = Task.Run(() =>
            {
                Thread.Sleep(1000);
            });
            longtask.Wait(1000);


            Task verylong = Task.Factory.StartNew(() =>
            {
                Thread.Sleep(2000);
            }, TaskCreationOptions.LongRunning);
            #endregion tpl

            #region thread
            for (int w = 0; w < 5; w++)
            {
                ThreadPool.QueueUserWorkItem(LongOperation);
            }


            Thread threada = new Thread(IncrMon);
            Thread threadb = new Thread(IncrMon);
            threada.Start();
            threadb.Start();
            threada.Join();
            threadb.Join();
            Console.WriteLine("n={0}", n2);

            Thread thread1 = new Thread(Incr);
            Thread thread2 = new Thread(Incr);
            thread1.Start();
            thread2.Start();
            thread1.Join();
            thread2.Join();
            Console.WriteLine("n={0}", n1);

            Thread t = new Thread(() =>
            {
                Console.WriteLine(Thread.CurrentThread.Name);
                Thread.Sleep(1000);
            });

            Thread t1 = new Thread(() =>
            {
                Console.WriteLine(Thread.CurrentThread.Name);
                for (int z = 0; z < 10; z++)
                {
                    lock (lockobj)
                    {
                        n = n + 1;
                        Thread.Sleep(1);
                        Console.WriteLine("n={0}", n);
                    }
                }
            });
            Thread t2 = new Thread(() =>
            {
                Console.WriteLine(Thread.CurrentThread.Name);
                for (int x = 0; x < 10; x++)
                {
                    lock (lockobj)
                    {
                        n = n + 1;
                        Thread.Sleep(1);
                        Console.WriteLine("n={0}", n);
                    }
                }
            });

            t.IsBackground = true;                       //termina appena finisce la app
            t.Priority     = ThreadPriority.AboveNormal; //determinata quantita di cpu destinata al thread ma non è deterministico
            t.Start();
            t1.Start();
            t2.Start();
            t.Join();//il codice si blocca e attende che t finisce

            #endregion

            Console.ReadLine();
        }
 private Gen2.IDS.SL900A.SensorReading performSensorReading(Gen2.IDS.SL900A.GetSensorValue tagop) 
 {
     //Execute the tagop
     Gen2.IDS.SL900A.SensorReading sensorReading = (Gen2.IDS.SL900A.SensorReading)reader.ExecuteTagOp(tagop, null);
     //Return the sensor reading
     return sensorReading;
 }
 private double getCelsiusTemp(Gen2.IDS.SL900A.SensorReading sensorReading) 
 { 
     //Get the code value
     ushort value = sensorReading.Value;
     //Convert the code to a Temp (Using default config function)
     double temp = ((double)value)*0.18-89.3;
     //Return the temp as a double
     return temp;
 }
示例#29
0
 /// <summary>
 /// Create Gen2.LockAction out of enum-wrapped mask and action bitmasks
 /// </summary>
 /// <param name="mask">Lock bits to act on</param>
 /// <param name="action">Lock bit values</param>
 private LockAction(Gen2.LockBits mask, Gen2.LockBits action)
     : this((UInt16)mask, (UInt16)action) { }
示例#30
0
        private PARAM_ThingMagicDenatranIAVOBUAuthenticateID BuildIAVOBUAuthenticateID(Gen2.Denatran.IAV.OBUAuthID tagOp)
        {
            PARAM_ThingMagicDenatranIAVOBUAuthenticateID authenticateID = new PARAM_ThingMagicDenatranIAVOBUAuthenticateID();

            //Set IAVCommandRequest
            authenticateID.ThingMagicDenatranIAVCommandRequest = BuildInitIAVCommandRequest(tagOp);

            return authenticateID;
        }
示例#31
0
 public Gen2LockArgs(TagFilter target, Gen2.LockAction action)
 {
     Target = target;
     Action = action;
 }
示例#32
0
        private PARAM_ThingMagicDenatranIAVOBUWriteToMemMap BuildIAVOBUWriteToMemMap(Gen2.Denatran.IAV.OBUWriteToMemMap tagOp)
        {
            PARAM_ThingMagicDenatranIAVOBUWriteToMemMap writeToMemMap = new PARAM_ThingMagicDenatranIAVOBUWriteToMemMap();

            //Set IAVCommandRequest
            writeToMemMap.ThingMagicDenatranIAVCommandRequest = BuildInitIAVCommandRequest(tagOp);

            return writeToMemMap;
        }
示例#33
0
    public static void Main()
    {
        Gen2 <string> g2 = new Gen2 <string>("Hello");

        Console.WriteLine(g2.getob());
    }
示例#34
0
        public void CreateDifferentPartial()
        {
            var _ = AbstractCallable._;

            Helper.RunWithMultipleSimulators((s) =>
            {
                {
                    var gen     = new GenericCallable(s, typeof(Gen1 <,>));
                    var partial = gen.Partial(_);
                    Assert.Equal(typeof(GenericPartial), partial.GetType());
                }

                {
                    var closed  = new Gen1 <long, bool>(s);
                    var partial = closed.Partial <ICallable>(_);
                    Assert.Equal(typeof(OperationPartial <(long, bool), (long, bool), bool>), partial.GetType());
                }

                {
                    var closed  = new Gen1 <(long, long), bool>(s);
                    var partial = closed.Partial <ICallable>(((3L, _), true));
                    Assert.Equal(typeof(OperationPartial <long, ((long, long), bool), bool>), partial.GetType());
                }

                {
                    var x       = s.Get <IUnitary <Qubit>, Intrinsic.X>();
                    var closed  = new Gen1 <(long, (IUnitary, Qubit, Result)), bool>(s);
                    var partial = closed.Partial <ICallable>(((_, (x, _, _)), true));
                    Assert.Equal(typeof(OperationPartial <(long, (Qubit, Result)), ((long, (IUnitary, Qubit, Result)), bool), bool>), partial.GetType());
                }

                {
                    var x       = s.Get <IUnitary <Qubit>, Intrinsic.X>();
                    var closed  = new Gen1 <(long, (IUnitary, Qubit, Result)), bool>(s) as ICallable <((long, (IUnitary, Qubit, Result)), bool), bool>;
                    var partial = closed.Partial(((_, (x, _, _)), false));
                    Assert.Equal(typeof(OperationPartial <(long, (Qubit, Result)), ((long, (IUnitary, Qubit, Result)), bool), bool>), partial.GetType());
                }

                {
                    var closed  = new Gen2 <(long, bool, Result), IUnitary>(s);
                    var partial = closed.Partial <IAdjointable>(((_, true, _), 3L, _));
                    Assert.Equal(typeof(OperationPartial <((long, Result), IUnitary), ((long, bool, Result), long, IUnitary), QVoid>), partial.GetType());
                }

                {
                    var closed  = new Gen2 <bool, Result>(s) as IAdjointable <(bool, long, Result)>;
                    var partial = closed.Partial((_, 3L, Result.Zero));
                    Assert.Equal(typeof(OperationPartial <bool, (bool, long, Result), QVoid>), partial.GetType());
                }

                {
                    var closed  = new Gen4 <bool, bool>(s) as IUnitary <(Result, (bool, bool), Result)>;
                    var partial = closed.Controlled.Partial((_, (_, (true, _), Result.Zero)));
                    Assert.Equal(typeof(OperationPartial <(IQArray <Qubit>, (Result, bool)), (IQArray <Qubit>, (Result, (bool, bool), Result)), QVoid>), partial.GetType());
                }

                {
                    var closed  = new Gen4 <bool, bool>(s) as IControllable <(Result, (bool, bool), Result)>;
                    var partial = closed.Controlled.Partial((_, (_, (true, _), Result.Zero)));
                    Assert.Equal(typeof(OperationPartial <(IQArray <Qubit>, (Result, bool)), (IQArray <Qubit>, (Result, (bool, bool), Result)), QVoid>), partial.GetType());
                }

                {
                    var closed  = new Gen2 <bool, Result>(s) as IAdjointable;
                    var partial = closed.Partial((_, 3L, Result.Zero));
                    Assert.Equal(typeof(OperationPartial <bool, (bool, long, Result), QVoid>), partial.GetType());
                }

                {
                    var closed  = new Gen4 <bool, bool>(s) as IUnitary;
                    var partial = closed.Adjoint.Controlled.Partial((_, (_, (true, _), Result.Zero)));
                    Assert.Equal(typeof(OperationPartial <(IQArray <Qubit>, (Result, bool)), (IQArray <Qubit>, (Result, (bool, bool), Result)), QVoid>), partial.GetType());
                }

                {
                    var closed  = new Gen4 <bool, bool>(s) as IControllable;
                    var partial = closed.Controlled.Partial((_, (_, (true, _), Result.Zero)));
                    Assert.Equal(typeof(OperationPartial <(IQArray <Qubit>, (Result, bool)), (IQArray <Qubit>, (Result, (bool, bool), Result)), QVoid>), partial.GetType());
                }
            });
        }
示例#35
0
 private PARAM_ThingMagicDenatranIAVCommandRequest BuildInitIAVCommandRequest(Gen2.Denatran.IAV tagOp)
 {
     PARAM_ThingMagicDenatranIAVCommandRequest commandRequest = new PARAM_ThingMagicDenatranIAVCommandRequest();
     commandRequest.PayLoad = tagOp.Payload;
     commandRequest.OpSpecID = ++OpSpecID;
     return commandRequest;
 }
示例#36
0
        private PARAM_ThingMagicDenatranIAVOBUAuthenticateFullPass2 BuildIAVOBUAuthenticateFullPass2(Gen2.Denatran.IAV.OBUAuthFullPass2 tagOp)
        {
            PARAM_ThingMagicDenatranIAVOBUAuthenticateFullPass2 authenticateFullPass2 = new PARAM_ThingMagicDenatranIAVOBUAuthenticateFullPass2();

            //Set IAVCommandRequest
            authenticateFullPass2.ThingMagicDenatranIAVCommandRequest = BuildInitIAVCommandRequest(tagOp);

            return authenticateFullPass2;
        }
示例#37
0
        private PARAM_ThingMagicDenatranIAVAuthenticateOBU BuildIAVAuthenticateOBU(Gen2.Denatran.IAV.AuthenticateOBU tagOp)
        {
            PARAM_ThingMagicDenatranIAVAuthenticateOBU authenticateOBU = new PARAM_ThingMagicDenatranIAVAuthenticateOBU();

            //Set IAVCommandRequest
            authenticateOBU.ThingMagicDenatranIAVCommandRequest = BuildInitIAVCommandRequest(tagOp);

            return authenticateOBU;
        }
示例#38
0
 /// <summary>
 /// Constructor to initialize the parameters of ReadData
 /// </summary>
 /// <param name="bank">The memory bank to read</param>
 /// <param name="wordAddress">Read starting address</param>
 /// <param name="length">The length of data to read</param>
 public ReadData(Gen2.Bank bank, UInt32 wordAddress, byte length)
 {
     this.Bank = bank;
     this.WordAddress = wordAddress;
     this.Len = length;
 }
示例#39
0
        /// <summary>
        /// Read tag memory for readers or modules other the M5e variants
        /// </summary>
        /// <param name="bank">Gen2 memory bank</param>
        /// <param name="filter">filter</param>
        /// <param name="MemData">Data read from tag memory</param>
        private void ReadMemoryM6eVariants(Gen2.Bank bank, TagFilter filter, ref ushort[] MemData)
        {
            try
            {
                // Read tag memory with zero as start address and lenght of words to read as zero
                TagOp op = new Gen2.ReadData(bank, 0, 0);
                MemData = (ushort[])objectReader.ExecuteTagOp(op, filter);

                if (MemData.Length < 64)
                {
                    // If data read is less then 64 words, then perform read word by word to make sure 
                    // all the data is read from the tag memory
                    ReadTagMemoryWordByWord(bank, filter, ref MemData);
                }
                else
                {
                    // If data read is more then 64 words then perform read with start address as 64 words
                    // and length as zero
                    ReadLargeTagMemory(bank, filter, ref MemData);
                }
            }
            catch (Exception ex)
            {
                if ((ex is FAULT_PROTOCOL_BIT_DECODING_FAILED_Exception) || ((ex is FAULT_NO_TAGS_FOUND_Exception)))
                {
                    // Perform read when the tag has mem more then 128 bytes and doesn't support 
                    // Zero start address and number of words to read as zero
                    ReadLargeTagMemoryWithoutZeroLengthSupport(bank, filter, ref MemData);
                }
                else
                {
                    throw;
                }
            }
        }
示例#40
0
 /// <summary>
 /// Constructor to initialize the parameters of BlockWrite
 /// </summary>
 /// <param name="bank">Gen2 memory bank to write to</param>
 /// <param name="wordPtr">the word address to start writing to</param>
 /// <param name="data">the data to write</param>
 public BlockWrite(Gen2.Bank bank, uint wordPtr, ushort[] data)
 {
     this.Bank = bank;
     this.WordPtr=wordPtr;
     this.Data = data;
 }
示例#41
0
        /// <summary>
        /// Read specified tag memory bank 
        /// </summary>
        /// <param name="bank">Gen2 bank</param>
        /// <param name="filter">filter</param>
        /// <param name="MemData">Data read from the tag memory</param>
        public void ReadTagMemoryData(Gen2.Bank bank, TagFilter filter, ref ushort[] MemData)
        {

            if (modelReader.Equals("M5e") || modelReader.Equals("M5e EU") || modelReader.Equals("M5e Compact") || modelReader.Equals("Astra"))
            {
                // Read tag memory word by word for M5e variants
                ReadTagMemoryWordByWord(bank, filter, ref MemData);
            }
            else
            {
                // Read tag memory for m6e variants
                ReadMemoryM6eVariants(bank, filter, ref MemData);
            }
        }
示例#42
0
 /// <summary>
 /// Erase tag specific block
 /// </summary>
 /// <param name="bank">the tag memory bank to erase</param>
 /// <param name="wordPtr">the word address to start erase to</param>
 /// <param name="wordCount">no of words to erase</param>
 public BlockErase(Gen2.Bank bank, UInt32 wordPtr, byte wordCount)
 {
     this.Bank = bank;
     this.WordPtr = wordPtr;
     this.WordCount = wordCount;                
 }
示例#43
0
 /// <summary>
 /// Read tag memory when tag has more then 64 words or 128 bytes. And module doesn't supports zero address and zero length.
 /// Reads the tag memory with 0 address and length of words as 64. If memory overrun received. Initiates reading of tag 
 /// word by word with start address as length of alread read data and length of words to read as 0. Returns the data read from 
 /// tag memory.
 /// </summary>
 /// <param name="bank">Gen2 mem bank</param>
 /// <param name="filter">filter</param>
 /// <param name="data">Data read from tag memory</param>
 private void ReadLargeTagMemoryWithoutZeroLengthSupport(Gen2.Bank bank, TagFilter filter, ref ushort[] data)
 {
     lock (new Object())
     {
         data = null;
         // Data from tag memory
         List<ushort> dataTemp = new List<ushort>();
         // Number of words to read
         int words = 64;
         // Start address
         uint startaddress = 0;
         TagOp op;
         bool isAllDatareceived = true;
         // Read till all the data from the tag memory is read
         while (isAllDatareceived)
         {
             try
             {
                 op = new Gen2.ReadData(bank, startaddress, Convert.ToByte(words));
                 dataTemp.AddRange(((ushort[])objectReader.ExecuteTagOp(op, filter)));
                 // Increment the start address to 64 and keep length of wrods to read as 64 for
                 // all the iterations
                 startaddress += 64;
             }
             catch (Exception ex)
             {
                 try
                 {
                     if (ex is FAULT_GEN2_PROTOCOL_MEMORY_OVERRUN_BAD_PC_Exception || (-1 != ex.Message.IndexOf("Non-specific reader error")) || (-1 != ex.Message.IndexOf("General Tag Error")) || (-1 != ex.Message.IndexOf("Tag data access failed")))
                     {
                         // If the memory to read requested is more then the available memory in the tag, then initiate 
                         // reading the tag memory word by word with start address as length of already read data if exists 
                         // and lenght of words to read is 1
                         ushort[] wordData = null;
                         if (dataTemp.Count > 0)
                         {
                             // If some data is already read then include this data also so that 
                             // reading of memory doesn't continue from zero and the list sholud 
                             // not contain same data twice
                             wordData = dataTemp.ToArray();
                         }
                         ReadTagMemoryWordByWord(bank, filter, ref wordData);
                         dataTemp.AddRange(wordData);
                         // Come out of main while loop. And read the already read data
                         isAllDatareceived = false;
                     }
                     else
                     {
                         throw;
                     }
                 }
                 catch (Exception exception)
                 {
                     // If more then once the below exceptions are recieved then come out of the loop.
                     if (exception is FAULT_GEN2_PROTOCOL_MEMORY_OVERRUN_BAD_PC_Exception || (-1 != exception.Message.IndexOf("Non-specific reader error")) || (-1 != exception.Message.IndexOf("General Tag Error")) || (-1 != exception.Message.IndexOf("Tag data access failed")))
                     {
                         if (dataTemp.Count > 0)
                         {
                             // Just skip the exception and move on. So as not to lose the already read data.
                             isAllDatareceived = false;
                         }
                         else
                         {
                             // throw the exception if the data received is null for the first iteration itself
                             throw;
                         }
                     }
                     else
                     {
                         throw;
                     }
                 }
             }
         }
         data = dataTemp.ToArray();
     }
 }
示例#44
0
 /// <summary>
 /// Constructor to initialize the parameters of NxpEasAlarm
 /// </summary>
 /// <param name="dr">Gen2 divide ratio to use</param>
 /// <param name="m">Gen2 M parameter to use</param>
 /// <param name="trExt">Gen2 TrExt value to use</param>
 public EasAlarm(Gen2.DivideRatio dr, Gen2.TagEncoding m, Gen2.TrExt trExt): base(dr,m,trExt)
 {
     ChipType = 0x07;
 }
        private void ReadReservedMemData(Gen2.Bank bank, TagFilter filter)
        {            
            ushort [] reservedData;
            TagOp op;
            try
            {
                try
                {
                    // Read kill password
                    op = new Gen2.ReadData(Gen2.Bank.RESERVED, 0, 2);
                   reservedData = (ushort[])objReader.ExecuteTagOp(op, filter);
                   if (null != reservedData)
                   {
                       txtKillPassword.Text = ByteFormat.ToHex(ByteConv.ConvertFromUshortArray(reservedData), "", " ");
                   }
                   else
                   {
                       txtKillPassword.Text = "";
                   }
                }
                catch (Exception ex)
                {
                    if (ex is FAULT_GEN2_PROTOCOL_MEMORY_OVERRUN_BAD_PC_Exception)
                    {
                        txtKillPassword.Text = "Read Error";                        
                    }
                    else
                    {
                        txtKillPassword.Text = ex.Message;
                    }
                }

                try
                {
                    // Read access password
                    reservedData = null;
                    op = new Gen2.ReadData(Gen2.Bank.RESERVED, 2, 2);
                    reservedData = (ushort[])objReader.ExecuteTagOp(op, filter);
                    if (null != reservedData)
                    {
                        txtAcessPassword.Text = ByteFormat.ToHex(ByteConv.ConvertFromUshortArray(reservedData), "", " ");
                    }
                    else
                    {
                        txtAcessPassword.Text = "";
                    }
                }
                catch (Exception ex)
                {
                    if (ex is FAULT_GEN2_PROTOCOL_MEMORY_OVERRUN_BAD_PC_Exception)
                    {
                        txtAcessPassword.Text = "Read Error";
                    }
                    else
                    {                     
                        txtAcessPassword.Text = ex.Message;
                    }
                }

                // Read additional memory password
                try
                {
                    reservedData = null;
                    if (model.Equals("M5e") || model.Equals("M5e EU") || model.Equals("M5e Compact") || model.Equals("Astra"))
                    {                        
                        ReadAdditionalReservedMemDataM5eVariants(Gen2.Bank.RESERVED, 4, filter, out reservedData);
                    }
                    else
                    {
                        op = new Gen2.ReadData(Gen2.Bank.RESERVED, 4, 0);
                        reservedData = (ushort[])objReader.ExecuteTagOp(op, filter);
                    }

                    if (null != reservedData)
                    {
                        txtReservedMemUnusedValue.Text = ByteFormat.ToHex(ByteConv.ConvertFromUshortArray(reservedData), "", " ");
                        // Visible additional memory textboxes
                        lblAdditionalReservedMem.Visibility = System.Windows.Visibility.Visible;
                        txtReservedMemUnusedValue.Visibility = System.Windows.Visibility.Visible;
                        lblAdditionalReservedMemAdd.Visibility = System.Windows.Visibility.Visible;
                    }
                    else
                    {
                        txtReservedMemUnusedValue.Text = "";
                    }
                }
                catch
                { 
                    // catch the exception and move on. Only some tags has aditional memory 
                    txtReservedMemUnusedValue.Text = "";
                    // Hide additional memory textboxes
                    lblAdditionalReservedMem.Visibility = System.Windows.Visibility.Collapsed;
                    txtReservedMemUnusedValue.Visibility = System.Windows.Visibility.Collapsed;
                    lblAdditionalReservedMemAdd.Visibility = System.Windows.Visibility.Collapsed;
                }
            }
            catch (Exception)
            {
                throw;
            }            
        }
示例#46
0
 /// <summary>
 /// Constructor to initialize the parameters of WriteData
 /// </summary>
 /// <param name="bank">The memory bank to write</param>
 /// <param name="wordAddress">Write starting address</param>
 /// <param name="data">The data to write</param>
 public WriteData(Gen2.Bank bank, UInt32 wordAddress, ushort[] data)
 {
     this.Bank = bank;
     this.WordAddress = wordAddress;
     this.Data = data;
 }
 /// <summary>
 /// Read additional reserved memory for m5e variants
 /// </summary>
 /// <param name="bank"></param>
 /// <param name="startAddress"></param>
 /// <param name="filter"></param>
 /// <param name="data"></param>
 private void ReadAdditionalReservedMemDataM5eVariants(Gen2.Bank bank, uint startAddress, TagFilter filter, out ushort[] data)
 {
     data = null;
     int words = 1;
     TagOp op;
     while (true)
     {
         try
         {
             op = new Gen2.ReadData(bank, startAddress, Convert.ToByte(words));
             data = (ushort[])objReader.ExecuteTagOp(op, filter);
             words++;
         }
         catch (Exception)
         {
             throw;
         }
     }
 }
示例#48
0
 /// <summary>
 /// Read tag memory which has more then 64 words or 128 bytes. Returns the data read from tag memory. 
 /// Stops reading the tag memory if FAULT_PROTOCOL_BIT_DECODING_FAILED_Exception exception is received
 /// more then once. If the data read from tag memory is less then 64 words then initiates reading tag
 /// memory word by word
 /// </summary>
 /// <param name="bank"> Gen2 mem bank</param>
 /// <param name="filter">filter</param>
 /// <param name="data">Mem data obtained from the tag</param>
 private void ReadLargeTagMemory(Gen2.Bank bank, TagFilter filter, ref ushort[] data)
 {
     lock (new Object())
     {
         List<ushort> dataTemp = new List<ushort>();
         if (data != null)
         {
             dataTemp.AddRange(data);
         }
         int words = 0;
         uint startaddress = 64;
         TagOp op;
         bool isAllDatareceived = true;
         while (isAllDatareceived)
         {
             try
             {
                 op = new Gen2.ReadData(bank, startaddress, Convert.ToByte(words));
                 ushort[] tempDataReceived = (ushort[])objectReader.ExecuteTagOp(op, filter);
                 dataTemp.AddRange(tempDataReceived);
                 startaddress += 64;
                 if (tempDataReceived.Length < 64)
                 {
                     isAllDatareceived = false;
                     // If data received is less then 64 words, perform word by word with start address as length
                     // of the data and numer of words to read is 1 
                     ReadTagMemoryWordByWord(bank, filter, ref data);
                 }
             }
             catch (Exception ex)
             {
                 if (ex is FAULT_PROTOCOL_BIT_DECODING_FAILED_Exception)
                 {
                     try
                     {
                         // If read is success then continue the while loop with incremented start address and length as 0 
                         words = 64;
                         op = new Gen2.ReadData(bank, startaddress, Convert.ToByte(words));
                         dataTemp.AddRange(((ushort[])objectReader.ExecuteTagOp(op, filter)));
                         startaddress += 64;
                         words = 0;
                     }
                     catch (Exception et)
                     {
                         // If consecutively we get FAULT_PROTOCOL_BIT_DECODING_FAILED_Exception exception blindly come out of the loop to avoid
                         // dead lock
                         if (et is FAULT_PROTOCOL_BIT_DECODING_FAILED_Exception)
                         {
                             isAllDatareceived = false;
                         }
                         else
                         {
                             throw;
                         }
                     }
                 }
                 else
                 {
                     throw;
                 }
             }
         }
         data = dataTemp.ToArray();
     }
 }
 private double getVoltage(Gen2.IDS.SL900A.SensorReading sensorReading)
 {
     //Get the code value
     ushort value = sensorReading.Value;
     //Convert the code to a Voltage (V) (Using default config function)
     double voltage = ((double)value) * .310 / 1024 + .310;
     //Return the voltage as a double
     return voltage;
 }
示例#50
0
 /// <summary>
 /// Read tag memory word by word. If FAULT_GEN2_PROTOCOL_MEMORY_OVERRUN_BAD_PC_Exception 
 /// or Non-specific reader error or General Tag Error or Tag data access failed exception
 /// is recieved. Memory reading is stopped and the already read data is returned
 /// </summary>
 /// <param name="bank">Gen2 memory bank</param>
 /// <param name="filter">Select filter</param>
 /// <param name="data">Read tag memory data is returned</param>
 private void ReadTagMemoryWordByWord(Gen2.Bank bank, TagFilter filter, ref ushort[] data)
 {
     lock (new Object())
     {
         List<ushort> dataTemp = new List<ushort>();
         uint startaddress = 0;
         if (data != null)
         {
             // if the data varibale already contains the data, then add that data 
             // to data temp and chnage the start address to total data length
             dataTemp.AddRange(data);
             startaddress = (uint)data.Length;
         }
         int words = 1;
         TagOp op;
         bool isAllDatareceived = true;
         while (isAllDatareceived)
         {
             try
             {
                 // Read tag memory word by word
                 op = new Gen2.ReadData(bank, startaddress, Convert.ToByte(words));
                 dataTemp.AddRange(((ushort[])objectReader.ExecuteTagOp(op, filter)));
                 startaddress += 1;
             }
             catch (Exception exception)
             {
                 if (exception is FAULT_GEN2_PROTOCOL_MEMORY_OVERRUN_BAD_PC_Exception || (-1 != exception.Message.IndexOf("Non-specific reader error")) || (-1 != exception.Message.IndexOf("General Tag Error")) || (-1 != exception.Message.IndexOf("Tag data access failed")))
                 {
                     if (dataTemp.Count > 0)
                     {
                         // Just skip the exception and move on. So as not to lose the already read data.
                         isAllDatareceived = false;
                     }
                     else
                     {
                         // throw the exception if the data received is null for the first iteration itself
                         throw;
                     }
                 }
                 else
                 {
                     throw;
                 }
             }
         }
         data = dataTemp.ToArray();
     }
 }
示例#51
0
        private PARAM_ThingMagicDenatranIAVActivateSiniavMode BuildIAVActivateSiniavMode(Gen2.Denatran.IAV.ActivateSiniavMode tagOp)
        {
            PARAM_ThingMagicDenatranIAVActivateSiniavMode activateSiniavMode = new PARAM_ThingMagicDenatranIAVActivateSiniavMode();

            //Set IAVCommandRequest
            activateSiniavMode.ThingMagicDenatranIAVCommandRequest = BuildInitIAVCommandRequest(tagOp);

            return activateSiniavMode;
        }