Exemple #1
0
        /// <summary>
        /// Производит атаку на ячейку
        /// </summary>
        private void AtackCell()
        {
            Cell selectedCell = GetSelectedCell();
            Cell clickedCell  = GetFocusedCell();

            if (selectedCell != null && clickedCell != null)
            {
                if (clickedCell?.Owner == GetActivePlayer())
                {
                    _currentGameState = GameStates.Select;
                    selectedCell.DisactiveCell();
                    clickedCell.ActiveCell();
                }
                else
                {
                    _moveRunner.Move(selectedCell, clickedCell, GetActivePlayer());
                    if (IsFinishedGame())
                    {
                        _currentGameState = GameStates.Finished;
                        FinishedEvent?.Invoke(this, EventArgs.Empty);
                    }
                }
            }

            PaintEvent?.Invoke();
            _button.CallPaintEvent();
        }
Exemple #2
0
        public void CompareTo_ShouldConsiderDNFSlower()
        {
            Beacon martijnBeacon = new Beacon(new byte[] { 0, 0, 0, 0, 0, 1 }, 2);
            Rider  martijn       = new Rider("Martijn", martijnBeacon);

            //make a regular lap
            IdEvent     startId     = new IdEvent(DateTime.Now, martijn, "StartId", Direction.Enter);
            TimingEvent startTiming = new TimingEvent(DateTime.Now, martijn, 100, 0);
            IdEvent     endId       = new IdEvent(DateTime.Now, martijn, "EndId", Direction.Enter);
            TimingEvent endTiming   = new TimingEvent(DateTime.Now, martijn, 200, 1);

            FinishedEvent finish = new FinishedEvent(startId, startTiming, endTiming, endId);

            Lap normalLap = new Lap(finish);

            //make a DNF lap
            IdEvent dnfStartId = new IdEvent(DateTime.Now, martijn, "StartId", Direction.Enter);

            ManualDNFEvent manualDnf = new ManualDNFEvent(dnfStartId, "staff");
            UnitDNFEvent   unitDnf   = new UnitDNFEvent(finish, dnfStartId);

            Lap manualDnfLap = new Lap(manualDnf);
            Lap unitDnfLap   = new Lap(unitDnf);

            //a dnf lap should always be slower (bigger) than a finished lap
            Assert.AreEqual(1, manualDnfLap.CompareTo(normalLap));
            Assert.AreEqual(-1, normalLap.CompareTo(manualDnfLap));

            Assert.AreEqual(1, unitDnfLap.CompareTo(normalLap));
            Assert.AreEqual(-1, normalLap.CompareTo(unitDnfLap));

            //dnf laps have no mutual ordering
            Assert.AreEqual(1, manualDnfLap.CompareTo(unitDnfLap));
            Assert.AreEqual(1, unitDnfLap.CompareTo(manualDnfLap));
        }
Exemple #3
0
        /// <summary>
        /// Enqueues an event, to be handled by subscribers sometime later.
        /// There is no guarantee that the event will end up being handled
        /// (e.g. suspended or shut down queues silently ignore events,
        /// or the application may be terminated beforehand).
        /// </summary>
        /// <param name="eventQueue">The event queue to add the event to.</param>
        /// <param name="evnt">The event to enqueue.</param>
        /// <param name="onHandled">An optional delegate to invoke sometime after the event finished being handled. It may not get called, if the event queue is suspended or being shut down. Check the return value to know whether you can reasonably expect it.</param>
        /// <param name="file">The source file of the caller.</param>
        /// <param name="member">The method or property name of the caller to this method.</param>
        /// <param name="line">The line number in <paramref name="file"/>.</param>
        /// <returns><c>true</c> if the event was enqueued successfully and you can expect a callback once it's done being handled; otherwise, <c>false</c>.</returns>
        public static bool Enqueue(
            this IEventQueue eventQueue,
            EventBase evnt,
            EventHandledDelegate onHandled,
            [CallerFilePath] string file     = "",
            [CallerMemberName] string member = "",
            [CallerLineNumber] int line      = 0)
        {
            if (onHandled.NullReference())
            {
                return(eventQueue.Enqueue(evnt, file, member, line));
            }

            var finishedEvent    = new FinishedEvent(evnt);
            var finishedListener = new FinishedEventHandler(eventQueue, finishedEvent.Index, onHandled);

            eventQueue.Subscribers.Add(finishedListener, weakRef: false);

            var eventsAdded = eventQueue.Enqueue(evnt, file, member, line) &&
                              eventQueue.Enqueue(finishedEvent, file, member, line); // doesn't even get called if the first one fails, which is what we want.

            if (!eventsAdded)
            {
                eventQueue.Subscribers.Remove(finishedListener);
            }

            return(eventsAdded);
        }
