Exemple #1
1
        static void Main(string[] args)
        {
            const int NumberOfAnimals = 10;
            Stack<Animal> animalStack = new Stack<Animal>();
            Queue<Animal> animalQueue = new Queue<Animal>();

            Console.WriteLine("/// ORDER OF ENTRY...");
            Random r = new Random();
            for (int index = 0; index < NumberOfAnimals; index++)
            {
                var animalShouldBeCat = (r.Next(2) == 0);
                uint nextWeight = (uint)r.Next(10, 40);
                Animal nextAnimal = animalShouldBeCat ? (Animal)(new Cat(nextWeight, "John")) : (Animal)(new Dog(nextWeight, "Dave"));
                animalStack.Push(nextAnimal);
                animalQueue.Enqueue(nextAnimal);
                Console.WriteLine(nextAnimal);
            }

            Console.WriteLine();
            Console.WriteLine("/// OUTPUT FROM STACK...");
            foreach (Animal animal in animalStack)
            {
                Console.WriteLine(animal);
            }

            Console.WriteLine();
            Console.WriteLine("/// OUTPUT FROM QUEUE...");
            foreach (Animal animal in animalQueue)
            {
                Console.WriteLine(animal);
            }
        }
Exemple #2
1
        private void CollectEntities(int addr, Dictionary<int, Entity> list)
        {
            int num = addr;
            addr = M.ReadInt(addr + 4);
            var hashSet = new HashSet<int>();
            var queue = new Queue<int>();
            queue.Enqueue(addr);
            while (queue.Count > 0)
            {
                int nextAddr = queue.Dequeue();
                if (hashSet.Contains(nextAddr))
                    continue;

                hashSet.Add(nextAddr);
                if (M.ReadByte(nextAddr + 21) == 0 && nextAddr != num && nextAddr != 0)
                {
                    int key = M.ReadInt(nextAddr + 12);
                    if (!list.ContainsKey(key))
                    {
                        int address = M.ReadInt(nextAddr + 16);
                        var entity = base.GetObject<Entity>(address);
                        list.Add(key, entity);
                    }
                    queue.Enqueue(M.ReadInt(nextAddr));
                    queue.Enqueue(M.ReadInt(nextAddr + 8));
                }
            }
        }
Exemple #3
0
        public App()
        {
            UnhandledException += Application_UnhandledException;
            QueueFileOpenPickerArgs = new Queue<FileOpenPickerContinuationEventArgs>();
            if (Debugger.IsAttached)
                Host.Settings.EnableFrameRateCounter = true;

            InitializeComponent();

            InitializePhoneApplication();

            // Show graphics profiling information while debugging.
            if (System.Diagnostics.Debugger.IsAttached)
            {
                // Display the current frame rate counters.
                Application.Current.Host.Settings.EnableFrameRateCounter = true;

                // Show the areas of the app that are being redrawn in each frame.
                //Application.Current.Host.Settings.EnableRedrawRegions = true;

                // Display the metro grid helper.
                MetroGridHelper.IsVisible = true;

                // Enable non-production analysis visualization mode, 
                // which shows areas of a page that are handed off to GPU with a colored overlay.
                //Application.Current.Host.Settings.EnableCacheVisualization = true;

                // Disable the application idle detection by setting the UserIdleDetectionMode property of the
                // application's PhoneApplicationService object to Disabled.
                // Caution:- Use this under debug mode only. Application that disable user idle detection will continue to run
                // and consume battery power when the user is not using the phone.
                PhoneApplicationService.Current.UserIdleDetectionMode = IdleDetectionMode.Disabled;
            }
        }
Exemple #4
0
        /*************************/
        // Selecting initial vertices
        /*************************/
        // Returns a vertex on the last level of a Breadth-first search (BFS)
        public static int BFS(Graph graph, int init)
        {
            // BFS working queue
            Queue<int> queue = new Queue<int>();
            // Vertices that have already been visited
            Set<int> visited = new Set<int>();

            // Initial vertex is given as input
            visited.Add(init);
            queue.Enqueue(init);
            int current = init;

            // While there is still a vertex in the queue...
            while (queue.Count > 0)
            {
                //... select the first vertex and process it
                current = queue.Dequeue();
                foreach (int w in graph.OpenNeighborhood(current))
                {
                    // Enqueue all neighbors that have not been processed yet
                    if (!visited.Contains(w))
                    {
                        visited.Add(w);
                        queue.Enqueue(w);
                    }
                }
            }
            // This is the last vertex that has been processed, thus a vertex that is on the last level of the BFS search
            return current;
        }
Exemple #5
0
    private int BFS(int startEdge, int endEdge)
    {
        bool[] used = new bool[MaxNumber + 1];
        int level = 0;
        Queue<int> nodesQueue = new Queue<int>();
        nodesQueue.Enqueue(startEdge);
        while (nodesQueue.Count > 0)
        {
            Queue<int> nextLevelNodes = new Queue<int>();
            level++;
            while (nodesQueue.Count > 0)
            {
                int node = nodesQueue.Dequeue();
                if (node == endEdge)
                {
                    return level - 1;
                }

                // Pressing the left button
                for (int i = 0; i < WheelsCount; i++)
                {
                    int newNode = node;
                    int digit = (node / powerOf10[i]) % 10;
                    if (digit == 9)
                    {
                        newNode -= 9 * powerOf10[i];
                    }
                    else
                    {
                        newNode += powerOf10[i];
                    }
                    if (used[newNode]) continue;
                    if (isForbiddenEdge[newNode]) continue;
                    used[newNode] = true;
                    nextLevelNodes.Enqueue(newNode);
                }

                // Pressing the right button
                for (int i = 0; i < WheelsCount; i++)
                {
                    int newNode = node;
                    int digit = (node / powerOf10[i]) % 10;
                    if (digit == 0)
                    {
                        newNode += 9 * powerOf10[i];
                    }
                    else
                    {
                        newNode -= powerOf10[i];
                    }
                    if (used[newNode]) continue;
                    if (isForbiddenEdge[newNode]) continue;
                    used[newNode] = true;
                    nextLevelNodes.Enqueue(newNode);
                }
            }
            nodesQueue = nextLevelNodes;
        }
        return -1;
    }
Exemple #6
0
        static void Main(string[] args)
        {
            List<int> list = new List<int>
            {
                3,2,
            }; // 3, 2

            list.Add(5); // 3, 2, 5
            list.Add(6); // 3, 2, 5, 6
            list.Remove(5); // 3, 2, 6

            Queue<int> queue = new Queue<int>();
            queue.Enqueue(3);// 3
            queue.Enqueue(8);// 3, 8
            queue.Dequeue(); // 8

            Stack<int> stack = new Stack<int>();
            stack.Push(2); // 2
            stack.Push(7); // 7, 2
            stack.Push(8); // 8, 7, 2
            stack.Pop();   // 7, 2

            foreach (var i in stack)
            {
                Console.WriteLine(i);
            }

            LinkedList<int> linkedList = new LinkedList<int>();
            linkedList.AddFirst(9); // 9
            linkedList.AddAfter(linkedList.Find(9), 5); // 9, 5
            linkedList.Remove(9); // 5

            Console.Read();
        }
Exemple #7
0
 public void PlayMessage(Queue<string> messages)
 {
     dialogue.gameObject.SetActive(true);
     player.state = Player.State.Interacting;
     msgQueue = messages;
     PlayNextMessage();
 }
 public void Write(Queue<CollectableValue> values)
 {
     foreach (CollectableValue value in values)
     {
         Write(value);
     }
 }
        public DashboardView()
        {
            InitializeComponent();

            AndonManager = new AndonManager(StationList, null, Andonmanager.AndonManager.MODE.MASTER);

            AndonManager.start();
            StationList = new Queue<int>();

            Plans = new Plans();
            PlanGrid.DataContext = Plans;

            Actuals = new Models.Actuals();
            ActualGrid.DataContext = Actuals;

            AppTimer = new Timer(1000);
            AppTimer.AutoReset = false;
            AppTimer.Elapsed += AppTimer_Elapsed;

            EfficiencyWatch = new Stopwatch();

            using (PSBContext DBContext = new PSBContext())
            {

                Shifts = DBContext.Shifts.ToList();

                foreach (Shift s in Shifts)
                {
                    s.Update();
                }

            }

            AppTimer.Start();
        }
Exemple #10
0
    public bool NegTest1()
    {
        bool retVal = true;
        TestLibrary.TestFramework.BeginScenario("NegTest1: InvalidOperationException should be thrown when the queue is empty.");

        try
        {
            Queue<string> TestQueue = new Queue<string>();
            TestQueue.Peek();
            TestLibrary.TestFramework.LogError("N01.1", "InvalidOperationException is not thrown when the queue is empty!");
            retVal = false;
        }
        catch (InvalidOperationException)
        {

        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("N01.2", "Unexpected exception: " + e);
            TestLibrary.TestFramework.LogVerbose(e.StackTrace);
            retVal = false;
        }

        return retVal;
    }
 private static void TraverseWithBFS(string[,] matrix, Cell startCell)
 {
     Queue<Cell> visitedCells = new Queue<Cell>();
     visitedCells.Enqueue(startCell);
     while (visitedCells.Count > 0)
     {
         Cell cell = visitedCells.Dequeue();
         int row = cell.Row;
         int col = cell.Col;
         int dist = cell.Distance;
         matrix[row, col] = dist.ToString();
         if (IsInMatrix(matrix, row + 1, col) && matrix[row + 1, col] == "0")
         {
             visitedCells.Enqueue(new Cell(row + 1, col, dist + 1));
         }
         if (IsInMatrix(matrix, row, col + 1) && matrix[row, col + 1] == "0")
         {
             visitedCells.Enqueue(new Cell(row, col + 1, dist + 1));
         }
         if (IsInMatrix(matrix, row - 1, col) && matrix[row - 1, col] == "0")
         {
             visitedCells.Enqueue(new Cell(row - 1, col, dist + 1));
         }
         if (IsInMatrix(matrix, row, col - 1) && matrix[row, col - 1] == "0")
         {
             visitedCells.Enqueue(new Cell(row, col - 1, dist + 1));
         }
     }
 }
Exemple #12
0
        public Eywi(string fileName)
        {
            IEnumerator<string> iter = File.ReadLines(fileName).GetEnumerator();
            if (iter.MoveNext())
            {
                string firstLine = iter.Current;
                string[] firsts = firstLine.Split(' ');
                if (firsts[0].StartsWith("VERSION="))
                    Version = int.Parse(firsts[0].Substring("VERSION=".Length));
                if (firsts[1].StartsWith("UID="))
                    Uid = ushort.Parse(firsts[1].Substring("UID=".Length));
                if (firsts.Length > 2 && firsts[2].StartsWith("ENCRY=0"))
                    Encryed = false;
                else
                    Encryed = true;
            }
            magnification = new float[] { 0.25f, 0.5f, 1, 2, 4, 8 };
            magnificationFlat = new float[] { 0.75f, 0.9f, 1, 1.25f, 1.75f, 2.5f };
            magnificationstr = new string[] { "0.25", "0.5", "1", "2", "4", "8" };
            mMagIndex = 2;
            mInProcess = true;
            yMessage = new Queue<string>();

            dixits = new List<string>();
            while (iter.MoveNext())
                dixits.Add(iter.Current);
            dixitCursor = 0;
        }
