コード例 #1
0
ファイル: ReassemblingTestBase.cs プロジェクト: nesfit/NTPAC
        protected IEnumerable <Frame> GetFramesFromPcapAndDefragment(String pcapFileName)
        {
            var ipv4DefragmentationEngine =
                new Ipv4DefragmentationEngine(this._services.GetService <ILoggerFactory>().CreateLogger <Ipv4DefragmentationEngine>());
            var frames = new List <Frame>();

            foreach (var(packet, timestampTicks) in this.GetPacketsFromPcap(pcapFileName))
            {
                Frame frame;
                if (!(packet.PayloadPacket is IPPacket ipPacket))
                {
                    continue;
                }

                if (ipPacket is IPv4Packet ipv4Packet && Ipv4Helpers.Ipv4PacketIsFragmented(ipv4Packet))
                {
                    var(isDefragmentationSuccessful, defragmentedIpv4Packet, fragments) =
                        ipv4DefragmentationEngine.TryDefragmentFragments(FrameFactory.CreateFromIpPacket(ipv4Packet, timestampTicks));
                    if (!isDefragmentationSuccessful)
                    {
                        continue;
                    }

                    frame = FrameFactory.CreateFromDefragmentedIpPacket(defragmentedIpv4Packet, fragments);
                }
コード例 #2
0
        static void RunInteractiveGame()
        {
            IFrameFactory frameFactory = new FrameFactory();
            IGame         newGame      = new Game(frameFactory);

            while (true)
            {
                int remainingPins = newGame.GetRemainingPinsInFrame();
                int frameNumber   = newGame.Frames.Count;
                Console.WriteLine($"(Frame {frameNumber}) Enter the number of pins knocked down (remaining pins in frame = {remainingPins}):");
                string userInput = Console.ReadLine();
                if (int.TryParse(userInput, out int pinsScored))
                {
                    if (pinsScored >= 0 && pinsScored <= remainingPins)
                    {
                        newGame.AddScore(pinsScored);
                    }
                    else
                    {
                        Console.WriteLine($"Your score must be between 0 and the number of remaning pins in the frame ({remainingPins}).");
                    }
                }
                else
                {
                    Console.WriteLine("Input may only be integers.");
                }
                if (newGame.IsFinished == true)
                {
                    break;
                }
            }
            Console.WriteLine($"Final game score: {newGame.GetTotalScore()}");
        }
コード例 #3
0
ファイル: FrameTests.cs プロジェクト: danielburnley/KanKan
        public void ExecuteMethodCorrectlyExecutesFrameRequest(string testMessage, string testActionDataPayload)
        {
            //Arrange
            KarassDependenciesSpy dependenciesSpy = new KarassDependenciesSpy();
            FrameStructDummy      frameActionData = new FrameStructDummy
            {
                Test = testActionDataPayload
            };

            FrameRequest frameRequest = new FrameRequest(frameActionData);
            KarassFrameSpy <FrameStructDummy> frameAction = new KarassFrameSpy <FrameStructDummy>(dependenciesSpy);

            dependenciesSpy.Register <IKarassFrame <FrameStructDummy> >(() => frameAction);
            FrameFactory frameFactory = new FrameFactory(dependenciesSpy);

            frameFactory.RegisterRoute <FrameStructDummy, IKarassFrame <FrameStructDummy> >();

            //Act
            frameFactory.Execute(frameRequest, testMessage);

            //Assert
            Assert.True(dependenciesSpy.RegisterCallCount == 1);
            Assert.True(dependenciesSpy.GetCallCount == 1);
            Assert.True(frameAction.ExecuteCallCount == 1);
            Assert.True(frameAction.RequestData.Test == testActionDataPayload);
            Assert.True(frameAction.Message == testMessage);
            Assert.True(frameAction.Dependencies == dependenciesSpy);
        }
コード例 #4
0
        public async Task <bool> ProcessData(SocketConnection conn)
        {
            try
            {
                if (conn.CurrentFrame == null)
                {
                    conn.CurrentFrame = FrameFactory.Create(conn.Buffer);

                    if (conn.CurrentFrame == null)
                    {
                        return(true);
                    }
                }

                Frame f = conn.CurrentFrame;
                if (!f.Exam(conn.Buffer))
                {
                    return(true);
                }

                f.Parse(conn.Buffer);
                await f.Process(conn);

                conn.CurrentFrame = null;

                return(true);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return(false);
            }
        }
コード例 #5
0
ファイル: ReassemblingTestBase.cs プロジェクト: lulzzz/NTPAC
        protected IEnumerable <Frame> GetFramesFromPcapAndDefragment(Uri pcapUri)
        {
            var ipv4DefragmentationEngine =
                new Ipv4DefragmentationEngine(this._services.GetService <ILoggerFactory>().CreateLogger <Ipv4DefragmentationEngine>());
            var frames     = new List <Frame>();
            var pcapLoader = this._services.GetService <IPcapLoader>();

            using (pcapLoader)
            {
                RawCapture rawCapture;
                pcapLoader.Open(pcapUri);
                while ((rawCapture = pcapLoader.GetNextPacket()) != null)
                {
                    Frame frame;
                    var   parsedPacket = Packet.ParsePacket(pcapLoader.LinkType, rawCapture.Data);
                    if (!(parsedPacket.PayloadPacket is IPPacket ipPacket))
                    {
                        continue;
                        ;
                    }

                    if (ipPacket is IPv4Packet ipv4Packet && Ipv4Helpers.Ipv4PacketIsFragmented(ipv4Packet))
                    {
                        var(isDefragmentationSuccessful, firstTimeStamp, defragmentedIpv4Packet) =
                            ipv4DefragmentationEngine.TryDefragmentFragments(
                                FrameFactory.CreateFromIpPacket(ipv4Packet, rawCapture.Timeval.Date.Ticks));
                        if (!isDefragmentationSuccessful)
                        {
                            continue;
                        }

                        frame = FrameFactory.CreateFromIpPacket(defragmentedIpv4Packet, firstTimeStamp);
                    }
コード例 #6
0
        public void CreateIf_True_NotNullFrame()
        {
            var result = FrameFactory.CreateIf(true, 0);

            Assert.IsNotNull(result);
            Assert.AreEqual(0, result.Rank);
        }
コード例 #7
0
ファイル: LayerConverter.cs プロジェクト: michaliskambi/holo
        public void Convert(ModelLayerInfo layerInfo)
        {
            var frameFactory = new FrameFactory();
            var frameExporter = new FrameExporter();

            string outputLayerDir = outputRootDir + @"\" + Path.GetFileName(layerInfo.Directory);
            Directory.CreateDirectory(outputLayerDir);

            string[] inputPaths = GetFilepaths(layerInfo.Directory);
            CheckIfVTKFormat(inputPaths[0]);
            foreach (string inputPath in inputPaths)
            {
                string filename = Path.GetFileNameWithoutExtension(inputPath);

                IFrame frame = frameFactory.Import(inputPath, layerInfo.DataType);
                if (scalingFactor == -1)
                {
                    scalingFactor = GetScalingFactor(frame);
                }
                frame.NormalizeVectors(scalingFactor);
                frameExporter.ExportFrameToTxt(frame, filename, outputLayerDir);
                
                Log.Info(filename + " converted sucessfully.");
            }
        }
コード例 #8
0
        public void CurrentFramesReturnsNextFrames()
        {
            KarassFactory     karassFactory     = new KarassFactory();
            IDependencies     dependencies      = new KarassDependencies();
            FrameFactory      frameFactory      = new FrameFactory(dependencies);
            MockFramesFactory mockFramesFactory = new MockFramesFactory(frameFactory);

            IKarass karass = karassFactory.Get(new List <Action>(), new List <Action>(), new List <FrameRequest[]>()
            {
                new FrameRequest[]
                {
                    mockFramesFactory.GetValidFrameRequest((_) => true),
                    mockFramesFactory.GetValidFrameRequest((_) => true),
                    mockFramesFactory.GetValidFrameRequest((_) => true),
                    mockFramesFactory.GetValidFrameRequest((_) => true),
                    mockFramesFactory.GetValidFrameRequest((_) => true),
                    mockFramesFactory.GetValidFrameRequest((_) => true),
                    mockFramesFactory.GetValidFrameRequest((_) => true),
                    mockFramesFactory.GetValidFrameRequest((_) => true),
                    mockFramesFactory.GetValidFrameRequest((_) => true),
                    mockFramesFactory.GetValidFrameRequest((_) => true),
                }
            });

            Assert.True(karass.FramesCollection[0].Length == 10);

            KanKan kanKan = new KanKan(karass, frameFactory);

            for (int i = 0; i < 10; i++)
            {
                Assert.AreEqual(kanKan.Current, kanKan.CurrentState.NextFrames);
                kanKan.MoveNext();
            }
        }
コード例 #9
0
 public static void Init(RollbarConfig config = null)
 {
     Data.SetPlatform("Android");
     Data.SetFramework("CLR " + Environment.Version);
     FrameFactory.Init(FrameBuilder);
     RollbarDotNet.Rollbar.Current = new RollbarImplementation(config);
 }
コード例 #10
0
        public void ParseHeaderByteForFirstConsFrames()
        {
            //     1110 0000 >> 0000 0111 &
            // 0   000? ???? => 0 => SINGLE
            // 1   001? ???? => 1 => FIRST
            // 2   010? ???? => 2 => CONS
            // 3   011? ???? => 3 => CONTROL
            // 4   100? ???? => 4 => INFO

            // IsSubframeCount ==>          ???? ???1
            // SubFrameCountOrIndex ==>     ???? ?11? ==> Used in Single Frame
            // HasMessageTypeByte_b4 ==>    ???1 ????
            // Frame Type ==>               111? ????

            // ConsFrame:
            // IsSubFrameCount ==>          1??? ????
            // SubFrameCountOrIndex ==>     ?11? ????
            // HasMessageTypeByte_b4 ==>    ???? 1???
            // FrameCountOrNuber ==> byte[1]

            //Arrange
            var  frameFactory = new FrameFactory();
            byte headerByte   = 0x30;
            var  frameType    = frameFactory.getFrameTypeFromHeaderByte(headerByte);

            Assert.AreEqual(FrameType.FIRST, frameType);
        }
コード例 #11
0
ファイル: Program.cs プロジェクト: weinre/nettunnel
        public async Task <bool> ProcessData(SocketConnection conn)
        {
            connection = conn;

            if (connection.CurrentFrame == null)
            {
                connection.CurrentFrame = FrameFactory.Create(connection.Buffer);

                if (connection.CurrentFrame == null)
                {
                    return(true);
                }
            }

            Frame f = connection.CurrentFrame;

            if (!f.Exam(connection.Buffer))
            {
                return(true);
            }

            f.Parse(connection.Buffer);
            await f.Process(connection);

            connection.CurrentFrame = null;

            return(true);
        }
コード例 #12
0
        /// <summary>
        /// Process an incoming message within the conversation.
        /// </summary>
        /// <remarks>
        /// This method:
        /// 1. instantiates and composes the required components
        /// 2. deserializes the dialog state (the dialog stack and each dialog's state) from the <see cref="toBot"/> <see cref="Message"/>
        /// 3. resumes the conversation processes where the dialog suspended to wait for a <see cref="Message"/>
        /// 4. queues <see cref="Message"/>s to be sent to the user
        /// 5. serializes the updated dialog state in the messages to be sent to the user.
        ///
        /// The <see cref="MakeRoot"/> factory method is invoked for new conversations only,
        /// because existing conversations have the dialog stack and state serialized in the <see cref="Message"/> data.
        /// </remarks>
        /// <param name="toBot">The message sent to the bot.</param>
        /// <param name="MakeRoot">The factory method to make the root dialog.</param>
        /// <param name="token">The cancellation token.</param>
        /// <param name="singletons">An optional list of object instances that should not be serialized.</param>
        /// <returns>A task that represents the message to send inline back to the user.</returns>
        public static async Task <Message> SendAsync(Message toBot, Func <IDialog> MakeRoot, CancellationToken token = default(CancellationToken), params object[] singletons)
        {
            IWaitFactory     waits   = new WaitFactory();
            IFrameFactory    frames  = new FrameFactory(waits);
            IBotData         botData = new JObjectBotData(toBot);
            IConnectorClient client  = new ConnectorClient();
            var botToUser            = new ReactiveBotToUser(toBot, client);
            var provider             = new Serialization.SimpleServiceLocator(singletons)
            {
                waits, frames, botData, botToUser
            };
            var formatter = Conversation.MakeBinaryFormatter(provider);

            IDialogContextStore contextStore = new DialogContextStore(formatter);
            IDialogContextStore store        = new ErrorResilientDialogContextStore(contextStore);

            IDialogContext context;

            if (!store.TryLoad(botData.PerUserInConversationData, BlobKey, out context))
            {
                IFiberLoop fiber = new Fiber(frames);
                context = new Internals.DialogContext(botToUser, botData, fiber);
                var root = MakeRoot();
                var loop = root.Loop();
                context.Call <object>(loop, null);
                await fiber.PollAsync();
            }

            IUserToBot userToBot = (IUserToBot)context;
            await userToBot.SendAsync(toBot, token);

            store.Save(context, botData.PerUserInConversationData, BlobKey);

            return(botToUser.ToUser);
        }
コード例 #13
0
        public void ParseConsFrames()
        {
            //Arrange
            List <byte[]> frameData = new List <byte[]>
            {
                Utils.StringToByteArray("300605000057febf00010082523134362e323178"), // First 1/6
                Utils.StringToByteArray("52012e78782e7848423138303645553135333437"), // Cons 2/6
                Utils.StringToByteArray("54023100000000000030342e30362e3230313841"), // Cons 3/6
                Utils.StringToByteArray("5603717561436c65616e204d65726120436f6d66"), // Cons 4/6
                Utils.StringToByteArray("40046f7274000000000000000000000000000000"), // Cons 5/6
                Utils.StringToByteArray("4205000000000000000000000000000000000000"), // Cons 6/6
            };

            var frameFactory   = new FrameFactory();
            var frameCollector = new FrameCollector();

            foreach (var data in frameData)
            {
                //Act
                var frame = frameFactory.CreateFrameFromBytes(data);
                //frameCollector.AddFrame(frame.SubFrameCountOrIndex)
                //Assert
                Assert.IsTrue(frame is FirstConsFrame);
            }
        }
コード例 #14
0
ファイル: FrameTests.cs プロジェクト: danielburnley/KanKan
        public void GetMethodReturnsCorrectData(string testString, string message)
        {
            // Arrange
            KarassDependenciesSpy dependenciesSpy = new KarassDependenciesSpy();
            FrameStructDummy      frameActionData = new FrameStructDummy
            {
                Test = testString
            };
            KarassFrameSpy <FrameStructDummy> frameAction = new KarassFrameSpy <FrameStructDummy>(dependenciesSpy);

            dependenciesSpy.Register <IKarassFrame <FrameStructDummy> >(() => frameAction);
            FrameFactory frameFactory = new FrameFactory(dependenciesSpy);

            frameFactory.RegisterRoute <FrameStructDummy, IKarassFrame <FrameStructDummy> >();

            //Act
            IKarassFrame <FrameStructDummy> frame = frameFactory.Get <FrameStructDummy>();

            frame.Execute(message, frameActionData);


            //Assert
            Assert.True(dependenciesSpy.GetCallCount == 1);
            Assert.True(dependenciesSpy.RegisterCallCount == 1);
            Assert.True(frameAction.ExecuteCallCount == 1);
            Assert.True(frame.Message == message);
            Assert.True(frame.RequestData.Test == testString);
            Assert.AreEqual(frameAction.Dependencies, dependenciesSpy);
        }
コード例 #15
0
ファイル: FrameTests.cs プロジェクト: danielburnley/KanKan
        public void HasRegisterMethodWhichTakesStructIKarassFrame()
        {
            IDependencies dependencies = new DependenciesDummy();
            FrameFactory  frameFactory = new FrameFactory(dependencies);

            frameFactory.RegisterRoute <FrameStructDummy, IKarassFrame <FrameStructDummy> >();
        }
コード例 #16
0
        public static void AddFrame(this EditID3File file, string id, string text)
        {
            TextFrame frame = FrameFactory.GetFrame(id) as TextFrame;

            frame.Text = text;

            file.V2Tag.Add(frame);
        }
コード例 #17
0
        public int Receive(byte[] frame)
        {
            var serialNumber = "SN-100-200";
            var data         = ConvertUtils.ConvertTextToByteArrayInHexadecimal(serialNumber);

            FrameFactory.Create(frame, MetersOperationsConstants.RESPONSE_SERIAL_NUMBER, data);
            return(data.Length + 4);
        }
コード例 #18
0
        internal AquaCleanBaseClient(IBluetoothLeConnector bluetoothLeConnector)
        {
            this.bluetoothLeConnector = bluetoothLeConnector;
            frameService   = new FrameService();
            frameFactory   = new FrameFactory();
            messageService = new MessageService();

            // Build lookup
            var type  = typeof(IApiCall);
            var types = AppDomain.CurrentDomain.GetAssemblies()
                        .SelectMany(s => s.GetTypes())
                        .Where(p => type.IsAssignableFrom(p));

            contextLookup = types
                            .Select(t => new
            {
                Type = t,
                Api  = (ApiCallAttribute)t.GetCustomAttributes(typeof(ApiCallAttribute), false).FirstOrDefault()
            }
                                    )
                            .Where(t => t.Api != null)
                            .ToDictionary(t => t.Api, t => t.Type);

            // Process received data from Bluetooth
            bluetoothLeConnector.DataReceived += (sender, data) =>
            {
                frameService.ProcessData(data);
            };

            // Connection status has changed
            bluetoothLeConnector.ConnectionStatusChanged += (sender, args) => {
                this.ConnectionStatusChanged?.Invoke(this, new ConnectionStatusChangedEventArgs(args));
            };

            // Send Frame over Bluetooth
            frameService.SendData += async(sender, data) =>
            {
                await bluetoothLeConnector.SendMessageAsync(data);
            };

            // Process complete transaction
            frameService.TransactionComplete += (sender, data) =>
            {
                this.messageContext = messageService.ParseMessage(data);
                var context = new ApiCallAttribute()
                {
                    Context   = messageContext.Context,
                    Procedure = messageContext.Procedure
                };
                if (contextLookup.ContainsKey(context))
                {
                    var cc = contextLookup[context];
                    Debug.WriteLine("Result for " + cc.Name);
                }

                eventWaitHandle.Set();
            };
        }
コード例 #19
0
        public void Arrange()
        {
            _frameFactory = new FrameFactory();
            bowl1         = new Bowl(7);
            bowl2         = new Bowl(3);

            //10th Frame Bowl
            strike = new Bowl(10);
        }
コード例 #20
0
        protected IMaybeMultipleValues <RawPacket> ParsePacket(RawCapture rawCapture)
        {
            if (rawCapture == null)
            {
                return(new ProcessRawPacketRequestError("Missing packet payload"));
            }


//      return new RawPacket(rawCapture) {EntityId = 0};



            Packet parsedPacket;

            try
            {
                parsedPacket = Packet.ParsePacket(rawCapture.LinkLayerType, rawCapture.Data);
            }
            catch (ArgumentOutOfRangeException ex)
            {
                return(new ProcessRawPacketRequestError($"Parsing error {ex}"));
            }

            // Ignore non-IP traffic (STP, ... )
            if (!(parsedPacket?.PayloadPacket is IPPacket ipPacket))
            {
                return(new ProcessRawPacketRequestError("Non-IP packet"));
            }

            // Attempt to defragment
            if (ipPacket is IPv4Packet ipv4Packet && Ipv4Helpers.Ipv4PacketIsFragmented(ipv4Packet))
            {
                var(isDefragmentationSuccessful, firstTimestamp, defragmentedIpv4Packet) =
                    this.IPIpv4DefragmentationEngine.TryDefragmentFragments(
                        FrameFactory.CreateFromIpPacket(ipv4Packet, rawCapture.Timeval.Date.Ticks));
                if (!isDefragmentationSuccessful)
                {
                    return(ProcessRawPacketFragmentsRequest.EmptyInstance);
                }

                var defragmentedL3L4Key = new L3L4ConversationKey(defragmentedIpv4Packet);
                return(new RawPacket(firstTimestamp, LinkLayers.Raw, defragmentedIpv4Packet.Bytes, defragmentedL3L4Key,
                                     this.MaxNumberOfShards));
            }

            // Ignore unsupported transport protocols
            var transportPacket = ipPacket.PayloadPacket;

            if (!(transportPacket is TcpPacket || transportPacket is UdpPacket))
            {
                return(new ProcessRawPacketRequestError("Unsupported transport protocol"));
            }

            var l3L4Key = new L3L4ConversationKey(ipPacket);

            return(new RawPacket(rawCapture, l3L4Key, this.MaxNumberOfShards));
        }
コード例 #21
0
        public XamMac(out IRendererFactory rendererFactory)
            : base()
        {
            rendererFactory = new FrameFactory(() => /*CGLGetCurrentContext()*/ NSOpenGLContext.CurrentContext?.CGLContext.Handle ?? IntPtr.Zero);

            Application.Initialize(ToolkitType.XamMac);

            // NSApplication.Initialize(); // Problem: This does not allow creating a separate app and using CocoaNativeWindow.
        }
コード例 #22
0
        private EditTextFrame CreateTextFrame(string id, string value)
        {
            EditTextFrame frame = (EditTextFrame)FrameFactory.GetFrame(id);

            frame.Text = value;

            V2Tag.Add(frame);

            return(frame);
        }
コード例 #23
0
        public void ParseString_StingIsInvalid_RaiseException()
        {
            string        testString   = "These,are,not,integers";
            IFrameFactory frameFactory = new FrameFactory();
            IGameFactory  gameFactory  = new GameFactory(frameFactory);

            IStringParser stringParser = new StringParser(gameFactory);

            stringParser.GetGamesInString(testString);
        }
コード例 #24
0
        public void ParseString_ValueOutOfRange_RaiseException()
        {
            string        testString   = "10,10,10,10,10,99999,10,10,10,10,10";
            IFrameFactory frameFactory = new FrameFactory();
            IGameFactory  gameFactory  = new GameFactory(frameFactory);

            IStringParser stringParser = new StringParser(gameFactory);

            stringParser.GetGamesInString(testString);
        }
コード例 #25
0
        public void ParseCsv_FileDoesNotExist_RaisesException()
        {
            string        testFilePath = "ThisFileDoesn'tExist";
            IFrameFactory frameFactory = new FrameFactory();
            IGameFactory  gameFactory  = new GameFactory(frameFactory);
            IStringParser stringParser = new StringParser(gameFactory);

            ICsvParser csvParser = new CsvParser(stringParser);

            csvParser.GetGamesInCsv(testFilePath);
        }
コード例 #26
0
        private static Person CreateTarget(out Context target)
        {
            var obj = new Person("Alice");

            obj.Occupation = "Student";
            target         = new Context(obj.ToString());
            target.AddFrame(FrameFactory.Create(obj));
            obj.Occupation = "Lawyer";
            target.AddFrame(FrameFactory.Create(obj));
            return(obj);
        }
コード例 #27
0
        public void WorstGameEver_TenFrames_ScoreIs0()
        {
            FrameFactory testFactory = new FrameFactory();
            Game         testGame    = new Game(testFactory);

            while (testGame.IsFinished != true)
            {
                testGame.AddScore(0);
            }
            Assert.AreEqual(0, testGame.GetTotalScore());
        }
コード例 #28
0
        public void SpareEveryFrame_FivePinsPerBall_ScoreIs150()
        {
            FrameFactory testFactory = new FrameFactory();
            Game         testGame    = new Game(testFactory);

            while (testGame.IsFinished != true)
            {
                testGame.AddScore(5);
            }
            Assert.AreEqual(150, testGame.GetTotalScore());
        }
コード例 #29
0
        public void PerfectGame_TwentyFrames_ScoreIs600()
        {
            FrameFactory testFactory = new FrameFactory();
            Game         testGame    = new Game(testFactory, 20);

            while (testGame.IsFinished != true)
            {
                testGame.AddScore(10);
            }
            Assert.AreEqual(600, testGame.GetTotalScore());
        }
コード例 #30
0
ファイル: ReassemblingTestBase.cs プロジェクト: nesfit/NTPAC
        protected IEnumerable <Frame> GetFramesFromPcapWithoutDefragmentation(String pcapFileName)
        {
            var frames = new List <Frame>();

            foreach (var(packet, timestampTicks) in this.GetPacketsFromPcap(pcapFileName))
            {
                var frame = FrameFactory.CreateFromPacket(packet, timestampTicks);
                frames.Add(frame);
            }
            return(frames);
        }