Exemple #4
0
 public void RemoveOnFinished(FinishedEvent call)
 {
     if (onFinished != null)
     {
         this.onFinished.Remove(call);
     }
 }
Exemple #5
0
        private IEnumerator CallWrapper()
        {
            yield return(null);

            while (IsRunning)
            {
                if (IsPaused)
                {
                    yield return(null);
                }
                else
                {
                    if (Enumerator != null && Enumerator.MoveNext())
                    {
                        yield return(Enumerator.Current);
                    }
                    else
                    {
                        IsRunning = false;
                    }
                }
            }

            FinishedEvent?.Invoke(this, stoppedManually);
        }
Exemple #6
0
            private void DoWork()
            {
                try
                {
                    //iterate action while previous action in chain is not completed
                    do
                    {
                        _action(_param1, _param2);
                    } while (!PreviousTaskIsCompleted());

                    _action(_param1, _param2);
                }

                catch (Exception exception)
                {
                    exception.Source = $"{Name}: {exception.Source}. Thread: {Thread.CurrentThread.Name}";
                    this.Exception   = exception;
                }
                finally
                {
                    FinishedFlag = true;

                    if (Exception != null)
                    {
                        //signal error to for other threads in chain
                        try { SignalError(); }
                        catch { } //ignore possible error in callback;
                    }
                    //set completed flag
                    FinishedEvent.Set();
                }
            }
Exemple #7
0
        public SimulationTimingUnit(RaceSummary race)
            : base(race)
        {
            FinishedEvent finish = race.Events.Find(r => r is FinishedEvent) as FinishedEvent;

            StartId = finish.TimeStart.GateId;
            EndId   = finish.TimeEnd.GateId;
        }
Exemple #8
0
 public void AddOnFinished(FinishedEvent call)
 {
     if (onFinished == null)
     {
         onFinished = new List <FinishedEvent>();
     }
     this.onFinished.Add(call);
 }
Exemple #9
0
 /// <summary>
 /// 外部から呼び出す、フェードアウト開始関数
 /// </summary>
 /// <param name="time">何秒かけてフェードアウトするか</param>
 /// <param name="finishedEvent">終了時に呼ばれる関数</param>
 public void Out(float time, FinishedEvent finishedEvent = null)
 {
     image.raycastTarget = true;
     this.finishedEvent  = finishedEvent;
     remainingTime       = time;
     addAmout            = (1.0f - image.color.a) / time;
     doing = true;
 }
Exemple #10
0
 /// <summary>
 /// 外部から呼び出す、フェードイン開始関数
 /// </summary>
 /// <param name="time">何秒かけてフェードインするか</param>
 /// <param name="finishedEvent">終了時に呼ばれる関数</param>
 public void In(float time, FinishedEvent finishedEvent = null)
 {
     image.raycastTarget = false;
     this.finishedEvent  = finishedEvent;
     remainingTime       = time;
     addAmout            = -image.color.a / time;
     doing = true;
 }
        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="fileId"></param>
        /// <param name="savePath">文件保存路径</param>
        public void DownLoadFile(DriveService driveService, string fileId, long fileSize, string savePath)
        {
            if (driveService == null)
            {
                return;
            }
            var request = driveService.Files.Get(fileId);
            var stream  = new FileStream(savePath, FileMode.Create);

            // Add a handler which will be notified on progress changes.
            // It will notify on each chunk download and when the
            // download is completed or failed.
            try
            {
                request.MediaDownloader.ChunkSize        = 8192;//配置chunk大小
                request.MediaDownloader.ProgressChanged +=
                    (IDownloadProgress progress) =>
                {
                    switch (progress.Status)
                    {
                    case DownloadStatus.Downloading:
                    {
                        Console.WriteLine(progress.BytesDownloaded);
                        ProgressEvent?.Invoke(progress.BytesDownloaded, fileSize);
                        break;
                    }

                    case DownloadStatus.Completed:
                    {
                        Console.WriteLine("Download complete.");
                        FinishedEvent?.Invoke();
                        break;
                    }

                    case DownloadStatus.Failed:
                    {
                        Console.WriteLine("Download failed.");
                        FailedEvent?.Invoke();
                        break;
                    }
                    }
                };
                request.Download(stream);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.ToString());
            }
            finally
            {
                if (stream != null)
                {
                    stream.Close();
                    stream = null;
                    GC.Collect();
                }
            }
        }
 public void Finish(bool wait, int timeout = -1)
 {
     _startedRunning.Wait(timeout);
     if (_blockingQueueSourceAdapter == null)
     {
         throw new InvalidOperationException("Can't call BlockingQueueDataPipeline.Finish(). Pump is not running");
     }
     _blockingQueueSourceAdapter.Finish();
     if (wait)
     {
         FinishedEvent.WaitOne(timeout);
     }
 }