Exemple #13
0
    public bool PosTest1()
    {
        bool retVal = true;
        TestLibrary.TestFramework.BeginScenario("PosTest1: Test whether Peek() is successful when the queue is not empty.");

        try
        {
            Queue<string> TestQueue = new Queue<string>();
            TestQueue.Enqueue("one");
            TestQueue.Enqueue("two");
            TestQueue.Enqueue("three");
            string PeekResult = TestQueue.Peek();
            if (PeekResult != "one")
            {
                TestLibrary.TestFramework.LogError("P01.1", "Peek() failed! Expected value is "+"\"one\". But actual value is \""+PeekResult+"\".");
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("P01.2", "Unexpected exception: " + e);
            TestLibrary.TestFramework.LogVerbose(e.StackTrace);
            retVal = false;
        }

        return retVal;
    }
Exemple #14
0
        private Queue<Message> SetMessageOrder(IEnumerable<Message> unorderedMessages)
        {
            var messages = new Queue<Message>(
                unorderedMessages.OrderBy(x => x.MessengerOrderId));

            return messages;
        }
Exemple #15
0
 public BreadthFirstSearch(Graph graph)
 {
     this.graph = graph;
     traversedVertex = new bool[graph.Vertices.Count()];
     queueVertices = new Queue<int>();
     distance = new int[graph.Vertices.Count()];
 }
Exemple #16
0
	public void GenerateTileMap()
	{
		allTileCoords = new List<Coord> ();

		for (int x = 0; x < mapSize.x; x ++) {

			for (int y = 0; y < mapSize.y; y ++) {

				allTileCoords.Add(new Coord(x,y));

			}

		}

		shuffledTileCoords = new Queue<Coord> (Utility.ShuffleArray (allTileCoords.ToArray (), seed));

		string holderName = "Generated Map";

		if (transform.FindChild (holderName)) {

			DestroyImmediate (transform.FindChild (holderName).gameObject);
		}

		Transform mapHolder = new GameObject (holderName).transform;
		mapHolder.parent = transform;

		for (int x = 0; x < mapSize.x; x ++) {

			for (int y = 0; y < mapSize.y; y ++) {

				Vector3 tilePosition = CoordToPosition(x,y);

				Transform newTile = Instantiate (tilePrefab, tilePosition, Quaternion.Euler (Vector3.right * 90)) as Transform;

				newTile.localScale = Vector3.one * (1 - outlinePercent) * tileSize;

				newTile.parent = mapHolder;


			}


		}

		/*int obstacleCount = 10;

		for (int i =0; i < obstacleCount; i ++) {

			Coord randomCoord = GetRandomCoord();

			Vector3 obstaclePosition = CoordToPosition(randomCoord.x,randomCoord.y);

			Transform newObstacle = Instantiate(navPrefab, obstaclePosition + Vector3.up * .5f, Quaternion.identity) as Transform;

			newObstacle.parent = mapHolder;
		}*/



	}
        public Mapquest_Matrix(List <double> latitude,List<double> longitude, double depotlatitude,double depotlongitude)
        {
            finishedthreads=0;
            points = new Queue<PointD>();
            this.depotlatitude = depotlatitude;
            this.depotlongitude = depotlongitude;
            latitude.Insert(0, depotlatitude);
            longitude.Insert(0, depotlongitude);
            distancematrix = new List<List<Double>>();
            for (int i = 0; i < latitude.Count; i++)
            {

                distancematrix.Add(new List<Double>());
                for (int j = 0; j < latitude.Count; j++)
                {
                    if (i < j)
                    {
                        points.Enqueue(new PointD(latitude[i], longitude[i], i, latitude[j], longitude[j], j));
                    }
                        distancematrix[i].Add(100000);
                }
            }
            latitude.RemoveAt(0);
            longitude.RemoveAt(0);
        }
Exemple #18
0
		internal Dispatcher()
		{
			State = new NepripojenoState();
			_comPortCommunicator = new Communicator(this);

			_messagesToSend = new Queue<Message>();
		}
        /// <summary>
        /// Performs additional hardware initilization
        /// </summary>
        public void InitializeDriver()
        {
            mBuffer=new Queue<byte[]>(16);
            //Turn on Tx and Rx
            EnableTransmit();
            EnableReceive();
            //Initialize buffers
            InitTransmitBuffer();
            InitReceiveBuffer();
            
            //Setting Transmit configuration
            var tcr = Register.TransmitConfigurationRegister.Load(mem);
            tcr.Init();
            SetEarlyTxThreshold(1024);
            
            //Setting Receive configuration
            var rcr = Register.ReceiveConfigurationRegister.Load(mem);
            rcr.Init();
            rcr.PromiscuousMode = true;
            
            //Enable IRQ Interrupt
            //Cosmos.Hardware2.Interrupts.IRQ11 += HandleNetworkInterrupt;
            //Interrupts.AddIRQHandler(pciCard.InterruptLine, HandleNetworkInterrupt);

            InitIRQMaskRegister();
            mInstance = this;
            //DebugWriteLine("Listening for IRQ" + pciCard.InterruptLine + ".");

        }
Exemple #20
0
        private static void AddTriVertexCycle(List<int> list)
        {
            Queue<int> queue = new Queue<int>();
            int minVertex = Int32.MaxValue;

            for (var i = 0; i < 3; i++)
            {
                int vertex = list[list.Count - 3 + i];
                if (vertex < minVertex)
                {
                    minVertex = vertex;
                }
                queue.Enqueue(vertex);
            }

            while (minVertex != queue.Peek())
            {
                queue.Enqueue(queue.Dequeue());
            }

            string str = "{" + string.Join(" -> ", queue) + "}";
            if (!uniqueCycles.Contains(str))
            {
                uniqueCycles.Add(str);
                Console.WriteLine(str);
            }
        }
Exemple #21
0
        /// <summary>
        /// Initializes a new instance of the <see cref="LocationService"/> class.
        /// </summary>
        public LocationService()
        {
            var interval = TimeSpan.FromSeconds(1);
            _timer = new Timer(OnTimerTick, null, interval, interval);

            ExpectedLocations = new Queue<LocationTestData>();
        }
Exemple #22
0
        /// <summary>
        /// Instantiates MmfReader.
        /// </summary>
        /// <param name="ipcType">Identifies memory mapped file and used to authenticate incoming data.</param>
        /// <param name="bufferLength">Length of data segment</param>
        /// <param name="ignoreExceptions">True if exceptions should be handled; false if they should be thrown to caller</param>
        public MmfReader(string ipcType, int bufferLength, Niawa.Utilities.UtilsServiceBus utilsBus, bool ignoreExceptions)
        {
            try
            {
                _receiveQueue = new Queue<NiawaMmfContainer>();

                _ipcType = ipcType;
                _description = "MmfReader " + _ipcType;
                _bufferLength = bufferLength;
                _ignoreExceptions = ignoreExceptions;

                _lastMsgID = 0;
                _threadStatus = new Niawa.Threading.ThreadStatus(_description, 60, utilsBus.InitializeSerialId(Niawa.Utilities.IdGeneratorUtils.ID_ROOT_NIAWA_THREAD_ID).ToString(), string.Empty, null);

                //thread status
                _threadStatus.Status = Niawa.Threading.ThreadStatus.STATUS_INITIALIZED;

            }
            catch (Exception ex)
            {
                logger.Error("[" + _description + "-M] Exception while instantiating: " + ex.Message, ex);
                if (!ignoreExceptions)
                    throw ex;
            }
        }
Exemple #23
0
        public static List<Tuple<String, String>> MatchFormat(String Format, String Line)
        {
            var Matches = new List<Tuple<String, String>>();

            var FormatChunks = new Queue<String>(Tokenize(Format));
            var LineChunks = new Queue<String>(Tokenize(Line));

            while (FormatChunks.Count > 0)
            {
                var CurrentFormat = FormatChunks.Dequeue();
                var CurrentLine = LineChunks.Dequeue();

                switch (CurrentFormat)
                {
                    default:
                        if (CurrentFormat[0] == '%')
                        {
                            Matches.Add(new Tuple<String, String>(CurrentFormat, CurrentLine));
                        }
                        else
                        {
                            if (CurrentLine != CurrentFormat) throw (new InvalidDataException());
                        }
                        break;
                }
            }

            if (LineChunks.Count > 0)
            {
                throw (new InvalidDataException("Unexpected token '" + LineChunks.Dequeue() + "' on '" + Line + "' for format '" + Format + "'"));
            }

            return Matches;
        }
		public static void EnqueueRecursive(AbstractProjectBrowserTreeNode node)
		{
			lock (queue) {
				if (inQueue.Add(node))
					queue.Enqueue(node);
				// use breadth-first search
				Queue<AbstractProjectBrowserTreeNode> q = new Queue<AbstractProjectBrowserTreeNode>();
				q.Enqueue(node);
				while (q.Count > 0) {
					node = q.Dequeue();
					foreach (TreeNode n in node.Nodes) {
						node = n as AbstractProjectBrowserTreeNode;
						if (node != null) {
							q.Enqueue(node);
							if (inQueue.Add(node))
								queue.Enqueue(node);
						}
					}
				}
				
				if (!threadRunning) {
					threadRunning = true;
					ThreadPool.QueueUserWorkItem(Run);
				}
			}
		}
            public async Task RetriesWhenResendRequested()
            {
                var firstResponse = new TwoFactorRequiredException(TwoFactorType.AuthenticatorApp);
                var challengeResults = new Queue<TwoFactorChallengeResult>(new[]
                {
                    TwoFactorChallengeResult.RequestResendCode,
                    new TwoFactorChallengeResult("two-factor-code")
                });
                var secondResponse = new Authorization { Token = "OAUTHSECRET" };

                var client = Substitute.For<IObservableAuthorizationsClient>();
                client.GetOrCreateApplicationAuthentication(Args.String, Args.String, Args.NewAuthorization)
                    .Returns(Observable.Throw<Authorization>(firstResponse));
                client.GetOrCreateApplicationAuthentication(
                    Args.String,
                    Args.String,
                    Args.NewAuthorization,
                    "two-factor-code")
                    .Returns(Observable.Return(secondResponse));

                var result = await client.GetOrCreateApplicationAuthentication(
                    "clientId",
                    "secret",
                    new NewAuthorization { Note = "Was it this one?" },
                    _ => Observable.Return(challengeResults.Dequeue()));

                client.Received(2).GetOrCreateApplicationAuthentication("clientId",
                    "secret",
                    Arg.Any<NewAuthorization>());
                client.Received().GetOrCreateApplicationAuthentication("clientId",
                    "secret",
                    Arg.Any<NewAuthorization>(), "two-factor-code");
                Assert.Equal("OAUTHSECRET", result.Token);
            }
Exemple #26
0
        protected MapItem(IntVector2 hexQuoords, World world)
        {
            HexQuoordinates = hexQuoords;
            World = world;

            Tasks = new Queue<Task>();
        }
Exemple #27
0
        public bool Execute(params object[] stuff)
        {
            if (Room == null) return false;
            Queue<RoomItem> toRemove = new Queue<RoomItem>();

            if (Items.Any())
            {
                foreach (RoomItem item in Items)
                {
                    if (item == null || Room.GetRoomItemHandler().GetItem(item.Id) == null)
                    {
                        toRemove.Enqueue(item);
                        continue;
                    }

                    HandleMovement(item);
                }
            }


            while (toRemove.Count > 0)
            {
                RoomItem itemToRemove = toRemove.Dequeue();

                if (Items.Contains(itemToRemove))
                    Items.Remove(itemToRemove);
            }

            return true;
        }
    static void Main()
    {
        //S1 = N;
        //S2 = S1 + 1;
        //S3 = 2 * S1 + 1;
        //S4 = S1 + 2;
        //S5 = S2 + 1;
        //S6 = 2 * S2 + 1;
        //S7 = S2 + 2;
        //Using the Queue<T> class write a program to print its first 50 members for given N.
        //Example: N=2 -> 2, 3, 5, 4, 4, 7, 5, 6, 11, 7, 5, 9, 6, ...

        Queue<int> queue = new Queue<int>();
        queue.Enqueue(2);
        for (int i = 1; i <= 50; i++)
        {
            int s = queue.Dequeue();

            queue.Enqueue(s + 1);
            queue.Enqueue(2 * s + 1);
            queue.Enqueue(s + 2);

            Console.WriteLine("{0}. {1}", i, s);
        }
    }
 public GlobalCacheEntity()
 {
     _readCount = 0;
     _lock = Lock.None;
     _isDeleted = false;
     _blockThreads = new Queue<Thread>();
 }
        static IEnumerable<string> Search(string root, string searchPattern)
        {
            // taken from: http://stackoverflow.com/a/438316/105999
            Queue<string> dirs = new Queue<string>();
            dirs.Enqueue(root);
            while (dirs.Count > 0) {
                string dir = dirs.Dequeue();

                // files
                string[] paths = null;
                try {
                    paths = Directory.GetFiles(dir, searchPattern);
                }
                catch(Exception ex) { } // swallow

                if (paths != null && paths.Length > 0) {
                    foreach (string file in paths) {
                        yield return file;
                    }
                }

                // sub-directories
                paths = null;
                try {
                    paths = Directory.GetDirectories(dir);
                }
                catch(Exception ex) { } // swallow

                if (paths != null && paths.Length > 0) {
                    foreach (string subDir in paths) {
                        dirs.Enqueue(subDir);
                    }
                }
            }
        }
 public Task <Queue> CreatePrivateQueueAsync(Queue queue, bool isTransactional = true)
 {
     Guard.NotNull(() => queue, queue);
     return(_queueOperations.CreateQueueAsync(queue, isTransactional));
 }
Exemple #32
0
    public static IEnumerator Explode(Vector3 hitPoint, float radius, float force, Stats returnedStats, bool immidiateHingeBreak = false)
    {
        Debug.Log("Explosion started!");
        Stopwatch stopWatch = new Stopwatch();

        stopWatch.Start();
        int fragmentsExploded = 0;

        Collider[] colliders = Physics.OverlapSphere(hitPoint, radius);

        HashSet <FragmentsGraph> graphsToFlood = new HashSet <FragmentsGraph>();
        HashSet <FragmentsGraph> graphsVisited = new HashSet <FragmentsGraph>();

        foreach (Collider collider in colliders)
        {
            if (collider.CompareTag(Constants.FrozenFragmentStr))
            {
                FragmentsGraph fragmentsGraph = collider.transform.parent.gameObject.GetComponent <FragmentsGraph>();
                if (fragmentsGraph != null)
                {
                    GameObject[] neighbours = new GameObject[fragmentsGraph.graph.GetNeighbours(collider.gameObject).Count];
                    fragmentsGraph.graph.GetNeighbours(collider.gameObject).Keys.CopyTo(neighbours, 0);

                    // Remove hinges
                    foreach (GameObject neighbour in neighbours)
                    {
                        Object.Destroy(fragmentsGraph.graph.GetEdgeData(collider.gameObject, neighbour));
                        Object.Destroy(fragmentsGraph.graph.GetEdgeData(neighbour, collider.gameObject));

                        fragmentsGraph.graph.RemoveEdge(collider.gameObject, neighbour);
                        fragmentsGraph.graph.RemoveEdge(neighbour, collider.gameObject);
                    }

                    fragmentsGraph.graph.RemoveNode(collider.gameObject);
                    if (fragmentsGraph.anchoredFragments != null)
                    {
                        fragmentsGraph.anchoredFragments.Remove(collider.gameObject);
                    }
                    fragmentsGraph.currentFragmentsCount--;

                    graphsVisited.Add(fragmentsGraph);
                }

                DestroyFragment(collider.gameObject, hitPoint, radius, force);
                ++fragmentsExploded;
            }
            // Apply force to already destroyed fragment.
            else if (collider.CompareTag(Constants.MovingFragmentStr))
            {
                Rigidbody rb = collider.gameObject.GetComponent <Rigidbody>();
                if (rb != null)
                {
                    rb.AddExplosionForce(force, hitPoint, radius);
                }
            }

            // Ensure the current function operation does not take a lot of time
            // in a single frame.
            if (stopWatch.ElapsedMilliseconds > Constants.MaxTimeMs)
            {
                Debug.Log("Explosion Yield in parsing colliders");
                returnedStats.totalTime += stopWatch.ElapsedMilliseconds;
                yield return(null);

                stopWatch.Restart();
            }
        }

        bool destroyedAll = false;

        void DestroyAllFragments(FragmentsGraph fg)
        {
            foreach (GameObject fragment in fg.graph.GetNodes())
            {
                foreach (KeyValuePair <GameObject, HingeJoint> pair in fg.graph.GetNeighbours(fragment))
                {
                    Object.Destroy(pair.Value, Random.Range(Constants.FragmentHingeMinDestroyDelay, Constants.FragmentHingeMaxDestroyDelay));
                }

                DestroyFragment(fragment, hitPoint, radius, force, immidiateHingeBreak);
            }
            fg.graph                = null;
            fg.anchoredFragments    = null;
            fg.initialAnchoredCount = 0;
            destroyedAll            = true;
            Debug.Log("Destroyed all fragments");
        }

        foreach (FragmentsGraph fragmentsGraph in graphsVisited)
        {
            if (fragmentsGraph.currentFragmentsCount <= 0.25f * fragmentsGraph.initialFragmentsCount ||
                fragmentsGraph.anchoredFragments == null)
            {
                DestroyAllFragments(fragmentsGraph);
            }
            else
            {
                // Flood fill
                Queue <GameObject>   toVisit = new Queue <GameObject>();
                HashSet <GameObject> visited = new HashSet <GameObject>();

                foreach (GameObject anchoredFragmnt in fragmentsGraph.anchoredFragments)
                {
                    toVisit.Enqueue(anchoredFragmnt);
                }

                while (toVisit.Count > 0)
                {
                    GameObject fragment = toVisit.Dequeue();
                    visited.Add(fragment);

                    if (fragmentsGraph.graph.ContainsNode(fragment))
                    {
                        foreach (GameObject neighbour in fragmentsGraph.graph.GetNeighbours(fragment).Keys)
                        {
                            if (!visited.Contains(neighbour))
                            {
                                toVisit.Enqueue(neighbour);
                            }
                        }
                    }

                    // Ensure the current function operation does not take a lot of time
                    // in a single frame.
                    if (stopWatch.ElapsedMilliseconds > Constants.MaxTimeMs)
                    {
                        Debug.Log("Explosion Yield in flood fill");
                        returnedStats.totalTime += stopWatch.ElapsedMilliseconds;
                        yield return(null);

                        stopWatch.Restart();
                    }
                }

                if (visited.Count <= 0.25f * fragmentsGraph.initialFragmentsCount)
                {
                    DestroyAllFragments(fragmentsGraph);
                }
            }
        }

        foreach (FragmentsGraph fragmentsGraph in graphsToFlood)
        {
            // Destroy entire mesh when a certain threshold is exceeded.
            if (fragmentsGraph.anchoredFragments.Count < fragmentsGraph.initialAnchoredCount / 2)
            {
                foreach (GameObject fragment in fragmentsGraph.graph.GetNodes())
                {
                    //fragmentsGraph.anchoredFragments.Remove(fragment);
                    DestroyFragment(fragment, hitPoint, radius, force);

                    // Ensure the current function operation does not take a lot of time
                    // in a single frame.
                    if (stopWatch.ElapsedMilliseconds > Constants.MaxTimeMs)
                    {
                        Debug.Log("Explosion Yield in destroying entire mesh");
                        yield return(null);

                        stopWatch.Restart();
                    }
                }
                fragmentsGraph.graph                = null;
                fragmentsGraph.anchoredFragments    = null;
                fragmentsGraph.initialAnchoredCount = 0;
            }
            else
            {
                // Use flood fill to detect isolated islands of fragments.
                Queue <GameObject>   toVisit = new Queue <GameObject>();
                HashSet <GameObject> visited = new HashSet <GameObject>();

                foreach (GameObject anchoredFragmnt in fragmentsGraph.anchoredFragments)
                {
                    toVisit.Enqueue(anchoredFragmnt);
                }

                while (toVisit.Count > 0)
                {
                    GameObject fragment = toVisit.Dequeue();
                    visited.Add(fragment);

                    if (fragmentsGraph.graph.ContainsNode(fragment))
                    {
                        foreach (GameObject neighbour in fragmentsGraph.graph.GetNeighbours(fragment).Keys)
                        {
                            if (!visited.Contains(neighbour))
                            {
                                toVisit.Enqueue(neighbour);
                            }
                        }
                    }

                    // Ensure the current function operation does not take a lot of time
                    // in a single frame.
                    if (stopWatch.ElapsedMilliseconds > Constants.MaxTimeMs)
                    {
                        Debug.Log("Explosion Yield in flood fill");
                        yield return(null);

                        stopWatch.Restart();
                    }
                }

                // Find isolated islands of fragments and destroy all fragments from them.
                HashSet <GameObject> toRemove = new HashSet <GameObject>();

                foreach (GameObject fragment in fragmentsGraph.graph.GetNodes())
                {
                    if (!visited.Contains(fragment))
                    {
                        toRemove.Add(fragment);
                    }

                    // Ensure the current function operation does not take a lot of time
                    // in a single frame.
                    if (stopWatch.ElapsedMilliseconds > Constants.MaxTimeMs)
                    {
                        Debug.Log("Explosion Yield in finding islands");
                        yield return(null);

                        stopWatch.Restart();
                    }
                }

                foreach (GameObject fragment in toRemove)
                {
                    fragmentsGraph.graph.RemoveNode(fragment);
                    fragmentsGraph.anchoredFragments.Remove(fragment);
                    DestroyFragment(fragment, hitPoint, radius, force);
                }
            }
        }

        if (returnedStats != null)
        {
            returnedStats.isDone               = true;
            returnedStats.fragments            = fragmentsExploded;
            returnedStats.fragmentedGameObject = null;
            returnedStats.destroyedAll         = destroyedAll;
        }
    }
Exemple #33
0
        public async Task WhenDnsServerListening_AndDnsRequestReceivedRepeatedly_ThenResponsesReturnedInRoundRobinOrder_Async()
        {
            // Arrange.
            Queue <CancellationTokenSource> sources = new Queue <CancellationTokenSource>();
            Queue <byte[]>    responses             = new Queue <byte[]>();
            Mock <IUdpClient> udpClient             = new Mock <IUdpClient>();

            udpClient.Setup(c => c.ReceiveAsync()).ReturnsAsync(new Tuple <IPEndPoint, byte[]>(new IPEndPoint(IPAddress.Loopback, 80), this.GetDnsRequest()));
            udpClient.Setup(c => c.SendAsync(It.IsAny <byte[]>(), It.IsAny <int>(), It.IsAny <IPEndPoint>())).Callback <byte[], int, IPEndPoint>((p, s, ip) =>
            {
                // One response at a time.
                responses.Enqueue(p);
                CancellationTokenSource source = sources.Dequeue();
                source.Cancel();
            }).ReturnsAsync(1);

            DnsSeedMasterFile masterFile = new DnsSeedMasterFile();

            masterFile.Add(new IPAddressResourceRecord(new Domain("google.com"), IPAddress.Parse("192.168.0.1")));
            masterFile.Add(new IPAddressResourceRecord(new Domain("google.com"), IPAddress.Parse("192.168.0.2")));
            masterFile.Add(new IPAddressResourceRecord(new Domain("google.com"), IPAddress.Parse("192.168.0.3")));
            masterFile.Add(new IPAddressResourceRecord(new Domain("google.com"), IPAddress.Parse("192.168.0.4")));

            IAsyncLoopFactory asyncLoopFactory = new Mock <IAsyncLoopFactory>().Object;
            INodeLifetime     nodeLifetime     = new Mock <INodeLifetime>().Object;
            DnsSettings       dnsSettings      = new Mock <DnsSettings>().Object;

            dnsSettings.DnsHostName   = "host.example.com";
            dnsSettings.DnsNameServer = "ns1.host.example.com";
            dnsSettings.DnsMailBox    = "*****@*****.**";
            DataFolder dataFolder = CreateDataFolder(this);

            Mock <ILogger>        logger        = new Mock <ILogger>();
            Mock <ILoggerFactory> loggerFactory = new Mock <ILoggerFactory>();

            loggerFactory.Setup <ILogger>(f => f.CreateLogger(It.IsAny <string>())).Returns(logger.Object);

            IDateTimeProvider dateTimeProvider = new Mock <IDateTimeProvider>().Object;

            // Act (Part 1).
            DnsSeedServer server = new DnsSeedServer(udpClient.Object, masterFile, asyncLoopFactory, nodeLifetime, loggerFactory.Object, dateTimeProvider, dnsSettings, dataFolder);

            try
            {
                CancellationTokenSource source = new CancellationTokenSource();
                sources.Enqueue(source);
                await server.ListenAsync(53, source.Token);
            }
            catch (OperationCanceledException)
            {
                // Expected.
            }

            // Assert (Part 1).
            responses.Count.Should().Be(1);
            byte[]    response    = responses.Dequeue();
            IResponse dnsResponse = Response.FromArray(response);

            dnsResponse.AnswerRecords.Count.Should().Be(4);
            dnsResponse.AnswerRecords[0].Should().BeOfType <IPAddressResourceRecord>();

            ((IPAddressResourceRecord)dnsResponse.AnswerRecords[0]).IPAddress.ToString().Should().Be("192.168.0.1");

            while (responses.Count > 0)
            {
                // Consume queue completely.
                responses.Dequeue();
            }

            // Act (Part 2).
            try
            {
                CancellationTokenSource source = new CancellationTokenSource();
                sources.Enqueue(source);
                await server.ListenAsync(53, source.Token);
            }
            catch (OperationCanceledException)
            {
                // Expected.
            }

            // Assert (Part 2).
            responses.Count.Should().Be(1);
            response    = responses.Dequeue();
            dnsResponse = Response.FromArray(response);

            dnsResponse.AnswerRecords.Count.Should().Be(4);
            dnsResponse.AnswerRecords[0].Should().BeOfType <IPAddressResourceRecord>();

            ((IPAddressResourceRecord)dnsResponse.AnswerRecords[0]).IPAddress.ToString().Should().Be("192.168.0.2");

            while (responses.Count > 0)
            {
                // Consume queue completely.
                responses.Dequeue();
            }

            // Act (Part 3).
            try
            {
                CancellationTokenSource source = new CancellationTokenSource();
                sources.Enqueue(source);
                await server.ListenAsync(53, source.Token);
            }
            catch (OperationCanceledException)
            {
                // Expected.
            }

            // Assert (Part 3).
            responses.Count.Should().Be(1);
            response    = responses.Dequeue();
            dnsResponse = Response.FromArray(response);

            dnsResponse.AnswerRecords.Count.Should().Be(4);
            dnsResponse.AnswerRecords[0].Should().BeOfType <IPAddressResourceRecord>();

            ((IPAddressResourceRecord)dnsResponse.AnswerRecords[0]).IPAddress.ToString().Should().Be("192.168.0.3");

            while (responses.Count > 0)
            {
                // Consume queue completely.
                responses.Dequeue();
            }

            // Act (Part 4).
            try
            {
                CancellationTokenSource source = new CancellationTokenSource();
                sources.Enqueue(source);
                await server.ListenAsync(53, source.Token);
            }
            catch (OperationCanceledException)
            {
                // Expected.
            }

            // Assert (Part 4).
            responses.Count.Should().Be(1);
            response    = responses.Dequeue();
            dnsResponse = Response.FromArray(response);

            dnsResponse.AnswerRecords.Count.Should().Be(4);
            dnsResponse.AnswerRecords[0].Should().BeOfType <IPAddressResourceRecord>();

            ((IPAddressResourceRecord)dnsResponse.AnswerRecords[0]).IPAddress.ToString().Should().Be("192.168.0.4");

            while (responses.Count > 0)
            {
                // Consume queue completely.
                responses.Dequeue();
            }

            // Act (Part 5).
            try
            {
                CancellationTokenSource source = new CancellationTokenSource();
                sources.Enqueue(source);
                await server.ListenAsync(53, source.Token);
            }
            catch (OperationCanceledException)
            {
                // Expected.
            }

            // Assert (Part 5).
            responses.Count.Should().Be(1);
            response    = responses.Dequeue();
            dnsResponse = Response.FromArray(response);

            dnsResponse.AnswerRecords.Count.Should().Be(4);
            dnsResponse.AnswerRecords[0].Should().BeOfType <IPAddressResourceRecord>();

            // This should start back at the beginning again.
            ((IPAddressResourceRecord)dnsResponse.AnswerRecords[0]).IPAddress.ToString().Should().Be("192.168.0.1");

            while (responses.Count > 0)
            {
                // Consume queue completely.
                responses.Dequeue();
            }
        }
		public static object Parse ( Type retType, string [] args, ArgumentStyle style, bool skipNoMember = false )
		{
			object ret = Activator.CreateInstance ( retType );
			TypeUtility util = new TypeUtility ( retType );

			char separatorChar = ConvertSeparator ( style.Separator );

			Queue<string> argsQueue = new Queue<string> ( args );
			while ( argsQueue.Count > 0 )
			{
				string arg = argsQueue.Dequeue ();

				bool isShortName = false;
				string key = null, value = null;

				if ( ( ( style.NamePrestring != style.ShortNamePrestring ) && !string.IsNullOrEmpty ( style.ShortNamePrestring ) )
					&& ( arg.Substring ( 0, style.NamePrestring.Length ) != style.NamePrestring )
					&& ( arg.Substring ( 0, style.ShortNamePrestring.Length ) == style.ShortNamePrestring ) )
					isShortName = true;

				int separatorIndex = arg.IndexOf ( separatorChar );
				if ( separatorIndex >= 0 )
				{
					key = arg.Substring ( 2, separatorIndex - 2 );
					value = arg.Substring ( separatorIndex );
				}
				else
				{
					key = arg;
					if ( key.Substring ( 0, style.NamePrestring.Length ) != style.NamePrestring )
						if ( key.Substring ( 0, style.ShortNamePrestring.Length ) != style.ShortNamePrestring )
						{
							value = key;
							key = null;
						}
				}

				MemberInfo member = util.GetMember ( style, key, isShortName );
				if ( member == null )
				{
					if ( util.ArgumentStoreMember != null )
					{
						util.SetValue ( ref ret, key, value );
						continue;
					}
					else if ( skipNoMember )
						continue;
					else throw new ArgumentException ( "Unknown argument(s) detected." );
				}

				Type memberType = GetMemberType ( member );
				if ( style.Separator == ArgumentKeyValueSeparator.Space && memberType != typeof ( bool ) && value == null && argsQueue.Count > 0 )
					if ( argsQueue.Peek ().Substring ( 0, style.NamePrestring.Length ) != style.NamePrestring &&
						argsQueue.Peek ().Substring ( 0, style.ShortNamePrestring.Length ) != style.ShortNamePrestring )
						value = argsQueue.Dequeue ();

				object settingValue = null;

				if ( memberType == typeof ( bool ) )
					settingValue = ConvertBoolean ( value );
				else if ( memberType == typeof ( string ) )
					settingValue = value;
				else if ( memberType == typeof ( int ) )
					settingValue = int.Parse ( value );
				else if ( memberType == typeof ( uint ) )
					settingValue = uint.Parse ( value );
				else if ( memberType == typeof ( short ) )
					settingValue = short.Parse ( value );
				else if ( memberType == typeof ( ushort ) )
					settingValue = ushort.Parse ( value );
				else if ( memberType == typeof ( long ) )
					settingValue = long.Parse ( value );
				else if ( memberType == typeof ( ulong ) )
					settingValue = ulong.Parse ( value );
				else if ( memberType == typeof ( byte ) )
					settingValue = byte.Parse ( value );
				else if ( memberType == typeof ( sbyte ) )
					settingValue = sbyte.Parse ( value );
				else if ( memberType == typeof ( float ) )
					settingValue = float.Parse ( value );
				else if ( memberType == typeof ( double ) )
					settingValue = double.Parse ( value );
				else if ( memberType == typeof ( DateTime ) )
					settingValue = DateTime.Parse ( value );
				else if ( memberType == typeof ( TimeSpan ) )
					settingValue = TimeSpan.Parse ( value );
				else if ( memberType == typeof ( Enum ) )
				{
					try
					{
						settingValue = Enum.Parse ( memberType, value, true );
					}
					catch
					{
						settingValue = int.Parse ( value );
					}
				}
				else if ( memberType == typeof ( string [] ) )
				{
					settingValue = value.Split ( '|' );
				}
				else
				{
					try
					{
						settingValue = Activator.CreateInstance ( memberType, value );
					}
					catch
					{
						foreach ( var methodInfo in memberType.GetMethods () )
						{
							if ( !methodInfo.IsStatic ) continue;
							if ( methodInfo.ReturnType == typeof ( void ) ) continue;
							var ps = methodInfo.GetParameters ();
							if ( ps.Length != 1 ) continue;
							if ( ps [ 0 ].ParameterType == typeof ( string ) )
							{
								settingValue = methodInfo.Invoke ( memberType, new object [] { value } );
								break;
							}
						}
					}
				}

				if ( !util.SetValue ( ref ret, member, settingValue ) )
					throw new ArgumentException ();
			}

			return ret;
		}
Exemple #35
0
        static void Main()
        {
            var                 MAP       = ReadMap();
            var                 entered   = new bool[Row, Col];
            List <int>          Answer    = new List <int>();
            Queue <List <int> > Histories = new Queue <List <int> >();
            var                 init      = new List <int>(new int[] { sy * 100 + sx });

            Histories.Enqueue(init);
            while (Histories.Count > 0)
            {
                var history = Histories.Dequeue();
                var P       = history.Last();
                if (P / 100 == gy && P % 100 == gx)
                {
                    Answer = history;
                    break;
                }
                if (P % 100 > 0 && !MAP[P / 100, P % 100 - 1] && !entered[P / 100, P % 100 - 1])
                {
                    entered[P / 100, P % 100 - 1] = true;
                    var H = new List <int>();
                    for (int i = 0; i < history.Count; i++)
                    {
                        H.Add(history[i]);
                    }
                    H.Add(P - 1);
                    Histories.Enqueue(H);
                }
                if (P % 100 < Col - 1 && !MAP[P / 100, P % 100 + 1] && !entered[P / 100, P % 100 + 1])
                {
                    entered[P / 100, P % 100 + 1] = true;
                    var H = new List <int>();
                    for (int i = 0; i < history.Count; i++)
                    {
                        H.Add(history[i]);
                    }
                    H.Add(P + 1);
                    Histories.Enqueue(H);
                }

                if (P / 100 > 0 && !MAP[P / 100 - 1, P % 100] && !entered[P / 100 - 1, P % 100])
                {
                    entered[P / 100 - 1, P % 100] = true;
                    var H = new List <int>();
                    for (int i = 0; i < history.Count; i++)
                    {
                        H.Add(history[i]);
                    }
                    H.Add(P - 100);
                    Histories.Enqueue(H);
                }

                if (P / 100 < Row - 1 && !MAP[P / 100 + 1, P % 100] && !entered[P / 100 + 1, P % 100])
                {
                    entered[P / 100 + 1, P % 100] = true;
                    var H = new List <int>();
                    for (int i = 0; i < history.Count; i++)
                    {
                        H.Add(history[i]);
                    }
                    H.Add(P + 100);
                    Histories.Enqueue(H);
                }
            }
            Console.WriteLine(Answer.Count - 1);
        }
Exemple #36
0
 /// <summary>
 /// 文件传输服务初始化
 /// </summary>
 public FileTransmissionServer()
 {
     RecivePacketQuene = new Queue <FilePacket>();
     mReciveQuene      = new Queue <FilePacket>();
 }
Exemple #37
0
 public RingStringAppender(int bufferCapacity, int lineCapacity)
 {
     buffer = new Queue <StringBuilder>(this.bufferCapacity);
     this.bufferCapacity = bufferCapacity;
     this.lineCapacity   = lineCapacity;
 }
    public bool runTest()
    {
        //////////// Global Variables used for all tests
        int iCountErrors    = 0;
        int iCountTestcases = 0;

        Queue arrSon;
        Queue arrMother;

        Task[] workers;
        Action ts1;
        Action ts2;
        Int32  iNumberOfWorkers = 1000;

        try
        {
            do
            {
                /////////////////////////  START TESTS ////////////////////////////
                ///////////////////////////////////////////////////////////////////

                arrMother = new Queue();
                for (int i = 0; i < iNumberOfElements; i++)
                {
                    arrMother.Enqueue(i);
                }

                if (arrMother.SyncRoot.GetType() != typeof(Object))
                {
                    iCountErrors++;
                }

                arrSon            = Queue.Synchronized(arrMother);
                _arrGrandDaughter = Queue.Synchronized(arrSon);
                _arrDaughter      = Queue.Synchronized(arrMother);

                iCountTestcases++;
                if (arrSon.SyncRoot != arrMother.SyncRoot)
                {
                    iCountErrors++;
                }

                iCountTestcases++;
                if (arrSon.SyncRoot != arrMother.SyncRoot)
                {
                    iCountErrors++;
                }

                iCountTestcases++;
                if (_arrGrandDaughter.SyncRoot != arrMother.SyncRoot)
                {
                    iCountErrors++;
                }

                iCountTestcases++;
                if (_arrDaughter.SyncRoot != arrMother.SyncRoot)
                {
                    iCountErrors++;
                }

                iCountTestcases++;
                if (arrSon.SyncRoot != arrMother.SyncRoot)
                {
                    iCountErrors++;
                }

                workers = new Task[iNumberOfWorkers];
                ts1     = new Action(SortElements);
                ts2     = new Action(ReverseElements);
                for (int iThreads = 0; iThreads < iNumberOfWorkers; iThreads += 2)
                {
                    workers[iThreads]     = Task.Run(ts1);
                    workers[iThreads + 1] = Task.Run(ts2);
                }

                Task.WaitAll(workers);
            } while (false);
        }
        catch (Exception exc_general)
        {
            ++iCountErrors;
            Console.WriteLine(" : Error Err_8888yyy! exc_general==\n" + exc_general.ToString());
        }

        return(iCountErrors == 0);
    }
        public int GetMessageCount(Queue queue)
        {
            Guard.NotNull(() => queue, queue);

            return(_queueOperations.GetMessageCount(queue));
        }
        public Queue CreatePrivateQueue(Queue queue, bool transactional = true)
        {
            Guard.NotNull(() => queue, queue);

            return(_queueOperations.CreateQueue(queue, transactional));
        }
        public IList <MessageInfo> GetMessages(Queue queue)
        {
            Guard.NotNull(() => queue, queue);

            return(_queueOperations.GetMessages(queue));
        }
        public MessageBody GetMessageBody(Queue queue, string messageId)
        {
            Guard.NotNull(() => queue, queue);

            return(_queueOperations.GetMessageBody(queue, messageId));
        }
Exemple #43
0
        static int Main(string[] args)
        {
            Log.Initialize(true);
            Log.Console.Enabled         = true;
            Log.Console.AutoColorOutput = true;
            Log.WriteLine("NRO Geolocation DB Generator");
            Log.WriteLine("NRO Registry Processing Tool for Geolocation IP Database generation");
            Log.WriteLine("By RazorSoftware.dev (c) 2020");
            Log.WriteLine("This tool is intended to be used for generating IP-to-Country databases from NRO public stats.");
            Log.WriteLine("All other usages for this tool are explicitly prohibited.");
            Log.WriteLine();

            DateTime startTime = DateTime.Now;

            FileInfo EulaFile = new FileInfo("EULA.txt");

            if (!EulaFile.Exists)
            {
                File.WriteAllText(EulaFile.FullName, Resources.EULA);
                Log.WriteColoredLine("A copy of the EULA has been written to: %@", ConsoleColor.Green, LogLevel.Message, EulaFile.FullName);
            }

            if (args == null || args.Length < 1)
            {
                Log.WriteColoredLine("No arguments given.", ConsoleColor.Red, LogLevel.Error);
                Log.WriteLine();

                FileInfo answersFileTemplate = new FileInfo("answers_file.txt");
                if (!answersFileTemplate.Exists)
                {
                    Settings settings = new Settings();
                    using (FileStream fs = new FileStream(answersFileTemplate.FullName, FileMode.Create, FileAccess.Write, FileShare.None))
                        settings.SaveToStream(fs);
                    Log.WriteColoredLine("A template Answers file has been written to the application directory.\nYou can use it to customize the Application behavior.", ConsoleColor.Green, LogLevel.Message);
                    Log.WriteLine();
                }

                Log.WriteLine("You must specify at least an answers file by supplying the argument --answers=<file> or /answers=<file>");
                Log.WriteLine("      Usage: nroipdbgen --answers=<file>");

                return(EXIT_ARGS_INVALID);
            }

            Settings.Current         = new Settings();
            Processor.TargetInstance = Settings.Current;
            if (!Processor.Parse(args))
            {
                Log.WriteColoredLine("Failed to process command line parameters.", ConsoleColor.Red, LogLevel.Error);
                return(EXIT_ARGS_INVALID);
            }

            if (Settings.Current.ShowHelp)
            {
                Log.WriteLine("NOT IMPLEMENTED.");
                return(EXIT_ARGS_INVALID);
            }

            if (!string.IsNullOrWhiteSpace(Settings.Current.AnswersFile))
            {
                Log.WriteLine("Loading answers file from %@...", LogLevel.Message, Settings.Current.AnswersFile);

                using (FileStream fs = new FileStream(Settings.Current.AnswersFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                    Settings.Current = (Settings)Settings.LoadFromStream(fs, typeof(Settings));

                Log.WriteLine("Answers file loaded.");
            }

            if (Settings.Current.VerboseOutput)
            {
                Log.Console.MinimumLevel = LogLevel.Debug;
            }

            FileInfo Alpha2File = new FileInfo(Settings.Current.Alpha2CodesFile);

            if (!Alpha2File.Exists)
            {
                File.WriteAllText(Alpha2File.FullName, Resources.IsoAlpha2CountryCodes);
            }
            Alpha2File.Refresh();

            try
            {
                Settings.IsoCountryCodes = new Alpha2.IsoAlpha2CountryCodes(Alpha2File);
                Log.WriteLine("Loaded %@ country codes from file %@ for ISO-3166-2.", LogLevel.Debug, Settings.IsoCountryCodes.Count.ToString("N0"), Alpha2File.Name);
            }
            catch (Exception ex)
            {
                Log.WriteLine("Cannot load ISO-3166-2 country file from disk at %@. [%@] %@.", LogLevel.Error, Alpha2File.FullName, ex.GetType().Name, ex.Message);
                return(EXIT_INVALID_RESOURCES);
            }

            try
            {
                while (Console.KeyAvailable)
                {
                    Console.ReadKey();
                }
            }
            catch (Exception ex)
            {
                if (!Settings.Current.HeadlessMode)
                {
                    Log.WriteLine("Console input stream not available. Cannot continue unless --headless or /headless is specified.", LogLevel.Error);
                    Log.WriteLine("[%@] %@", LogLevel.Error, ex.GetType().Name, ex.Message);

                    return(EXIT_ARGS_INVALID);
                }
                else
                {
                    Log.WriteLine("Console input stream not available. Continuing in Headless mode as requested.");
                }
            }

            Log.WriteColoredLine("BEGIN OF PARTIAL EULA", ConsoleColor.Cyan);

            Log.WriteLine(Resources.EULA_Redacted);

            Log.WriteColoredLine("END OF PARTIAL EULA", ConsoleColor.Cyan);
            Log.WriteLine("Full EULA location: %@", LogLevel.Message, EulaFile.FullName);

            if (Settings.Current.IsEulaAccepted)
            {
                Log.WriteColoredLine("EULA has been already accepted by user configuration.", ConsoleColor.Green, LogLevel.Message);
            }
            else
            {
                Log.WriteLine();
                if (Settings.Current.HeadlessMode)
                {
                    Log.WriteLine("Cannot continue. EULA is not accepted and the application is currently running in Headless mode.", LogLevel.Error);
                    Log.WriteLine("Remove the --headless or /headless in command args or accept the EULA on the answers file to continue.", LogLevel.Error);
                    return(EXIT_ARGS_INVALID);
                }
                Log.WriteLine("You must accept the EULA before continuing (type \"I Agree\" without quotes): ");
                string acceptEulaString = Console.ReadLine();

                if (!string.Equals(acceptEulaString, "I Agree", StringComparison.OrdinalIgnoreCase))
                {
                    Log.WriteLine("EULA not accepted. Cannot continue.");
                    return(EXIT_EULA_NOT_ACCEPTED);
                }

                Log.WriteColoredLine("EULA HAS BEEN ACCEPTED.", ConsoleColor.Cyan);
            }

            if (Settings.Current.IsSettingsFileVanilla)
            {
                Log.WriteLine("Cannot load answers file. Please take the time to read it and customize it to your needs.", LogLevel.Error);
                return(EXIT_EULA_NOT_ACCEPTED);
            }

            Log.WriteLine();
            Log.WriteLine();
            Log.WriteLine();
            Log.WriteLine();

            Log.AutoWrappingEnabled = true;


            // Download packages
            List <RirPackage> packages = new List <RirPackage>();

            if (Settings.Current.UseAFRINIC)
            {
                AFRINIC rir = new AFRINIC();
                rir.OfflineMode = Settings.Current.OfflineMode;
                //rir.PublicFtpHostname = "127.0.0.1";
                rir.RequestEmail = Settings.Current.FtpContactEmailAddress;
                RirPackage package = rir.DownloadPackage();

                packages.Add(package);
            }

            if (Settings.Current.UseAPNIC)
            {
                APNIC rir = new APNIC();
                rir.OfflineMode = Settings.Current.OfflineMode;
                //rir.PublicFtpHostname = "127.0.0.1";
                rir.RequestEmail = Settings.Current.FtpContactEmailAddress;
                RirPackage package = rir.DownloadPackage();

                packages.Add(package);
            }

            if (Settings.Current.UseARIN)
            {
                ARIN rir = new ARIN();
                rir.OfflineMode = Settings.Current.OfflineMode;
                //rir.PublicFtpHostname = "127.0.0.1";
                rir.RequestEmail = Settings.Current.FtpContactEmailAddress;
                RirPackage package = rir.DownloadPackage();

                packages.Add(package);
            }

            if (Settings.Current.UseRIPE)
            {
                RIPENCC rir = new RIPENCC();
                rir.OfflineMode = Settings.Current.OfflineMode;
                //rir.PublicFtpHostname = "127.0.0.1";
                rir.RequestEmail = Settings.Current.FtpContactEmailAddress;
                RirPackage package = rir.DownloadPackage();

                packages.Add(package);
            }

            if (Settings.Current.UseLACNIC)
            {
                LACNICv1 rir = new LACNICv1();
                rir.OfflineMode = Settings.Current.OfflineMode;
                //rir.PublicFtpHostname = "127.0.0.1";
                rir.RequestEmail = Settings.Current.FtpContactEmailAddress;
                RirPackage package = rir.DownloadPackage();

                packages.Add(package);
            }


            // Pre-Scan packages
            long totalRecords = 0;

            foreach (RirPackage package in packages)
            {
                package.ScanPackage(Settings.Current.IgnorePackageProcessingErrors);
                if (package.TotalRecordCount > 0)
                {
                    totalRecords += package.TotalRecordCount;
                }
            }

            Log.WriteLine();
            Log.WriteLine("Download succeeded. %@ Total records found for the selected RIRs.", LogLevel.Message, totalRecords.ToString("N0"));

            // Update MySQL
            if (Settings.Current.UpdateMySQL)
            {
                SQL.MySqlDriverConfiguration config = new SQL.MySqlDriverConfiguration(Settings.Current.RemoteMySQLHost,
                                                                                       Settings.Current.RemoteMySQLUsername,
                                                                                       Settings.Current.RemoteMySQLPassword,
                                                                                       Settings.Current.RemoteMySQLSchema,
                                                                                       Settings.Current.RemoteMySQLPrefix);
                config.TableName = Settings.Current.RemoteMySQLTableName;

                SQL.MySqlIpDatabase db = new SQL.MySqlIpDatabase(config);
                db.Connect();

                // Check if table exists
                if (db.GetTableExists())
                {
                    Log.WriteLine("Remote MySQL Table %@ is present on the remote server.", LogLevel.Debug, db.TableName);

                    if (Settings.Current.RemoteMySQLTruncateExisting)
                    {
                        db.TruncateTable();
                    }

                    if (Settings.Current.RemoteMySQLDropExisting)
                    {
                        db.DropTable();
                    }
                }

                // Check if table is missing
                if (!db.GetTableExists())
                {
                    Log.WriteLine("Remote MySQL Table %@ is NOT present on the remote server.", LogLevel.Debug, db.TableName);

                    if (Settings.Current.RemoteMySQLCreateMissing)
                    {
                        db.CreateTable();
                    }
                    else
                    {
                        throw Log.WriteAndMakeException("The specified Table name doesnt exists on the remote MySQL Server.", LogLevel.Error, typeof(InvalidOperationException));
                    }
                }

                db.Begin();

                Log.WriteLine("Updating remote MySQL Table %@::%@.%@:%@...", LogLevel.Message, config.Hostname, config.Schema, config.TablePrefix, config.TableName);

                int processedRecords        = 0;
                int confirmedRecords        = 0;
                ConsoleProgressBar progress = new ConsoleProgressBar();
                if (Settings.Current.HeadlessMode)
                {
                    progress.Enabled = false;
                }
                else
                {
                    progress.Enabled = true;
                    progress.Maximum = totalRecords;
                    progress.Value   = 0;
                }

                Queue <RIR.Package.Reader.RirIpRecord> queuedRecords = new Queue <RIR.Package.Reader.RirIpRecord>(Settings.Current.RemoteMySQLRecordsPerQuery);
                foreach (RirPackage package in packages)
                {
                    foreach (RirPackageEntry entry in package.Entries)
                    {
                        RIR.Package.Reader.RirFileReader reader = entry.Open();
                        RIR.Package.Reader.RirIpRecord   record;
                        while (true)
                        {
                            try
                            {
                                record = reader.NextEntry();
                            }
                            catch (Exception ex)
                            {
                                if (!Settings.Current.HeadlessMode && Console.CursorLeft > 0)
                                {
                                    Console.WriteLine();
                                }
                                if (Settings.Current.IgnorePackageProcessingErrors)
                                {
                                    Log.WriteLine("An error occurred while processing record #%@ from package %@.%@ [%@] %@.", LogLevel.Warning, processedRecords.ToString("N0"), package.RirName, entry.Identifier, ex.GetType().Name, ex.Message);
                                    continue;
                                }

                                Log.WriteLine("An error occurred while processing record #%@ from package %@.%@ [%@] %@.", LogLevel.Error, processedRecords.ToString("N0"), package.RirName, entry.Identifier, ex.GetType().Name, ex.Message);
                                db.Disconnect();
                                return(EXIT_PROCESSING_ERROR);
                            }

                            if (record != null)
                            {
                                queuedRecords.Enqueue(record);
                            }

                            if (queuedRecords.Count >= Settings.Current.RemoteMySQLRecordsPerQuery || record == null)
                            {
                                processedRecords += queuedRecords.Count;
                                confirmedRecords += db.InsertRecords(queuedRecords.ToArray());
                                queuedRecords.Clear();
                                progress.Value = processedRecords;
                            }

                            if (progress.NeedsRedraw)
                            {
                                progress.Refresh();
                            }

                            if (record == null)
                            {
                                break;
                            }
                        }
                    }
                }
                if (!Settings.Current.HeadlessMode && Console.CursorLeft > 0)
                {
                    Console.WriteLine();
                }

                Log.WriteLine("%@ out of %@ MySQL Records updated on the remote database.", LogLevel.Message, confirmedRecords.ToString("N0"), processedRecords.ToString("N0"));

                if (confirmedRecords != processedRecords)
                {
                    Log.WriteLine("Confirmed record count (%@) and processed record count (%@) dont match!. Database may be corrupt.", LogLevel.Warning, confirmedRecords.ToString("N0"), processedRecords.ToString("N0"));
                }

                db.End(true);
                db.Disconnect();

                if (Settings.Current.MySQLDumpCommands)
                {
                    FileInfo dumpFile = new FileInfo(Settings.Current.MySQLDumpFilename);

                    if (!dumpFile.Directory.Exists)
                    {
                        dumpFile.Directory.Create();
                    }
                    Log.WriteLine("Writting SQL history to file %@...", LogLevel.Debug, dumpFile.Name);
                    using (FileStream fs = new FileStream(dumpFile.FullName, FileMode.Create, FileAccess.Write, FileShare.None))
                        db.DumpCommandsToStream(fs);
                }
                Log.WriteLine("MySQL table generation completed.", LogLevel.Debug);
            }

            // Generate SQLite
            if (Settings.Current.GenerateSQLite)
            {
                SQL.SQLiteDriverConfiguration config = new SQL.SQLiteDriverConfiguration(Settings.Current.SQLiteFilename);
                config.TableName = Settings.Current.SQLiteTableName;

                SQL.SQLiteIpDatabase db = new SQL.SQLiteIpDatabase(config);
                db.Connect();

                // Check if table exists
                if (db.GetTableExists())
                {
                    Log.WriteLine("SQLite Table %@ is present on file.", LogLevel.Debug, db.TableName);

                    if (Settings.Current.SQLiteTruncateExisting)
                    {
                        db.TruncateTable();
                    }

                    if (Settings.Current.SQLiteDropExisting)
                    {
                        db.DropTable();
                    }
                }

                // Check if table is missing
                if (!db.GetTableExists())
                {
                    Log.WriteLine("SQLite Table %@ is NOT present on file.", LogLevel.Debug, db.TableName);

                    if (Settings.Current.SQLiteCreateMissing)
                    {
                        db.CreateTable();
                    }
                    else
                    {
                        throw Log.WriteAndMakeException("The specified Table name doesnt exists on file.", LogLevel.Error, typeof(InvalidOperationException));
                    }
                }

                Log.WriteLine("Updating SQLite Table %@ at file %@...", LogLevel.Message, config.TableName, config.DatabaseFile.Name);

                int processedRecords        = 0;
                int confirmedRecords        = 0;
                ConsoleProgressBar progress = new ConsoleProgressBar();
                if (Settings.Current.HeadlessMode)
                {
                    progress.Enabled = false;
                }
                else
                {
                    progress.Enabled = true;
                    progress.Maximum = totalRecords;
                    progress.Value   = 0;
                }

                Queue <RIR.Package.Reader.RirIpRecord> queuedRecords = new Queue <RIR.Package.Reader.RirIpRecord>(Settings.Current.SQLiteRecordsPerQuery);
                foreach (RirPackage package in packages)
                {
                    foreach (RirPackageEntry entry in package.Entries)
                    {
                        RIR.Package.Reader.RirFileReader reader = entry.Open();
                        RIR.Package.Reader.RirIpRecord   record;
                        while (true)
                        {
                            try
                            {
                                record = reader.NextEntry();
                            }
                            catch (Exception ex)
                            {
                                if (!Settings.Current.HeadlessMode && Console.CursorLeft > 0)
                                {
                                    Console.WriteLine();
                                }
                                if (Settings.Current.IgnorePackageProcessingErrors)
                                {
                                    Log.WriteLine("An error occurred while processing record #%@ from package %@.%@ [%@] %@.", LogLevel.Warning, processedRecords.ToString("N0"), package.RirName, entry.Identifier, ex.GetType().Name, ex.Message);
                                    continue;
                                }

                                Log.WriteLine("An error occurred while processing record #%@ from package %@.%@ [%@] %@.", LogLevel.Error, processedRecords.ToString("N0"), package.RirName, entry.Identifier, ex.GetType().Name, ex.Message);
                                db.Disconnect();
                                return(EXIT_PROCESSING_ERROR);
                            }

                            if (record != null)
                            {
                                queuedRecords.Enqueue(record);
                            }

                            if (queuedRecords.Count >= Settings.Current.SQLiteRecordsPerQuery || record == null)
                            {
                                processedRecords += queuedRecords.Count;
                                confirmedRecords += db.InsertRecords(queuedRecords.ToArray());
                                queuedRecords.Clear();
                                progress.Value = processedRecords;
                            }

                            if (progress.NeedsRedraw)
                            {
                                progress.Refresh();
                            }

                            if (record == null)
                            {
                                break;
                            }
                        }
                    }
                }
                if (!Settings.Current.HeadlessMode && Console.CursorLeft > 0)
                {
                    Console.WriteLine();
                }

                Log.WriteLine("%@ out of %@ SQLite Records updated on file.", LogLevel.Message, confirmedRecords.ToString("N0"), processedRecords.ToString("N0"));

                if (confirmedRecords != processedRecords)
                {
                    Log.WriteLine("Confirmed record count (%@) and processed record count (%@) dont match!. Database may be corrupt.", LogLevel.Warning, confirmedRecords.ToString("N0"), processedRecords.ToString("N0"));
                }

                db.Disconnect();

                if (Settings.Current.SQLiteDumpCommands)
                {
                    FileInfo dumpFile = new FileInfo(Settings.Current.SQLiteDumpFilename);

                    if (!dumpFile.Directory.Exists)
                    {
                        dumpFile.Directory.Create();
                    }
                    Log.WriteLine("Writting SQL history to file %@...", LogLevel.Debug, dumpFile.Name);
                    using (FileStream fs = new FileStream(dumpFile.FullName, FileMode.Create, FileAccess.Write, FileShare.None))
                        db.DumpCommandsToStream(fs);
                }
                Log.WriteLine("SQLite table generation completed.", LogLevel.Debug);
            }

            TimeSpan runTime = DateTime.Now - startTime;

            Log.WriteLine("Operation completed in %@. Quitting...", LogLevel.Message, runTime.ToString("d':'hh':'mm':'ss"));
            return(EXIT_SUCCESS);
        }
 Task <int> IQueueManagerAsync.GetMessageCount(Queue queue)
 {
     return(_queueOperations.GetMessageCountAsync(queue));
 }
Exemple #45
0
 public QueueReader(Queue <T> collection)
 {
     m_collection = collection;
 }
 public void Purge(Queue queue)
 {
     Guard.NotNull(() => queue, queue);
     _queueOperations.PurgeQueue(queue);
 }
Exemple #47
0
        public async Task DownloadAsync(IProgress <ProgressReport> progress, CancellationToken cancellationToken)
        {
            string tempFolder     = Path.Combine(Path.GetTempPath(), "TwitchDownloader");
            string downloadFolder = Path.Combine(tempFolder, downloadOptions.Id.ToString() == "0" ? Guid.NewGuid().ToString() : downloadOptions.Id.ToString());

            try
            {
                ServicePointManager.DefaultConnectionLimit = downloadOptions.DownloadThreads;

                if (Directory.Exists(downloadFolder))
                {
                    Directory.Delete(downloadFolder, true);
                }
                Directory.CreateDirectory(downloadFolder);

                string playlistUrl;

                if (downloadOptions.PlaylistUrl == null)
                {
                    Task <JObject> taskInfo        = TwitchHelper.GetVideoInfo(downloadOptions.Id);
                    Task <JObject> taskAccessToken = TwitchHelper.GetVideoToken(downloadOptions.Id, downloadOptions.Oauth);
                    await Task.WhenAll(taskInfo, taskAccessToken);

                    string[] videoPlaylist = await TwitchHelper.GetVideoPlaylist(downloadOptions.Id, taskAccessToken.Result["token"].ToString(), taskAccessToken.Result["sig"].ToString());

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

                    for (int i = 0; i < videoPlaylist.Length; i++)
                    {
                        if (videoPlaylist[i].Contains("#EXT-X-MEDIA"))
                        {
                            string lastPart      = videoPlaylist[i].Substring(videoPlaylist[i].IndexOf("NAME=\"") + 6);
                            string stringQuality = lastPart.Substring(0, lastPart.IndexOf("\""));

                            if (!videoQualities.Any(x => x.Key.Equals(stringQuality)))
                            {
                                videoQualities.Add(new KeyValuePair <string, string>(stringQuality, videoPlaylist[i + 2]));
                            }
                        }
                    }

                    if (videoQualities.Any(x => x.Key.Equals(downloadOptions.Quality)))
                    {
                        playlistUrl = videoQualities.Where(x => x.Key.Equals(downloadOptions.Quality)).First().Value;
                    }
                    else
                    {
                        //Unable to find specified quality, defaulting to highest quality
                        playlistUrl = videoQualities.First().Value;
                    }
                }
                else
                {
                    playlistUrl = downloadOptions.PlaylistUrl;
                }

                string baseUrl = playlistUrl.Substring(0, playlistUrl.LastIndexOf("/") + 1);
                List <KeyValuePair <string, double> > videoList = new List <KeyValuePair <string, double> >();

                using (WebClient client = new WebClient())
                {
                    string[] videoChunks = (await client.DownloadStringTaskAsync(playlistUrl)).Split('\n');

                    for (int i = 0; i < videoChunks.Length; i++)
                    {
                        if (videoChunks[i].Contains("#EXTINF"))
                        {
                            videoList.Add(new KeyValuePair <string, double>(videoChunks[i + 1], Double.Parse(videoChunks[i].Remove(0, 8).TrimEnd(','), CultureInfo.InvariantCulture)));
                        }
                    }
                }

                List <KeyValuePair <string, double> > videoListCropped = GenerateCroppedVideoList(videoList, downloadOptions);
                Queue <string> videoParts = new Queue <string>();
                videoListCropped.ForEach(x => videoParts.Enqueue(x.Key));
                List <string> videoPartsList = new List <string>(videoParts);
                int           partCount      = videoParts.Count;
                int           doneCount      = 0;

                using (var throttler = new SemaphoreSlim(downloadOptions.DownloadThreads))
                {
                    Task[] downloadTasks = videoParts.Select(request => Task.Run(async() =>
                    {
                        await throttler.WaitAsync();
                        try
                        {
                            bool isDone    = false;
                            int errorCount = 0;
                            while (!isDone && errorCount < 10)
                            {
                                try
                                {
                                    using (WebClient client = new WebClient())
                                    {
                                        await client.DownloadFileTaskAsync(baseUrl + request, Path.Combine(downloadFolder, RemoveQueryString(request)));
                                        isDone = true;
                                    }
                                }
                                catch (WebException ex)
                                {
                                    errorCount++;
                                    Debug.WriteLine(ex);
                                    await Task.Delay(10000);
                                }
                            }

                            if (!isDone)
                            {
                                throw new Exception("Video part " + request + " failed after 10 retries");
                            }

                            doneCount++;
                            int percent = (int)Math.Floor(((double)doneCount / (double)partCount) * 100);
                            progress.Report(new ProgressReport()
                            {
                                reportType = ReportType.Message, data = String.Format("Downloading {0}% (1/3)", percent)
                            });
                            progress.Report(new ProgressReport()
                            {
                                reportType = ReportType.Percent, data = percent
                            });

                            return;
                        }
                        catch (Exception ex)
                        {
                            Debug.WriteLine(ex);
                        }
                        finally
                        {
                            throttler.Release();
                        }
                    })).ToArray();
                    await Task.WhenAll(downloadTasks);
                }

                CheckCancelation(cancellationToken, downloadFolder);

                progress.Report(new ProgressReport()
                {
                    reportType = ReportType.Message, data = "Combining Parts (2/3)"
                });
                progress.Report(new ProgressReport()
                {
                    reportType = ReportType.Percent, data = 0
                });

                await Task.Run(() =>
                {
                    string outputFile = Path.Combine(downloadFolder, "output.ts");
                    using (FileStream outputStream = new FileStream(outputFile, FileMode.Create, FileAccess.Write))
                    {
                        foreach (var part in videoPartsList)
                        {
                            string file = Path.Combine(downloadFolder, RemoveQueryString(part));
                            if (File.Exists(file))
                            {
                                byte[] writeBytes = File.ReadAllBytes(file);
                                outputStream.Write(writeBytes, 0, writeBytes.Length);

                                try
                                {
                                    File.Delete(file);
                                }
                                catch { }
                            }
                            CheckCancelation(cancellationToken, downloadFolder);
                        }
                    }
                });


                progress.Report(new ProgressReport()
                {
                    reportType = ReportType.Message, data = "Finalizing MP4 (3/3)"
                });

                double startOffset = 0.0;

                for (int i = 0; i < videoList.Count; i++)
                {
                    if (videoList[i].Key == videoPartsList[0])
                    {
                        break;
                    }

                    startOffset += videoList[i].Value;
                }

                double seekTime     = downloadOptions.CropBeginningTime;
                double seekDuration = Math.Round(downloadOptions.CropEndingTime - seekTime);

                await Task.Run(() =>
                {
                    try
                    {
                        var process = new Process
                        {
                            StartInfo =
                            {
                                FileName               = Path.GetFullPath(downloadOptions.FfmpegPath),
                                Arguments              = String.Format("-y -avoid_negative_ts make_zero -ss {1} -i \"{0}\" -analyzeduration {2} -probesize {2} " + (downloadOptions.CropEnding ? "-t {3} " : "") + "-c:v copy \"{4}\"", Path.Combine(downloadFolder, "output.ts"), (seekTime - startOffset).ToString(), Int32.MaxValue, seekDuration.ToString(), Path.GetFullPath(downloadOptions.Filename)),
                                UseShellExecute        = false,
                                CreateNoWindow         = true,
                                RedirectStandardInput  = false,
                                RedirectStandardOutput = false,
                                RedirectStandardError  = false
                            }
                        };
                        process.Start();
                        process.WaitForExit();
                    }
                    catch (TaskCanceledException) { }
                    Cleanup(downloadFolder);
                });
            }
            catch
            {
                Cleanup(downloadFolder);
                throw;
            }
        }
 Task <IList <MessageInfo> > IQueueManagerAsync.GetMessages(Queue queue)
 {
     return(_queueOperations.GetMessagesAsync(queue));
 }
Exemple #49
0
            internal static void twowaysAMI(Ice.Communicator communicator, Test.MyClassPrx p)
            {
                {
                    var i = Enumerable.Range(0, Length).Select(x => (byte)x).ToArray();
                    var r = p.opAByteSAsync(i).Result;
                    test(r.o.SequenceEqual(i));
                    test(r.returnValue.SequenceEqual(i));
                }

                {
                    var i = Enumerable.Range(0, Length).Select(x => (byte)x).ToList();
                    var r = p.opLByteSAsync(i).Result;
                    test(r.o.SequenceEqual(i));
                    test(r.returnValue.SequenceEqual(i));
                }

                {
                    var i = new LinkedList <byte>(Enumerable.Range(0, Length).Select(x => (byte)x).ToArray());
                    var r = p.opKByteSAsync(i).Result;
                    test(r.o.SequenceEqual(i));
                    test(r.returnValue.SequenceEqual(i));
                }

                {
                    var i = new Queue <byte>(Enumerable.Range(0, Length).Select(x => (byte)x).ToArray());
                    var r = p.opQByteSAsync(i).Result;
                    test(r.o.SequenceEqual(i));
                    test(r.returnValue.SequenceEqual(i));
                }

                {
                    var i = new Stack <byte>(Enumerable.Range(0, Length).Select(x => (byte)x).ToArray());
                    var r = p.opSByteSAsync(i).Result;
                    test(r.o.SequenceEqual(i));
                    test(r.returnValue.SequenceEqual(i));
                }

                {
                    var i = Enumerable.Range(0, Length).Select(x => x % 1 == 1).ToArray();
                    var r = p.opABoolSAsync(i).Result;
                    test(r.o.SequenceEqual(i));
                    test(r.returnValue.SequenceEqual(i));
                }

                {
                    var i = Enumerable.Range(0, Length).Select(x => x % 1 == 1).ToList();
                    var r = p.opLBoolSAsync(i).Result;
                    test(r.o.SequenceEqual(i));
                    test(r.returnValue.SequenceEqual(i));
                }

                {
                    var i = new LinkedList <bool>(Enumerable.Range(0, Length).Select(x => x % 1 == 1).ToArray());
                    var r = p.opKBoolSAsync(i).Result;
                    test(r.o.SequenceEqual(i));
                    test(r.returnValue.SequenceEqual(i));
                }

                {
                    var i = new Queue <bool>(Enumerable.Range(0, Length).Select(x => x % 1 == 1).ToArray());
                    var r = p.opQBoolSAsync(i).Result;
                    test(r.o.SequenceEqual(i));
                    test(r.returnValue.SequenceEqual(i));
                }

                {
                    var i = new Stack <bool>(Enumerable.Range(0, Length).Select(x => x % 1 == 1).ToArray());
                    var r = p.opSBoolSAsync(i).Result;
                    test(r.o.SequenceEqual(i));
                    test(r.returnValue.SequenceEqual(i));
                }

                {
                    var i = Enumerable.Range(0, Length).Select(x => (short)x).ToArray();
                    var r = p.opAShortSAsync(i).Result;
                    test(r.o.SequenceEqual(i));
                    test(r.returnValue.SequenceEqual(i));
                }

                {
                    var i = Enumerable.Range(0, Length).Select(x => (short)x).ToList();
                    var r = p.opLShortSAsync(i).Result;
                    test(r.o.SequenceEqual(i));
                    test(r.returnValue.SequenceEqual(i));
                }

                {
                    var i = new LinkedList <short>(Enumerable.Range(0, Length).Select(x => (short)x).ToArray());
                    var r = p.opKShortSAsync(i).Result;
                    test(r.o.SequenceEqual(i));
                    test(r.returnValue.SequenceEqual(i));
                }

                {
                    var i = new Queue <short>(Enumerable.Range(0, Length).Select(x => (short)x).ToArray());
                    var r = p.opQShortSAsync(i).Result;
                    test(r.o.SequenceEqual(i));
                    test(r.returnValue.SequenceEqual(i));
                }

                {
                    var i = new Stack <short>(Enumerable.Range(0, Length).Select(x => (short)x).ToArray());
                    var r = p.opSShortSAsync(i).Result;
                    test(r.o.SequenceEqual(i));
                    test(r.returnValue.SequenceEqual(i));
                }

                {
                    var i = Enumerable.Range(0, Length).ToArray();
                    var r = p.opAIntSAsync(i).Result;
                    test(r.o.SequenceEqual(i));
                    test(r.returnValue.SequenceEqual(i));
                }

                {
                    var i = Enumerable.Range(0, Length).ToList();
                    var r = p.opLIntSAsync(i).Result;
                    test(r.o.SequenceEqual(i));
                    test(r.returnValue.SequenceEqual(i));
                }

                {
                    var i = new LinkedList <int>(Enumerable.Range(0, Length).ToArray());
                    var r = p.opKIntSAsync(i).Result;
                    test(r.o.SequenceEqual(i));
                    test(r.returnValue.SequenceEqual(i));
                }

                {
                    var i = new Queue <int>(Enumerable.Range(0, Length).ToArray());
                    var r = p.opQIntSAsync(i).Result;
                    test(r.o.SequenceEqual(i));
                    test(r.returnValue.SequenceEqual(i));
                }

                {
                    var i = new Stack <int>(Enumerable.Range(0, Length).ToArray());
                    var r = p.opSIntSAsync(i).Result;
                    test(r.o.SequenceEqual(i));
                    test(r.returnValue.SequenceEqual(i));
                }

                {
                    var i = Enumerable.Range(0, Length).Select(x => (long)x).ToArray();
                    var r = p.opALongSAsync(i).Result;
                    test(r.o.SequenceEqual(i));
                    test(r.returnValue.SequenceEqual(i));
                }

                {
                    var i = Enumerable.Range(0, Length).Select(x => (long)x).ToList();
                    var r = p.opLLongSAsync(i).Result;
                    test(r.o.SequenceEqual(i));
                    test(r.returnValue.SequenceEqual(i));
                }

                {
                    var i = new LinkedList <long>(Enumerable.Range(0, Length).Select(x => (long)x).ToArray());
                    var r = p.opKLongSAsync(i).Result;
                    test(r.o.SequenceEqual(i));
                    test(r.returnValue.SequenceEqual(i));
                }

                {
                    var i = new Queue <long>(Enumerable.Range(0, Length).Select(x => (long)x).ToArray());
                    var r = p.opQLongSAsync(i).Result;
                    test(r.o.SequenceEqual(i));
                    test(r.returnValue.SequenceEqual(i));
                }

                {
                    var i = new Stack <long>(Enumerable.Range(0, Length).Select(x => (long)x).ToArray());
                    var r = p.opSLongSAsync(i).Result;
                    test(r.o.SequenceEqual(i));
                    test(r.returnValue.SequenceEqual(i));
                }

                {
                    var i = Enumerable.Range(0, Length).Select(x => (float)x).ToArray();
                    var r = p.opAFloatSAsync(i).Result;
                    test(r.o.SequenceEqual(i));
                    test(r.returnValue.SequenceEqual(i));
                }

                {
                    var i = Enumerable.Range(0, Length).Select(x => (float)x).ToList();
                    var r = p.opLFloatSAsync(i).Result;
                    test(r.o.SequenceEqual(i));
                    test(r.returnValue.SequenceEqual(i));
                }

                {
                    var i = new LinkedList <float>(Enumerable.Range(0, Length).Select(x => (float)x).ToArray());
                    var r = p.opKFloatSAsync(i).Result;
                    test(r.o.SequenceEqual(i));
                    test(r.returnValue.SequenceEqual(i));
                }

                {
                    var i = new Queue <float>(Enumerable.Range(0, Length).Select(x => (float)x).ToArray());
                    var r = p.opQFloatSAsync(i).Result;
                    test(r.o.SequenceEqual(i));
                    test(r.returnValue.SequenceEqual(i));
                }

                {
                    var i = new Stack <float>(Enumerable.Range(0, Length).Select(x => (float)x).ToArray());
                    var r = p.opSFloatSAsync(i).Result;
                    test(r.o.SequenceEqual(i));
                    test(r.returnValue.SequenceEqual(i));
                }

                {
                    var i = Enumerable.Range(0, Length).Select(x => (double)x).ToArray();
                    var r = p.opADoubleSAsync(i).Result;
                    test(r.o.SequenceEqual(i));
                    test(r.returnValue.SequenceEqual(i));
                }

                {
                    var i = Enumerable.Range(0, Length).Select(x => (double)x).ToList();
                    var r = p.opLDoubleSAsync(i).Result;
                    test(r.o.SequenceEqual(i));
                    test(r.returnValue.SequenceEqual(i));
                }

                {
                    var i = new LinkedList <double>(Enumerable.Range(0, Length).Select(x => (double)x).ToArray());
                    var r = p.opKDoubleSAsync(i).Result;
                    test(r.o.SequenceEqual(i));
                    test(r.returnValue.SequenceEqual(i));
                }

                {
                    var i = new Queue <double>(Enumerable.Range(0, Length).Select(x => (double)x).ToArray());
                    var r = p.opQDoubleSAsync(i).Result;
                    test(r.o.SequenceEqual(i));
                    test(r.returnValue.SequenceEqual(i));
                }

                {
                    var i = new Stack <double>(Enumerable.Range(0, Length).Select(x => (double)x).ToArray());
                    var r = p.opSDoubleSAsync(i).Result;
                    test(r.o.SequenceEqual(i));
                    test(r.returnValue.SequenceEqual(i));
                }

                {
                    var i = Enumerable.Range(0, Length).Select(x => x.ToString()).ToArray();
                    var r = p.opAStringSAsync(i).Result;
                    test(r.o.SequenceEqual(i));
                    test(r.returnValue.SequenceEqual(i));
                }

                {
                    var i = Enumerable.Range(0, Length).Select(x => x.ToString()).ToList();
                    var r = p.opLStringSAsync(i).Result;
                    test(r.o.SequenceEqual(i));
                    test(r.returnValue.SequenceEqual(i));
                }

                {
                    var i = new LinkedList <string>(Enumerable.Range(0, Length).Select(x => x.ToString()).ToArray());
                    var r = p.opKStringSAsync(i).Result;
                    test(r.o.SequenceEqual(i));
                    test(r.returnValue.SequenceEqual(i));
                }

                {
                    var i = new Queue <string>(Enumerable.Range(0, Length).Select(x => x.ToString()).ToArray());
                    var r = p.opQStringSAsync(i).Result;
                    test(r.o.SequenceEqual(i));
                    test(r.returnValue.SequenceEqual(i));
                }

                {
                    var i = new Stack <string>(Enumerable.Range(0, Length).Select(x => x.ToString()).ToArray());
                    var r = p.opSStringSAsync(i).Result;
                    test(r.o.SequenceEqual(i));
                    test(r.returnValue.SequenceEqual(i));
                }

                {
                    var i = Enumerable.Range(0, Length).Select(x => new Test.CV(x) as Value).ToArray();
                    var r = p.opAObjectSAsync(i).Result;
                    test(r.o.SequenceEqual(i, new CVComparer()));
                    test(r.returnValue.SequenceEqual(i, new CVComparer()));
                }

                {
                    var i = Enumerable.Range(0, Length).Select(x => new Test.CV(x) as Value).ToList();
                    var r = p.opLObjectSAsync(i).Result;
                    test(r.o.SequenceEqual(i, new CVComparer()));
                    test(r.returnValue.SequenceEqual(i, new CVComparer()));
                }

                {
                    var i = Enumerable.Range(0, Length).Select(
                        x => communicator.stringToProxy(x.ToString())).ToArray();
                    var r = p.opAObjectPrxSAsync(i).Result;
                    test(r.o.SequenceEqual(i));
                    test(r.returnValue.SequenceEqual(i));
                }

                {
                    var i = Enumerable.Range(0, Length).Select(
                        x => communicator.stringToProxy(x.ToString())).ToList();
                    var r = p.opLObjectPrxSAsync(i).Result;
                    test(r.o.SequenceEqual(i));
                    test(r.returnValue.SequenceEqual(i));
                }

                {
                    var i = new Queue <ObjectPrx>(Enumerable.Range(0, Length).Select(
                                                      x => communicator.stringToProxy(x.ToString())).ToArray());
                    var r = p.opQObjectPrxSAsync(i).Result;
                    test(r.o.SequenceEqual(i));
                    test(r.returnValue.SequenceEqual(i));
                }

                {
                    var i = new Stack <ObjectPrx>(Enumerable.Range(0, Length).Select(
                                                      x => communicator.stringToProxy(x.ToString())).ToArray());
                    var r = p.opSObjectPrxSAsync(i).Result;
                    test(r.o.SequenceEqual(i));
                    test(r.returnValue.SequenceEqual(i));
                }

                {
                    var i = Enumerable.Range(0, Length).Select(x => new Test.S(x)).ToArray();
                    var r = p.opAStructSAsync(i).Result;
                    test(r.o.SequenceEqual(i));
                    test(r.returnValue.SequenceEqual(i));
                }

                {
                    var i = Enumerable.Range(0, Length).Select(x => new Test.S(x)).ToList();
                    var r = p.opLStructSAsync(i).Result;
                    test(r.o.SequenceEqual(i));
                    test(r.returnValue.SequenceEqual(i));
                }

                {
                    var i = new LinkedList <Test.S>(Enumerable.Range(0, Length).Select(x => new Test.S(x)).ToArray());
                    var r = p.opKStructSAsync(i).Result;
                    test(r.o.SequenceEqual(i));
                    test(r.returnValue.SequenceEqual(i));
                }

                {
                    var i = new Queue <Test.S>(Enumerable.Range(0, Length).Select(x => new Test.S(x)).ToArray());
                    var r = p.opQStructSAsync(i).Result;
                    test(r.o.SequenceEqual(i));
                    test(r.returnValue.SequenceEqual(i));
                }

                {
                    var i = new Stack <Test.S>(Enumerable.Range(0, Length).Select(x => new Test.S(x)).ToArray());
                    var r = p.opSStructSAsync(i).Result;
                    test(r.o.SequenceEqual(i));
                    test(r.returnValue.SequenceEqual(i));
                }

                {
                    var i = Enumerable.Range(0, Length).Select(x => new Test.CV(x)).ToArray();
                    var r = p.opACVSAsync(i).Result;
                    test(r.o.SequenceEqual(i, new CVComparer()));
                    test(r.returnValue.SequenceEqual(i, new CVComparer()));
                }

                {
                    var i = Enumerable.Range(0, Length).Select(x => new Test.CV(x)).ToList();
                    var r = p.opLCVSAsync(i).Result;
                    test(r.o.SequenceEqual(i, new CVComparer()));
                    test(r.returnValue.SequenceEqual(i, new CVComparer()));
                }

                {
                    var i = Enumerable.Range(0, Length).Select(
                        x => Test.IPrxHelper.uncheckedCast(communicator.stringToProxy(x.ToString()))).ToArray();
                    var r = p.opAIPrxSAsync(i).Result;
                    test(r.o.SequenceEqual(i));
                    test(r.returnValue.SequenceEqual(i));
                }

                {
                    var i = Enumerable.Range(0, Length).Select(
                        x => Test.IPrxHelper.uncheckedCast(communicator.stringToProxy(x.ToString()))).ToList();
                    var r = p.opLIPrxSAsync(i).Result;
                    test(r.o.SequenceEqual(i));
                    test(r.returnValue.SequenceEqual(i));
                }

                {
                    var i = new LinkedList <Test.IPrx>(Enumerable.Range(0, Length).Select(
                                                           x => Test.IPrxHelper.uncheckedCast(communicator.stringToProxy(x.ToString()))).ToArray());
                    var r = p.opKIPrxSAsync(i).Result;
                    test(r.o.SequenceEqual(i));
                    test(r.returnValue.SequenceEqual(i));
                }

                {
                    var i = new Queue <Test.IPrx>(Enumerable.Range(0, Length).Select(
                                                      x => Test.IPrxHelper.uncheckedCast(communicator.stringToProxy(x.ToString()))).ToArray());
                    var r = p.opQIPrxSAsync(i).Result;
                    test(r.o.SequenceEqual(i));
                    test(r.returnValue.SequenceEqual(i));
                }

                {
                    var i = new Stack <Test.IPrx>(Enumerable.Range(0, Length).Select(
                                                      x => Test.IPrxHelper.uncheckedCast(communicator.stringToProxy(x.ToString()))).ToArray());
                    var r = p.opSIPrxSAsync(i).Result;
                    test(r.o.SequenceEqual(i));
                    test(r.returnValue.SequenceEqual(i));
                }

                {
                    var i = Enumerable.Range(0, Length).Select(x => new Test.CR(new Test.CV(x))).ToArray();
                    var r = p.opACRSAsync(i).Result;
                    test(r.o.SequenceEqual(i, new CRComparer()));
                    test(r.returnValue.SequenceEqual(i, new CRComparer()));
                }

                {
                    var i = Enumerable.Range(0, Length).Select(x => new Test.CR(new Test.CV(x))).ToList();
                    var r = p.opLCRSAsync(i).Result;
                    test(r.o.SequenceEqual(i, new CRComparer()));
                    test(r.returnValue.SequenceEqual(i, new CRComparer()));
                }

                {
                    var i = Enumerable.Range(0, Length).Select(x => (Test.En)(x % 3)).ToArray();
                    var r = p.opAEnSAsync(i).Result;
                    test(r.o.SequenceEqual(i));
                    test(r.returnValue.SequenceEqual(i));
                }

                {
                    var i = Enumerable.Range(0, Length).Select(x => (Test.En)(x % 3)).ToList();
                    var r = p.opLEnSAsync(i).Result;
                    test(r.o.SequenceEqual(i));
                    test(r.returnValue.SequenceEqual(i));
                }

                {
                    var i = new LinkedList <Test.En>(Enumerable.Range(0, Length).Select(
                                                         x => (Test.En)(x % 3)).ToArray());
                    var r = p.opKEnSAsync(i).Result;
                    test(r.o.SequenceEqual(i));
                    test(r.returnValue.SequenceEqual(i));
                }

                {
                    var i = new Queue <Test.En>(Enumerable.Range(0, Length).Select(x => (Test.En)(x % 3)).ToArray());
                    var r = p.opQEnSAsync(i).Result;
                    test(r.o.SequenceEqual(i));
                    test(r.returnValue.SequenceEqual(i));
                }

                {
                    var i = new Stack <Test.En>(Enumerable.Range(0, Length).Select(x => (Test.En)(x % 3)).ToArray());
                    var r = p.opSEnSAsync(i).Result;
                    test(r.o.SequenceEqual(i));
                    test(r.returnValue.SequenceEqual(i));
                }

                {
                    var i = new Custom <int>(Enumerable.Range(0, Length).ToList());
                    var r = p.opCustomIntSAsync(i).Result;
                    test(r.o.SequenceEqual(i));
                    test(r.returnValue.SequenceEqual(i));
                }

                {
                    var i = new Custom <Test.CV>(Enumerable.Range(0, Length).Select(x => new Test.CV(x)).ToList());
                    var r = p.opCustomCVSAsync(i).Result;
                    test(r.o.SequenceEqual(i, new CVComparer()));
                    test(r.returnValue.SequenceEqual(i, new CVComparer()));
                }

                {
                    var i = new Custom <Custom <int> >();
                    for (int c = 0; c < Length; ++c)
                    {
                        i.Add(new Custom <int>(Enumerable.Range(0, Length).ToList()));
                    }
                    var r = p.opCustomIntSSAsync(i).Result;
                    test(r.o.SequenceEqual(i));
                    test(r.returnValue.SequenceEqual(i));
                }

                {
                    var i = new Custom <Custom <Test.CV> >();
                    for (int c = 0; c < Length; ++c)
                    {
                        i.Add(new Custom <Test.CV>(Enumerable.Range(0, Length).Select(x => new Test.CV(x)).ToList()));
                    }
                    var r = p.opCustomCVSSAsync(i).Result;
                    for (int c = 0; c < Length; ++c)
                    {
                        test(r.o[c].SequenceEqual(i[c], new CVComparer()));
                        test(r.returnValue[c].SequenceEqual(i[c], new CVComparer()));
                    }
                }

                {
                    var r = p.opSerialSmallCSharpAsync(null).Result;
                    test(r.o == null);
                    test(r.returnValue == null);
                }

                {
                    var i = new Serialize.Small();
                    i.i = 99;

                    var r = p.opSerialSmallCSharpAsync(i).Result;
                    test(r.o.i == 99);
                    test(r.returnValue.i == 99);
                }

                {
                    var i = new Serialize.Large();
                    i.d1  = 1.0;
                    i.d2  = 2.0;
                    i.d3  = 3.0;
                    i.d4  = 4.0;
                    i.d5  = 5.0;
                    i.d6  = 6.0;
                    i.d7  = 7.0;
                    i.d8  = 8.0;
                    i.d9  = 9.0;
                    i.d10 = 10.0;

                    var r = p.opSerialLargeCSharpAsync(i).Result;

                    test(r.o.d1 == 1.0);
                    test(r.o.d2 == 2.0);
                    test(r.o.d3 == 3.0);
                    test(r.o.d4 == 4.0);
                    test(r.o.d5 == 5.0);
                    test(r.o.d6 == 6.0);
                    test(r.o.d7 == 7.0);
                    test(r.o.d8 == 8.0);
                    test(r.o.d9 == 9.0);
                    test(r.o.d10 == 10.0);

                    test(r.returnValue.d1 == 1.0);
                    test(r.returnValue.d2 == 2.0);
                    test(r.returnValue.d3 == 3.0);
                    test(r.returnValue.d4 == 4.0);
                    test(r.returnValue.d5 == 5.0);
                    test(r.returnValue.d6 == 6.0);
                    test(r.returnValue.d7 == 7.0);
                    test(r.returnValue.d8 == 8.0);
                    test(r.returnValue.d9 == 9.0);
                    test(r.returnValue.d10 == 10.0);
                }

                {
                    var i = new Serialize.Struct();
                    i.o  = null;
                    i.o2 = i;
                    i.s  = null;
                    i.s2 = "Hello";

                    var r = p.opSerialStructCSharpAsync(i).Result;

                    test(r.o.o == null);
                    test(r.o.o2 == r.o);
                    test(r.o.s == null);
                    test(r.o.s2 == "Hello");

                    test(r.returnValue.o == null);
                    test(r.returnValue.o2 == r.returnValue);
                    test(r.returnValue.s == null);
                    test(r.returnValue.s2 == "Hello");
                }
            }
Exemple #50
0
        public MixServerPage()
        {
            InitializeComponent();
            chart1 = new Chart();
            chart2 = new Chart();
            chart3 = new Chart();
            chart4 = new Chart();

            chart1.Rendered += chart_Rendered;
            chart2.Rendered += chart_Rendered;
            chart3.Rendered += chart_Rendered;
            chart4.Rendered += chart_Rendered;


            chart1.BorderThickness = new Thickness(0);
            chart1.Background      = Brushes.Transparent;
            chart1.Margin          = new Thickness(10, 5, 10, 5);
            //是否启用打印和保持图片
            chart1.ToolBarEnabled = false;

            //设置图标的属性
            chart1.ScrollingEnabled = false; //是否启用或禁用滚动
            chart1.View3D           = true;  //3D效果显示


            chart2.BorderThickness = new Thickness(0);
            chart2.Background      = Brushes.Transparent;
            chart2.Margin          = new Thickness(10, 5, 10, 5);
            //是否启用打印和保持图片
            chart2.ToolBarEnabled = false;

            //设置图标的属性
            chart2.ScrollingEnabled = false; //是否启用或禁用滚动
            chart2.View3D           = true;  //3D效果显示
            // chart2.Rendered += chart_Rendered;

            chart3.BorderThickness = new Thickness(0);
            chart3.Background      = Brushes.Transparent;
            chart3.Margin          = new Thickness(10, 5, 10, 5);
            //是否启用打印和保持图片
            chart3.ToolBarEnabled = false;

            //设置图标的属性
            chart3.ScrollingEnabled = false; //是否启用或禁用滚动
            chart3.View3D           = true;  //3D效果显示

            //  chart3.Rendered += chart_Rendered;

            chart4.BorderThickness = new Thickness(0);
            chart4.Background      = Brushes.Transparent;
            chart4.Margin          = new Thickness(10, 5, 10, 5);
            //是否启用打印和保持图片
            chart4.ToolBarEnabled = false;

            //设置图标的属性
            chart4.ScrollingEnabled = false; //是否启用或禁用滚动
            chart4.View3D           = true;  //3D效果显示

            //   chart4.Rendered += chart_Rendered;


            Axis yAxis = new Axis();

            //设置图标中Y轴的最小值永远为0
            yAxis.AxisMinimum = 0;
            yAxis.AxisMaximum = 100;
            yAxis.Interval    = 20;
            //设置图表中Y轴的后缀
            //yAxis.Suffix = sign;
            chart1.AxesY.Add(yAxis);

            Axis yAxis2 = new Axis();

            //设置图标中Y轴的最小值永远为0
            yAxis2.AxisMinimum = 0;
            yAxis2.AxisMaximum = 100;
            yAxis2.Interval    = 20;
            //设置图表中Y轴的后缀
            //yAxis.Suffix = sign;
            chart2.AxesY.Add(yAxis2);


            Axis yAxis3 = new Axis();

            //设置图标中Y轴的最小值永远为0
            yAxis3.AxisMinimum = 0;
            yAxis3.AxisMaximum = 100;
            yAxis3.Interval    = 20;
            //设置图表中Y轴的后缀
            //yAxis.Suffix = sign;
            chart3.AxesY.Add(yAxis3);


            Axis yAxis4 = new Axis();

            //设置图标中Y轴的最小值永远为0
            yAxis4.AxisMinimum = 0;
            yAxis4.AxisMaximum = 100;
            yAxis4.Interval    = 20;
            //设置图表中Y轴的后缀
            //yAxis.Suffix = sign;
            chart4.AxesY.Add(yAxis4);


            value1 = new Queue <double>();
            value2 = new Queue <double>();
            value3 = new Queue <double>();
            value4 = new Queue <double>();
            x      = new Queue <int>();
        }
 private IEnumerable<string> TraverseFilesCore(string path, Func<FileInfo, bool> filter)
 {
     Queue<string> directories = new Queue<string>();
     directories.Enqueue(path);
     while (directories.Count > 0)
     {
         string currentDir = directories.Dequeue();
         IEnumerable<string> files = null;
         try
         {
             files = new DirectoryInfo(currentDir)
                 .GetFiles()
                 .Where(x =>
                 {
                     //why? it prevents exception being thrown inside filter
                     bool success = true;
                     try
                     {
                         success = filter(x);
                     }
                     catch { success = false; }
                     return success;
                 })
                 .Select(x => x.FullName);
         }
         catch (UnauthorizedAccessException ex)
         {
             files = null;
             OnLogError(new TraversalError(ex.Message));
         }
         catch (Exception ex)
         {
             files = null;
             OnLogError(new TraversalError(ex.Message));
         }
         if (files != null)
         {
             foreach (string file in files)
             {
                 yield return file;
             }
         }
         string[] dirs = null;
         try
         {
             dirs = Directory.GetDirectories(currentDir);
         }
         catch (UnauthorizedAccessException ex)
         {
             dirs = null;
             OnLogError(new TraversalError(ex.Message));
         }
         catch (Exception ex)
         {
             dirs = null;
             OnLogError(new TraversalError(ex.Message));
         }
         if (dirs != null)
         {
             for (int i = 0; i < dirs.Length; i++)
             {
                 directories.Enqueue(dirs[i]);
             }
         }
     }
 }
Exemple #52
0
    void Awake()
    {
        destructionQueue = new Queue <GameObject> ();

        foreach (WaitingArea waitingArea in GameObject.FindObjectsOfType <WaitingArea>())
        {
            if (!waitingArea.GetComponent <Platform> ())
            {
                foyer = waitingArea;                    //foyer will be the only waiting area without a platform... if more foyers are added this could be a List
            }
        }

        foreach (Signal signal in GameObject.FindObjectsOfType <Signal>())
        {
            if (signal.signalType == Signal.SignalType.OutOfStation)
            {
                outOfStationTrigger = signal.gameObject.GetComponent <BoxCollider> ();
                break;
            }
        }
        if (!outOfStationTrigger)
        {
            Debug.LogWarning("Out of station trigger not found. Please add one to the scene.");
        }

        if (defaultMaterialColors.Count == 0)
        {
            Debug.LogWarning("No materials assigned to default color array in GameManager. Please do so.");
        }

        if (platforms != null || trainPool != null || destinations != null)
        {
            Debug.LogWarning("Another GameManager has somehow assigned to variables. There should only be one GameManager in the scene.");
        }
        else
        {
            platforms = new ExhaustibleList <Platform> ();
            IEnumerable <Platform> orderedPlatforms = GameObject.FindObjectsOfType <Platform> ().OrderBy(a => a.transform.position.z);                  //order by arrangement on z axis so that platforms can then be numbered sensibly
            int j = 1;
            foreach (Platform platform in orderedPlatforms)
            {
                platform.platformNumber = j++;
                platforms.Add(platform.platformNumber.ToString(), platform);
            }

            trainPool = new ExhaustibleList <Train>();
            Vector3 trainDockingPoint;
            trainDockingPoint.x = outOfStationTrigger.bounds.center.x;
            trainDockingPoint.y = 1.56f;
            trainDockingPoint.z = 20f;
            for (int i = 0; i < oneCarriageTrainCount; i++)
            {
                trainDockingPoint.z += 5f;                      //position trains along the z axis... when they are called into service/ journey time is complete just need to change z position to that of the platform's signal trigger and then go
                GameObject trainGO = Instantiate(oneCarriageTrainPrefab, trainDockingPoint, Quaternion.identity) as GameObject;
                Train      train   = trainGO.GetComponent <Train> ();
                train.Initialise();                     //Initialise some of Trains' properties early as they are required in DisplayManager before Trains' Start() method is called
                train.myDockingPoint = trainDockingPoint;
                trainPool.Add(train.trainSerialID, train);
            }
            for (int i = 0; i < twoCarriageTrainCount; i++)
            {
                trainDockingPoint.z += 5f;                      //position trains along the z axis... when they are called into service/ journey time is complete just need to change z position to that of the platform's signal trigger and then go
                GameObject trainGO = Instantiate(twoCarriageTrainPrefab, trainDockingPoint, Quaternion.identity) as GameObject;
                Train      train   = trainGO.GetComponent <Train> ();
                train.Initialise();                     //Initialise some of Trains' properties early as they are required in DisplayManager before Trains' Start() method is called
                train.myDockingPoint = trainDockingPoint;
                trainPool.Add(train.trainSerialID, train);
            }

            destinations = new List <Destination> ();
            destinations.Add(new Destination("Basimgstoke", 100, 400));
            destinations.Add(new Destination("Bristow", 200, 400));
            destinations.Add(new Destination("Camterbury", 150, 200));
            destinations.Add(new Destination("Edimburgh", 500, 100));                   //takes long time so you want to wait for people to build up
            destinations.Add(new Destination("Lomdom", 70, 2000));
            destinations.Add(new Destination("Southamptom", 100, 400));

            timetable = new List <TimetableItem>();
        }
    }
Exemple #53
0
        private static void Game_OnGameLoad(EventArgs args)
        {
            var name = ObjectManager.Player.ChampionName;

            if (name.Equals("Aatrox"))
            {
                List = Aatrox;
            }
            if (name.Equals("Ahri"))
            {
                List = Ahri;
            }
            if (name.Equals("Akali"))
            {
                List = Akali;
            }
            if (name.Equals("Alistar"))
            {
                List = Alistar;
            }
            if (name.Equals("Amumu"))
            {
                List = Amumu;
            }
            if (name.Equals("Anivia"))
            {
                List = Anivia;
            }
            if (name.Equals("Annie"))
            {
                List = Annie;
            }
            if (name.Equals("Ashe"))
            {
                List = Ashe;
            }
            if (name.Equals("Azir"))
            {
                List = Azir;
            }
            if (name.Equals("Bard"))
            {
                List = Bard;
            }
            if (name.Equals("Blitzcrank"))
            {
                List = Blitzcrank;
            }
            if (name.Equals("Brand"))
            {
                List = Brand;
            }
            if (name.Equals("Braum"))
            {
                List = Braum;
            }
            if (name.Equals("Caitlyn"))
            {
                List = Caitlyn;
            }
            if (name.Equals("Cassiopeia"))
            {
                List = Cassiopeia;
            }
            if (name.Equals("Chogath"))
            {
                List = Chogath;
            }
            if (name.Equals("Corki"))
            {
                List = Corki;
            }
            if (name.Equals("Darius"))
            {
                List = Darius;
            }
            if (name.Equals("Diana"))
            {
                List = Diana;
            }
            if (name.Equals("DrMundo"))
            {
                List = DrMundo;
            }
            if (name.Equals("Draven"))
            {
                List = Draven;
            }
            if (name.Equals("Ekko"))
            {
                List = Ekko;
            }
            if (name.Equals("Elise"))
            {
                List = Elise;
            }
            if (name.Equals("Evelynn"))
            {
                List = Evelynn;
            }
            if (name.Equals("Ezreal"))
            {
                List = Ezreal;
            }
            if (name.Equals("FiddleSticks"))
            {
                List = FiddleSticks;
            }
            if (name.Equals("Fiora"))
            {
                List = Fiora;
            }
            if (name.Equals("Fizz"))
            {
                List = Fizz;
            }
            if (name.Equals("Galio"))
            {
                List = Galio;
            }
            if (name.Equals("Gangplank"))
            {
                List = Gangplank;
            }
            if (name.Equals("Garen"))
            {
                List = Garen;
            }
            if (name.Equals("Gnar"))
            {
                List = Gnar;
            }
            if (name.Equals("Gragas"))
            {
                List = Gragas;
            }
            if (name.Equals("Graves"))
            {
                List = Graves;
            }
            if (name.Equals("Hecarim"))
            {
                List = Hecarim;
            }
            if (name.Equals("Heimerdinger"))
            {
                List = Heimerdinger;
            }
            if (name.Equals("Irelia"))
            {
                List = Irelia;
            }
            if (name.Equals("Janna"))
            {
                List = Janna;
            }
            if (name.Equals("JarvanIV"))
            {
                List = JarvanIV;
            }
            if (name.Equals("Jax"))
            {
                List = Jax;
            }
            if (name.Equals("Jayce"))
            {
                List = Jayce;
            }
            if (name.Equals("Jhin"))
            {
                List = Jhin;
            }
            if (name.Equals("Jinx"))
            {
                List = Jinx;
            }
            if (name.Equals("Kalista"))
            {
                List = Kalista;
            }
            if (name.Equals("Karma"))
            {
                List = Karma;
            }
            if (name.Equals("Karthus"))
            {
                List = Karthus;
            }
            if (name.Equals("Kassadin"))
            {
                List = Kassadin;
            }
            if (name.Equals("Katarina"))
            {
                List = Katarina;
            }
            if (name.Equals("Kayle"))
            {
                List = Kayle;
            }
            if (name.Equals("Kennen"))
            {
                List = Kennen;
            }
            if (name.Equals("Khazix"))
            {
                List = Khazix;
            }
            if (name.Equals("KogMaw"))
            {
                List = KogMaw;
            }
            if (name.Equals("Leblanc"))
            {
                List = Leblanc;
            }
            if (name.Equals("LeeSin"))
            {
                List = LeeSin;
            }
            if (name.Equals("Leona"))
            {
                List = Leona;
            }
            if (name.Equals("Lissandra"))
            {
                List = Lissandra;
            }
            if (name.Equals("Lucian"))
            {
                List = Lucian;
            }
            if (name.Equals("Lulu"))
            {
                List = Lulu;
            }
            if (name.Equals("Lux"))
            {
                List = Lux;
            }
            if (name.Equals("Malphite"))
            {
                List = Malphite;
            }
            if (name.Equals("Malzahar"))
            {
                List = Malzahar;
            }
            if (name.Equals("Maokai"))
            {
                List = Maokai;
            }
            if (name.Equals("MasterYi"))
            {
                List = MasterYi;
            }
            if (name.Equals("MissFortune"))
            {
                List = MissFortune;
            }
            if (name.Equals("Mordekaiser"))
            {
                List = Mordekaiser;
            }
            if (name.Equals("Morgana"))
            {
                List = Morgana;
            }
            if (name.Equals("Nami"))
            {
                List = Nami;
            }
            if (name.Equals("Nasus"))
            {
                List = Nasus;
            }
            if (name.Equals("Nautilus"))
            {
                List = Nautilus;
            }
            if (name.Equals("Nidalee"))
            {
                List = Nidalee;
            }
            if (name.Equals("Nocturne"))
            {
                List = Nocturne;
            }
            if (name.Equals("Nunu"))
            {
                List = Nunu;
            }
            if (name.Equals("Olaf"))
            {
                List = Olaf;
            }
            if (name.Equals("Orianna"))
            {
                List = Orianna;
            }
            if (name.Equals("Pantheon"))
            {
                List = Pantheon;
            }
            if (name.Equals("Poppy"))
            {
                List = Poppy;
            }
            if (name.Equals("Quinn"))
            {
                List = Quinn;
            }
            if (name.Equals("Rammus"))
            {
                List = Rammus;
            }
            if (name.Equals("RekSai"))
            {
                List = RekSai;
            }
            if (name.Equals("Renekton"))
            {
                List = Renekton;
            }
            if (name.Equals("Rengar"))
            {
                List = Rengar;
            }
            if (name.Equals("Riven"))
            {
                List = Riven;
            }
            if (name.Equals("Rumble"))
            {
                List = Rumble;
            }
            if (name.Equals("Ryze"))
            {
                List = Ryze;
            }
            if (name.Equals("Sejuani"))
            {
                List = Sejuani;
            }
            if (name.Equals("Shaco"))
            {
                List = Shaco;
            }
            if (name.Equals("Shen"))
            {
                List = Shen;
            }
            if (name.Equals("Shyvana"))
            {
                List = Shyvana;
            }
            if (name.Equals("Singed"))
            {
                List = Singed;
            }
            if (name.Equals("Sion"))
            {
                List = Sion;
            }
            if (name.Equals("Sivir"))
            {
                List = Sivir;
            }
            if (name.Equals("Skarner"))
            {
                List = Skarner;
            }
            if (name.Equals("Sona"))
            {
                List = Sona;
            }
            if (name.Equals("Soraka"))
            {
                List = Soraka;
            }
            if (name.Equals("Swain"))
            {
                List = Swain;
            }
            if (name.Equals("Syndra"))
            {
                List = Syndra;
            }
            if (name.Equals("TahmKench"))
            {
                List = TahmKench;
            }
            if (name.Equals("Taliyah"))
            {
                List = Taliyah;
            }
            if (name.Equals("Talon"))
            {
                List = Talon;
            }
            if (name.Equals("Taric"))
            {
                List = Taric;
            }
            if (name.Equals("Teemo"))
            {
                List = Teemo;
            }
            if (name.Equals("Thresh"))
            {
                List = Thresh;
            }
            if (name.Equals("Tristana"))
            {
                List = Tristana;
            }
            if (name.Equals("Trundle"))
            {
                List = Trundle;
            }
            if (name.Equals("Tryndamere"))
            {
                List = Tryndamere;
            }
            if (name.Equals("TwistedFate"))
            {
                List = TwistedFate;
            }
            if (name.Equals("Twitch"))
            {
                List = Twitch;
            }
            if (name.Equals("Udyr"))
            {
                List = Udyr;
            }
            if (name.Equals("Urgot"))
            {
                List = Urgot;
            }
            if (name.Equals("Varus"))
            {
                List = Varus;
            }
            if (name.Equals("Vayne"))
            {
                List = Vayne;
            }
            if (name.Equals("Veigar"))
            {
                List = Veigar;
            }
            if (name.Equals("Velkoz"))
            {
                List = Velkoz;
            }
            if (name.Equals("Vi"))
            {
                List = Vi;
            }
            if (name.Equals("Viktor"))
            {
                List = Viktor;
            }
            if (name.Equals("Vladimir"))
            {
                List = Vladimir;
            }
            if (name.Equals("Volibear"))
            {
                List = Volibear;
            }
            if (name.Equals("Warwick"))
            {
                List = Warwick;
            }
            if (name.Equals("MonkeyKing"))
            {
                List = MonkeyKing;
            }
            if (name.Equals("Xerath"))
            {
                List = Xerath;
            }
            if (name.Equals("XinZhao"))
            {
                List = XinZhao;
            }
            if (name.Equals("Yasuo"))
            {
                List = Yasuo;
            }
            if (name.Equals("Yorick"))
            {
                List = Yorick;
            }
            if (name.Equals("Zac"))
            {
                List = Zac;
            }
            if (name.Equals("Zed"))
            {
                List = Zed;
            }
            if (name.Equals("Ziggs"))
            {
                List = Ziggs;
            }
            if (name.Equals("Zilean"))
            {
                List = Zilean;
            }
            if (name.Equals("Zyra"))
            {
                List = Zyra;
            }
            //Cuz while this doesn't have all assemblies will just go for ad
            //List = Sivir;
            Queue = ShoppingQueue();
            AlterInventory();

            /*
             * if (Program.Config.Item("autosharp.shop").GetValue<bool>())
             * {
             *  Game.PrintChat("[{0}] Autobuy Loaded", ObjectManager.Player.ChampionName);
             * }
             * else
             * {
             *  Game.PrintChat("Autobuy has been disabled in the menu.");
             * }
             */
            Game.OnUpdate += BuyItems;
        }
Exemple #54
0
        public int ShortestPathByLeeBFS(int[,] matrix, Point srcPoint, Point destPoint, Stack <Point> resultPath)
        {
            if (matrix == null || matrix.GetLength(0) == 0 || matrix.GetLength(1) == 0)
            {
                return(-1);
            }

            if (matrix[srcPoint.xPos, srcPoint.yPos] != 1 || matrix[destPoint.xPos, destPoint.yPos] != 1)
            {
                return(-1);
            }

            bool[,] visited = new bool[matrix.GetLength(0), matrix.GetLength(1)];

            // Mark the source cell as visited
            visited[srcPoint.xPos, srcPoint.yPos] = true;

            Queue <Vertex> vertexQueue = new Queue <Vertex>();

            Vertex s = new Vertex()
            {
                Point = srcPoint, Distance = 0
            };

            vertexQueue.Enqueue(s);  // Enqueue source cell
            resultPath.Push(srcPoint);

            // These arrays are used to get row and column numbers of 4 neighbours of a given cell
            int[] rowNum = { -1, 0, 0, 1 };
            int[] colNum = { 0, -1, 1, 0 };

            // Do a BFS starting from source cell
            while (vertexQueue.Count > 0)
            {
                Vertex currVertex = vertexQueue.Dequeue();
                Point  currPoint  = currVertex.Point;

                // Reached the destination cell, we are done
                if (currPoint.xPos == destPoint.xPos && currPoint.yPos == destPoint.yPos)
                {
                    return(currVertex.Distance);
                }

                for (int lpCnt = 0; lpCnt < 4; lpCnt++)
                {
                    int rowPos = currPoint.xPos + rowNum[lpCnt];
                    int colPos = currPoint.yPos + colNum[lpCnt];

                    // If adjacent cell is valid, has path and not visited yet, enqueue it.
                    if (Point.IsSafePoint(matrix, rowPos, colPos) == true && visited[rowPos, colPos] == false)
                    {
                        visited[rowPos, colPos] = true;
                        Point point = new Point()
                        {
                            xPos = rowPos, yPos = colPos
                        };
                        Vertex Adjcell = new Vertex()
                        {
                            Point    = point,
                            Distance = currVertex.Distance + 1
                        };
                    }
                }
            }
            return(-1);
        }
Exemple #55
0
        async Task ProcessNavigationForCarouselPage(CarouselPage currentPage, string nextSegment, Queue <string> segments, NavigationParameters parameters, bool?useModalNavigation, bool animated)
        {
            var nextSegmentType = PageNavigationRegistry.GetPageType(UriParsingHelper.GetSegmentName(nextSegment));

            foreach (var child in currentPage.Children)
            {
                if (child.GetType() != nextSegmentType)
                {
                    continue;
                }

                await ProcessNavigation(child, segments, parameters, useModalNavigation, animated);
                await DoNavigateAction(null, nextSegment, child, parameters, onNavigationActionCompleted : () =>
                {
                    currentPage.CurrentPage = child;
                });

                return;
            }

            var nextPage = CreatePageFromSegment(nextSegment);

            await ProcessNavigation(nextPage, segments, parameters, useModalNavigation, animated);
            await DoNavigateAction(currentPage, nextSegment, nextPage, parameters, async() =>
            {
                await DoPush(currentPage, nextPage, useModalNavigation, animated);
            });
        }
Exemple #56
0
        async Task ProcessNavigationForMasterDetailPage(MasterDetailPage currentPage, string nextSegment, Queue <string> segments, NavigationParameters parameters, bool?useModalNavigation, bool animated)
        {
            bool isPresented = GetMasterDetailPageIsPresented(currentPage);

            if (useModalNavigation.HasValue && useModalNavigation.Value)
            {
                var nextPage = CreatePageFromSegment(nextSegment);
                await ProcessNavigation(nextPage, segments, parameters, useModalNavigation, animated);
                await DoNavigateAction(currentPage, nextSegment, nextPage, parameters, async() =>
                {
                    currentPage.IsPresented = isPresented;
                    await DoPush(currentPage, nextPage, true, animated);
                });

                return;
            }

            var detail = currentPage.Detail;

            if (detail == null)
            {
                var newDetail = CreatePageFromSegment(nextSegment);
                await ProcessNavigation(newDetail, segments, parameters, newDetail is NavigationPage?false : true, animated);
                await DoNavigateAction(null, nextSegment, newDetail, parameters, onNavigationActionCompleted : () =>
                {
                    currentPage.IsPresented = isPresented;
                    currentPage.Detail      = newDetail;
                });

                return;
            }

            var nextSegmentType = PageNavigationRegistry.GetPageType(UriParsingHelper.GetSegmentName(nextSegment));

            if (detail.GetType() == nextSegmentType)
            {
                await ProcessNavigation(detail, segments, parameters, useModalNavigation, animated);
                await DoNavigateAction(null, nextSegment, detail, parameters, onNavigationActionCompleted : () =>
                {
                    currentPage.IsPresented = isPresented;
                });

                return;
            }
            else
            {
                var newDetail = CreatePageFromSegment(nextSegment);
                await ProcessNavigation(newDetail, segments, parameters, newDetail is NavigationPage?false : true, animated);
                await DoNavigateAction(detail, nextSegment, newDetail, parameters, onNavigationActionCompleted : () =>
                {
                    currentPage.IsPresented = isPresented;
                    currentPage.Detail      = newDetail;
                });

                return;
            }
        }
Exemple #57
0
        async Task ProcessNavigationForContentPage(Page currentPage, string nextSegment, Queue <string> segments, NavigationParameters parameters, bool?useModalNavigation, bool animated)
        {
            var nextPage = CreatePageFromSegment(nextSegment);

            await ProcessNavigation(nextPage, segments, parameters, useModalNavigation, animated);

            await DoNavigateAction(currentPage, nextSegment, nextPage, parameters, async() =>
            {
                await DoPush(currentPage, nextPage, useModalNavigation, animated);
            });
        }
Exemple #58
0
        async Task ProcessNavigationForNavigationPage(NavigationPage currentPage, string nextSegment, Queue <string> segments, NavigationParameters parameters, bool?useModalNavigation, bool animated)
        {
            if (currentPage.Navigation.NavigationStack.Count == 0)
            {
                var newRoot = CreatePageFromSegment(nextSegment);
                await ProcessNavigation(newRoot, segments, parameters, false, animated);
                await DoNavigateAction(currentPage, nextSegment, newRoot, parameters, async() =>
                {
                    await DoPush(currentPage, newRoot, false, animated);
                });

                return;
            }

            var currentNavRoot = currentPage.Navigation.NavigationStack.Last();
            var nextPageType   = PageNavigationRegistry.GetPageType(UriParsingHelper.GetSegmentName(nextSegment));

            if (currentNavRoot.GetType() == nextPageType)
            {
                await ProcessNavigation(currentNavRoot, segments, parameters, false, animated);
                await DoNavigateAction(currentNavRoot, nextSegment, currentNavRoot, parameters);

                return;
            }
            else
            {
                bool clearNavStack = GetClearNavigationPageNavigationStack(currentPage);

                if (clearNavStack)
                {
                    await currentPage.Navigation.PopToRootAsync(false);
                }

                var newRoot = CreatePageFromSegment(nextSegment);
                await ProcessNavigation(newRoot, segments, parameters, false, animated);

                await DoNavigateAction(currentNavRoot, nextSegment, newRoot, parameters, async() =>
                {
                    var push = DoPush(currentPage, newRoot, false, animated);

                    if (clearNavStack)
                    {
                        currentPage.Navigation.RemovePage(currentPage.Navigation.NavigationStack[0]);
                    }

                    await push;
                });

                return;
            }
        }
 /// <summary>Creates the member entity collections queue.</summary>
 /// <param name="collectionsQueue">The collections queue.</param>
 /// <param name="requiredQueue">The required queue.</param>
 protected override void CreateMemberEntityCollectionsQueue(Queue <IEntityCollection2> collectionsQueue, Queue <bool> requiredQueue)
 {
     base.CreateMemberEntityCollectionsQueue(collectionsQueue, requiredQueue);
     collectionsQueue.Enqueue(requiredQueue.Dequeue() ? new EntityCollection <AuditInfoEntity>(EntityFactoryCache2.GetEntityFactory(typeof(AuditInfoEntityFactory))) : null);
 }
Exemple #60
0
 Task ProcessNavigationForAbsoulteUri(Queue <string> segments, NavigationParameters parameters, bool?useModalNavigation, bool animated)
 {
     return(ProcessNavigation(null, segments, parameters, useModalNavigation, animated));
 }