Exemple #13
0
        private FinishedEvent ReadFinishedEvent()
        {
            FinishedEvent finishedEvent = new FinishedEvent();
            string        headerLine;
            bool          expectedScriptRead = false;

            do
            {
                headerLine = ReadLine();
                Match headerMatch = Regex.Match(headerLine, HEADER_PATTERN);
                if (headerMatch.Success)
                {
                    string headerName  = headerMatch.Groups[1].Value;
                    string headerValue = headerMatch.Groups[2].Value;
                    switch (headerName)
                    {
                    case "name":
                        finishedEvent.Name = headerValue;
                        break;

                    case "content-length":
                        int length = Int32.Parse(headerValue);
                        if (length >= 0)
                        {
                            char[] payload = ReadBlock(length);
                            if (!expectedScriptRead)
                            {
                                expectedScriptRead           = true;
                                finishedEvent.ExpectedScript = new String(payload);

                                // end of expected script
                                ReadLine();
                            }
                            else
                            {
                                finishedEvent.ObservedScript = new String(payload);
                            }
                        }
                        break;

                    default:
                        throw new InvalidOperationException(String.Format("Invalid header - '{0}:{1}' while parsing ERROR event", headerName, headerValue));
                    }
                }
            } while (headerLine != String.Empty);



            return(finishedEvent);
        }
        public virtual void Shutdown()
        {
            LogManager.GetCurrentClassLogger().Info("Shutting Down {0}", InputType);

            FinishedEvent.WaitOne();
            try
            {
                if (File.Exists(CheckpointFileName))
                {
                    File.Delete(CheckpointFileName);
                }
            }
            catch (Exception ex)
            {
                LogManager.GetCurrentClassLogger().Error(ex);
            }
        }
Exemple #15
0
        public void OnTimer_ForEnd_ShouldRespectTimeout(int timeDifference)
        {
            Beacon martijnBeacon = new Beacon(new byte[] { 0, 0, 0, 0, 0, 1 }, 0);
            Rider  martijn       = new Rider("Martijn", martijnBeacon);

            subject.AddRider(martijn);

            //rider enters start box
            startId.EmitIdEvent(martijn, new DateTime(2000, 1, 1, 1, 1, 1));

            //rider triggers timing gate
            timer.EmitTriggerEvent(100, "Timer", 0, new DateTime(2000, 1, 1, 1, 1, 20));

            //rider triggers id in stop box
            endId.EmitIdEvent(martijn, new DateTime(2000, 1, 1, 1, 2, 20));

            //end timer triggered 11 seconds apart, should not match
            timer.EmitTriggerEvent(500, "Timer", 1, new DateTime(2000, 1, 1, 1, 2, 20 + timeDifference + Math.Sign(timeDifference)));

            //end timer triggered 10 seconds apart, should match
            timer.EmitTriggerEvent(500, "Timer", 1, new DateTime(2000, 1, 1, 1, 2, 20 + timeDifference));

            source.Cancel();
            RaceSummary summary = race.Result;
            var         state   = subject.GetState;

            FinishedEvent finish = summary.Events.Last() as FinishedEvent;

            Assert.AreEqual(20 + timeDifference, finish.TimeEnd.Time.Second);

            //There should be nothing going on in the race at this point
            Assert.AreEqual(0, state.waiting.Count);
            Assert.AreEqual(0, state.unmatchedIds.Count);
            Assert.AreEqual(0, state.onTrack.Count);

            //depending on whether the timeDifference is negative or positive the unmatched id should be cleared
            //on positive timeDifference the unmatched time is not old enough to be cleared
            if (timeDifference > 0)
            {
                Assert.AreEqual(1, state.unmatchedTimes.Count);
            }
            else
            {
                Assert.AreEqual(0, state.unmatchedTimes.Count);
            }
        }
Exemple #16
0
        public void CompareTo_ShouldConsiderPernalties()
        {
            Beacon martijnBeacon = new Beacon(new byte[] { 0, 0, 0, 0, 0, 1 }, 2);
            Rider  martijn       = new Rider("Martijn", martijnBeacon);

            //make a fast lap with loads of penalties
            IdEvent     startId     = new IdEvent(DateTime.Now, martijn, "StartId", Direction.Enter);
            TimingEvent startTiming = new TimingEvent(DateTime.Now, martijn, 100, 0);
            IdEvent     endId       = new IdEvent(DateTime.Now, martijn, "EndId", Direction.Enter);
            TimingEvent endTiming   = new TimingEvent(DateTime.Now, martijn, 200, 1);

            FinishedEvent fastFinish = new FinishedEvent(startId, startTiming, endTiming, endId);

            Lap fast = new Lap(fastFinish);

            fast.AddPenalties(new List <PenaltyEvent>
            {
                new PenaltyEvent(DateTime.Now, martijn, "reason", 1, "staff"),
                new PenaltyEvent(DateTime.Now, martijn, "reason", 2, "staff")
            });

            //make a slower lap without penalties
            IdEvent     slowStartId     = new IdEvent(DateTime.Now, martijn, "StartId", Direction.Enter);
            TimingEvent slowStartTiming = new TimingEvent(DateTime.Now, martijn, 100, 0);
            IdEvent     slowEndId       = new IdEvent(DateTime.Now, martijn, "EndId", Direction.Enter);
            TimingEvent slowEndTiming   = new TimingEvent(DateTime.Now, martijn, 300, 1);

            FinishedEvent slowFinish = new FinishedEvent(slowStartId, slowStartTiming, slowEndTiming, slowEndId);

            Lap slow = new Lap(slowFinish);

            //without penalties the lap time should dictate the ordering
            Assert.AreEqual(1, slow.CompareTo(fast, false));
            Assert.AreEqual(-1, fast.CompareTo(slow, false));

            //with penalties the slower lap is actually faster
            Assert.AreEqual(-1, slow.CompareTo(fast, true));
            Assert.AreEqual(1, fast.CompareTo(slow, true));

            //the default should take penalties into account
            Assert.AreEqual(-1, slow.CompareTo(fast));
            Assert.AreEqual(1, fast.CompareTo(slow));
        }
Exemple #17
0
        /// <summary>
        /// 检查是否全部完成
        /// </summary>
        /// <param name="pan"></param>
        private void VertifyFinished()
        {
            foreach (PanKey p in pans)
            {
                if (!p.CheckLocation(Columns))
                {
                    return;
                }
            }

            timer.Stop();

            //恢复空白格子模板
            Binding binding = new Binding("Template");

            binding.Source = pans[1];
            panNull.SetBinding(PanKey.TemplateProperty, binding);

            FinishedEvent.Invoke(Time.ToString());
        }
Exemple #18
0
    protected void OnAssigned(AssignableObject asg)
    {
        ++_assigned;

        if (Questions.Length != 0 && _assigned < 4)
        {
            int _a_tmp = _assigned - 1;

            Questions[_a_tmp].SetActive(false);
            Questions[_assigned].SetActive(true);

            _assignables = GetComponentsInChildren <AssignableObject>();
        }

        //if (_assigned == _assignableCount)
        if (_assigned == 4)
        {
            FinishedEvent.Invoke(this);
        }
    }
Exemple #19
0
        public void CompareTo_ShouldConsiderDSQOnFinshedLaps()
        {
            Beacon martijnBeacon = new Beacon(new byte[] { 0, 0, 0, 0, 0, 1 }, 2);
            Rider  martijn       = new Rider("Martijn", martijnBeacon);

            //make a fast lap
            IdEvent     startId     = new IdEvent(DateTime.Now, martijn, "StartId", Direction.Enter);
            TimingEvent startTiming = new TimingEvent(DateTime.Now, martijn, 100, 0);
            IdEvent     endId       = new IdEvent(DateTime.Now, martijn, "EndId", Direction.Enter);
            TimingEvent endTiming   = new TimingEvent(DateTime.Now, martijn, 200, 1);

            FinishedEvent fastFinish = new FinishedEvent(startId, startTiming, endTiming, endId);

            Lap fast = new Lap(fastFinish);

            //make a slower lap without penalties
            IdEvent     slowStartId     = new IdEvent(DateTime.Now, martijn, "StartId", Direction.Enter);
            TimingEvent slowStartTiming = new TimingEvent(DateTime.Now, martijn, 100, 0);
            IdEvent     slowEndId       = new IdEvent(DateTime.Now, martijn, "EndId", Direction.Enter);
            TimingEvent slowEndTiming   = new TimingEvent(DateTime.Now, martijn, 300, 1);

            FinishedEvent slowFinish = new FinishedEvent(slowStartId, slowStartTiming, slowEndTiming, slowEndId);

            Lap slow = new Lap(slowFinish);

            //when both are not DSQ the lap time should decide the order
            Assert.AreEqual(1, slow.CompareTo(fast));
            Assert.AreEqual(-1, fast.CompareTo(slow));

            fast.SetDsq(new DSQEvent(DateTime.Now, martijn, "staff", "reason"));

            //the faster lap has a DSQ, so it should be considered slower
            Assert.AreEqual(-1, slow.CompareTo(fast));
            Assert.AreEqual(1, fast.CompareTo(slow));

            slow.SetDsq(new DSQEvent(DateTime.Now, martijn, "staff", "reason"));

            //both are now DSQ lap time should decide order again
            Assert.AreEqual(1, slow.CompareTo(fast));
            Assert.AreEqual(-1, fast.CompareTo(slow));
        }
Exemple #20
0
        public void OnEndId_WithAccidentalEndId_ShouldMatch()
        {
            Beacon martijnBeacon = new Beacon(new byte[] { 0, 0, 0, 0, 0, 1 }, 0);
            Rider  martijn       = new Rider("Martijn", martijnBeacon);

            subject.AddRider(martijn);

            //rider enters start box
            startId.EmitIdEvent(martijn, new DateTime(2000, 1, 1, 1, 1, 1));

            //rider triggers timing gate
            timer.EmitTriggerEvent(100, "Timer", 0, new DateTime(2000, 1, 1, 1, 1, 1));

            //rider triggers id in stop box accidentally (maybe the track was constructed to pass too close to stop box
            endId.EmitIdEvent(martijn, new DateTime(2000, 1, 1, 1, 2, 20));

            //rider triggers id in stop box for real five seconds later
            endId.EmitIdEvent(martijn, new DateTime(2000, 1, 1, 1, 2, 25));

            //end timer triggered 1 second later
            timer.EmitTriggerEvent(500, "Timer", 1, new DateTime(2000, 1, 1, 1, 2, 26));

            source.Cancel();
            RaceSummary summary = race.Result;
            var         state   = subject.GetState;

            FinishedEvent finish = summary.Events.Last() as FinishedEvent;

            Assert.AreEqual(25, finish.Left.Time.Second);

            //There should be nothing going on in the race at this point, except for the lingering end id event
            Assert.AreEqual(0, state.waiting.Count);
            Assert.AreEqual(0, state.onTrack.Count);
            Assert.AreEqual(0, state.unmatchedTimes.Count);

            Assert.AreEqual(1, state.unmatchedIds.Count);
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="client"></param>
        /// <param name="dropboxSourcePath">folder + "/" + file,这个/一定不能省略</param>
        /// <param name="savePath"></param>
        /// <param name="fileSize"></param>
        /// <returns></returns>
        public async Task <bool> DownLoadFile(DropboxClient client, string folder, string fileName, string savePath, long fileSize)
        {
            string dropboxSourcePath = "";

            if (string.IsNullOrEmpty(folder))
            {
                dropboxSourcePath = "/" + fileName;
            }
            else
            {
                dropboxSourcePath = folder + "/" + fileName;
            }
            using (var response = await client.Files.DownloadAsync(dropboxSourcePath))
            {
                ulong     aFileSize   = response.Response.Size;
                const int aBufferSize = 4 * 1024 * 1024;

                var aBuffer = new byte[aBufferSize];
                using (var aDropboxContentStream = await response.GetContentAsStreamAsync())
                {
                    int aLengthOfBytesRead = 0;
                    using (FileStream fs = new FileStream(savePath, FileMode.Create))
                    {
                        long currentSize = 0;
                        while ((aLengthOfBytesRead = aDropboxContentStream.Read(aBuffer, 0, aBufferSize)) > 0)
                        {
                            fs.Write(aBuffer, 0, aLengthOfBytesRead);
                            currentSize += aLengthOfBytesRead;
                            ProgressEvent?.Invoke(currentSize, fileSize);
                        }
                    }
                }
                FinishedEvent?.Invoke();
            }
            return(true);
        }
 public void Finished()
 {
     FinishedEvent.Set();
     LogManager.GetCurrentClassLogger().Info("Finished Shutdown {0}", InputType);
 }
        /// <summary>
        ///
        /// </summary>
        /// <param name="graphClient"></param>
        /// <param name="fileId"></param>
        /// <param name="savePath">文件保存路径</param>
        /// <param name="fileSize"></param>
        /// <returns></returns>
        // Downloads the content of an existing file.
        public async Task <bool> DownLoadFile(GraphServiceClient graphClient, string fileId, string savePath, long fileSize)
        {
            const long DefaultChunkSize = 50 * 1024; // 50 KB, TODO: change chunk size to make it realistic for a large file.
            long       ChunkSize        = DefaultChunkSize;
            long       offset           = 0;         // cursor location for updating the Range header.

            byte[] bytesInStream;                    // bytes in range returned by chunk download.

            // We'll use the file metadata to determine size and the name of the downloaded file
            // and to get the download URL.
            var driveItemInfo = await graphClient.Me.Drive.Items[fileId].Request().GetAsync();

            // Get the download URL. This URL is preauthenticated and has a short TTL.
            object downloadUrl;

            driveItemInfo.AdditionalData.TryGetValue("@microsoft.graph.downloadUrl", out downloadUrl);

            // Get the number of bytes to download. calculate the number of chunks and determine
            // the last chunk size.
            long size           = (long)driveItemInfo.Size;
            int  numberOfChunks = Convert.ToInt32(size / DefaultChunkSize);
            // We are incrementing the offset cursor after writing the response stream to a file after each chunk.
            // Subtracting one since the size is 1 based, and the range is 0 base. There should be a better way to do
            // this but I haven't spent the time on that.
            int lastChunkSize = Convert.ToInt32(size % DefaultChunkSize) - numberOfChunks - 1;

            if (lastChunkSize > 0)
            {
                numberOfChunks++;
            }
            long currentSize = 0;

            // Create a file stream to contain the downloaded file.
            using (FileStream fileStream = new FileStream(savePath, FileMode.Create))
            {
                for (int i = 0; i < numberOfChunks; i++)
                {
                    // Setup the last chunk to request. This will be called at the end of this loop.
                    if (i == numberOfChunks - 1)
                    {
                        ChunkSize = lastChunkSize;
                    }

                    // Create the request message with the download URL and Range header.
                    HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Get, (string)downloadUrl);
                    req.Headers.Range = new System.Net.Http.Headers.RangeHeaderValue(offset, ChunkSize + offset);

                    // We can use the the client library to send this although it does add an authentication cost.
                    // HttpResponseMessage response = await graphClient.HttpProvider.SendAsync(req);
                    // Since the download URL is preauthenticated, and we aren't deserializing objects,
                    // we'd be better to make the request with HttpClient.
                    var client = new HttpClient();
                    HttpResponseMessage response = await client.SendAsync(req);

                    using (Stream responseStream = await response.Content.ReadAsStreamAsync())
                    {
                        bytesInStream = new byte[ChunkSize];
                        int read;
                        do
                        {
                            read = responseStream.Read(bytesInStream, 0, (int)bytesInStream.Length);
                            if (read > 0)
                            {
                                fileStream.Write(bytesInStream, 0, read);
                                currentSize += read;
                                ProgressEvent?.Invoke(currentSize, fileSize);
                            }
                        }while (read > 0);
                    }
                    offset += ChunkSize + 1; // Move the offset cursor to the next chunk.
                }
            }
            FinishedEvent?.Invoke();
            return(true);
        }
        private void AddFinishedEventsForCompetition(Competition competition)
        {
            var tournamentMatches =
                Client.GetStringAsync(
                    $"{_tournamentMatchListLink}{BuildUrlFromName(competition.Name)}/").Result;

            var doc = new HtmlDocument();

            doc.LoadHtml(tournamentMatches);

            var table = doc.DocumentNode.SelectSingleNode("//table[contains(@class,'table_list')]");

            var columns = table.SelectNodes(".//tr").Where(x => !x.InnerHtml.Contains("> - <")).Skip(1).ToList();

            for (int i = 0; i < columns.Count; i++)
            {
                try
                {
                    var currentGame = columns[i].SelectNodes(".//td");

                    var blueSideTeam = currentGame[1].InnerHtml;
                    var redSideTeam  = currentGame[3].InnerHtml;

                    var blueSideTeamFromDb = _dbContext.Teams.FirstOrDefault(team => team.Competition == competition && team.Name == blueSideTeam);
                    var redSideTeamFromDb  = _dbContext.Teams.FirstOrDefault(team => team.Competition == competition && team.Name == redSideTeam);

                    var score             = currentGame[2].InnerHtml.Split("-");
                    var blueSideTeamScore = int.Parse(score[0].Trim());
                    var redSideTeamScore  = int.Parse(score[1].Trim());
                    var date = DateTime.Parse(currentGame[6].InnerHtml);

                    FinishedEvent finishedEvent = null;

                    if (blueSideTeamFromDb != null && redSideTeamFromDb != null)
                    {
                        finishedEvent = _dbContext
                                        .FinishedEvents
                                        .FirstOrDefault(t => t.HomeTeamId == blueSideTeamFromDb.Id &&
                                                        t.AwayTeamId == redSideTeamFromDb.Id &&
                                                        t.GameDate == date);


                        if (finishedEvent == null)
                        {
                            finishedEvent = new FinishedEvent
                            {
                                HomeTeamId  = blueSideTeamFromDb.Id,
                                AwayTeamId  = redSideTeamFromDb.Id,
                                Competition = competition,
                                GameDate    = date,
                                Score1      = blueSideTeamScore,
                                Score2      = redSideTeamScore,
                            };

                            _dbContext.FinishedEvents.Add(finishedEvent);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Log.Logger.Error($"Error parsing Finished Event from Competition {competition.Name}({competition.Id})");
                }
            }
        }
        public async Task <bool> UpLoadFile(GraphServiceClient graphClient, string sourcePath, string fileID = null)
        {
            try
            {
                if (!System.IO.File.Exists(sourcePath))
                {
                    return(false);
                }
                System.IO.FileInfo info = new System.IO.FileInfo(sourcePath);
                long   fileSize         = info.Length;
                string fileName         = System.IO.Path.GetFileName(sourcePath);
                long   currentSize      = 0;
                using (FileStream fileStream = new FileStream(sourcePath, FileMode.Open))
                {
                    // Create the upload session. The access token is no longer required as you have session established for the upload.
                    // POST /v1.0/drive/root:/UploadLargeFile.bmp:/microsoft.graph.createUploadSession
                    UploadSession uploadSession;
                    if (string.IsNullOrEmpty(fileID))
                    {
                        uploadSession = await graphClient.Me.Drive.Root.ItemWithPath(fileName).CreateUploadSession().Request().PostAsync();
                    }
                    else
                    {
                        uploadSession = await graphClient.Me.Drive.Items[fileID].ItemWithPath(fileName).CreateUploadSession().Request().PostAsync();
                    }

                    var maxChunkSize = 320 * 1024; // 320 KB - Change this to your chunk size. 5MB is the default.
                    var provider     = new ChunkedUploadProvider(uploadSession, graphClient, fileStream, maxChunkSize);

                    // Setup the chunk request necessities
                    var       chunkRequests     = provider.GetUploadChunkRequests();
                    var       readBuffer        = new byte[maxChunkSize];
                    var       trackedExceptions = new List <Exception>();
                    DriveItem itemResult        = null;

                    //upload the chunks
                    foreach (var request in chunkRequests)
                    {
                        // Do your updates here: update progress bar, etc.
                        // ...
                        // Send chunk request
                        var result = await provider.GetChunkRequestResponseAsync(request, readBuffer, trackedExceptions);

                        //这里时最终的一个结果
                        if (result.UploadSucceeded)
                        {
                            itemResult  = result.ItemResponse;
                            currentSize = (long)result.ItemResponse.Size;
                        }
                        else
                        {
                            currentSize += maxChunkSize;
                        }
                        ProgressEvent?.Invoke(currentSize, fileSize);
                    }

                    // Check that upload succeeded
                    if (itemResult == null)
                    {
                        // Retry the upload
                        // ...
                        FailedEvent?.Invoke();
                    }
                    else
                    {
                        FinishedEvent?.Invoke();
                    }

                    return(true);
                }
            }

            catch (ServiceException e)
            {
                System.Diagnostics.Debug.WriteLine("We could not upload the file: " + e.Error.Message);
                FailedEvent?.Invoke();
                return(false);
            }
        }
Exemple #26
0
 static void OnFinished(FinishedEvent _)
 {
     dispatchFinished.Set();
 }
Exemple #27
0
        /// <summary>
        /// 分块下载文件
        /// </summary>
        /// <param name="url">下载的url</param>
        /// <param name="savePath">保存路径</param>
        /// <param name="fileSize">文件的大小</param>
        public async void Download(string url, string savePath, long fileSize = 0)
        {
            //获取文件大小
            if (fileSize == 0)
            {
                fileSize = Size(url);
            }
            const long DefaultChunkSize = 50 * 1024; // 50 KB, TODO: change chunk size to make it realistic for a large file.
            long       ChunkSize        = DefaultChunkSize;
            long       offset           = 0;         // cursor location for updating the Range header.

            byte[] bytesInStream;                    // bytes in range returned by chunk download.
            int    numberOfChunks = Convert.ToInt32(fileSize / DefaultChunkSize);
            // We are incrementing the offset cursor after writing the response stream to a file after each chunk.
            // Subtracting one since the size is 1 based, and the range is 0 base. There should be a better way to do
            // this but I haven't spent the time on that.
            int lastChunkSize = Convert.ToInt32(fileSize % DefaultChunkSize) - numberOfChunks - 1;

            if (lastChunkSize > 0)
            {
                numberOfChunks++;
            }
            long currentSize = 0;

            // Create a file stream to contain the downloaded file.
            using (FileStream fileStream = new FileStream(savePath, FileMode.Create))
            {
                for (int i = 0; i < numberOfChunks; i++)
                {
                    // Setup the last chunk to request. This will be called at the end of this loop.
                    if (i == numberOfChunks - 1)
                    {
                        ChunkSize = lastChunkSize;
                    }

                    // Create the request message with the download URL and Range header.
                    HttpRequestMessage req = new HttpRequestMessage(System.Net.Http.HttpMethod.Get, url);
                    req.Headers.Range = new System.Net.Http.Headers.RangeHeaderValue(offset, ChunkSize + offset);
                    var client = new HttpClient();
                    HttpResponseMessage response = await client.SendAsync(req);

                    using (Stream responseStream = await response.Content.ReadAsStreamAsync())
                    {
                        bytesInStream = new byte[ChunkSize];
                        int read;
                        do
                        {
                            read = responseStream.Read(bytesInStream, 0, (int)bytesInStream.Length);
                            if (read > 0)
                            {
                                fileStream.Write(bytesInStream, 0, read);
                                currentSize += read;
                                ProgressEvent?.Invoke(currentSize, fileSize);
                                Debug.WriteLine(i + " : " + currentSize + " : " + fileSize);
                            }
                        }while (read > 0);
                    }
                    offset += ChunkSize + 1; // Move the offset cursor to the next chunk.
                }
            }
            FinishedEvent?.Invoke();
        }
Exemple #28
0
 private void DownloadComplete(object sender, DownloadDataCompletedEventArgs args)
 {
     FinishedEvent?.Invoke(args.Result);
 }
Exemple #29
0
 public void OnFinished(FinishedEvent finished)
 {
     this.finished = finished;
     CPP.Add("QObject::connect($q, &QDialog::finished, [=] (int result) {this->SlotFinished(result);});");
 }
Exemple #30
0
 public void Finished()
 {
     LogManager.GetCurrentClassLogger().Info("{0}: Signalling Event Shutdown {1}", Thread.CurrentThread.ManagedThreadId, InputType);
     FinishedEvent.Set();
     LogManager.GetCurrentClassLogger().Info("{0}: Finished signalling Shutdown {1}", Thread.CurrentThread.ManagedThreadId, InputType);
 }