Ejemplo n.º 1
0
    public CustomSocket(OnData onData, OnStatus onStatus)
    {
        this._onData   = onData;
        this._onStatus = onStatus;

        this._status = SocketStatus.UNDEFINE;
    }
Ejemplo n.º 2
0
 public WebsocketJsonClient(Uri socketUrl, IWebsocketLogger logger = null, ICredentials credentials = null, int bufferSize = 1024 * 5, Encoding encoding = null, IWebProxy proxy = null)
 {
     _socketUrl    = socketUrl;
     _logger       = logger;
     _socketBuffer = new byte[bufferSize];
     _encoding     = encoding ?? Encoding.UTF8;
     if (credentials != null)
     {
         _socket.Options.Credentials = credentials;
     }
     if (proxy != null)
     {
         _socket.Options.Proxy = proxy;
     }
     if (_socket.Options.Credentials == null && !string.IsNullOrEmpty(_socketUrl.UserInfo) && _socketUrl.UserInfo.Contains(":"))
     {
         var split = _socketUrl.UserInfo.Split(':');
         if (split.Length == 2)
         {
             _socket.Options.Credentials = new NetworkCredential(Uri.UnescapeDataString(split[0]), Uri.UnescapeDataString(split[1]));
         }
     }
     _jsonProcessor           = new JsonProcessor(_logger);
     _jsonProcessor.OnEot    += () => OnEot?.Invoke();
     _jsonProcessor.OnEdges  += (e) => OnEdges?.Invoke(e);
     _jsonProcessor.OnNode   += (n) => OnNode?.Invoke(n);
     _jsonProcessor.OnStatus += (s) => OnStatus?.Invoke(s);
 }
Ejemplo n.º 3
0
        private void Update()
        {
            if (IsRunning != (Runner != null))
            {
                IsRunning = Runner != null;
                OnRunningChanged?.Invoke(IsRunning);
                if (IsRunning)
                {
                    OnInit?.Invoke();
                }
            }
            if (Runner != null)
            {
                updateWatch.Start();
                var now     = Time.time;
                var extraMs = Mathf.Max(0, (int)((next - now) * 1000f) - 1);
                Runner.Idle(extraMs);
                Thread.Sleep(extraMs);

                if (now >= next)
                {
                    OnPreRunFrame();
                    Runner.RunFrame();
                    next = now + 1f / 60f;
                    OnStateChanged?.Invoke();
                }
                updateWatch.Stop();

                string status = Runner.GetStatus(updateWatch);
                OnStatus?.Invoke(status);
                OnChecksum?.Invoke(RenderChecksum(Runner.GameInfo.periodic) + RenderChecksum(Runner.GameInfo.now));
            }
        }
Ejemplo n.º 4
0
        private void Update()
        {
            if (IsRunning != (Runner != null))
            {
                IsRunning = Runner != null;
                OnRunningChanged?.Invoke(IsRunning);
                if (IsRunning)
                {
                    OnInit?.Invoke();
                    start = next = Utils.TimeGetTime();
                }
            }
            if (IsRunning)
            {
                updateWatch.Start();
                if (useNewUpdate)
                {
                    NewUpdate();
                }
                else
                {
                    OriginalUpdate();
                }
                updateWatch.Stop();

                OnStatus?.Invoke(Runner.GetStatus(updateWatch));
            }
        }
Ejemplo n.º 5
0
        private async Task <IReadOnlyList <(Composer composer, IComposerContext context, Step step)> > ExecuteUpAsync(
            Composition composition)
        {
            var executedSteps = new List <(Composer composer, IComposerContext context, Step step)>(composition.Count);

            foreach (Step step in composition)
            {
                OnStatus.Report(StepStatus.Up,
                                "Executing step up '{StepName}'.",
                                new { StepName = step.Name });

                var composer = (Composer)Activator.CreateInstance(step.ComposerType,
                                                                  new ComposerProperties(step));

                try
                {
                    var context = await composer.UpAsync().ConfigureAwait(false);

                    executedSteps.Add((composer, context, step));
                }
                catch (Exception ex)
                {
                    OnStatus.Report(StepStatus.Error,
                                    "Error occurred in step up '{StepName}' - '{ErrorMessage}'.",
                                    new { StepName = step.Name, ErrorMessage = ex.Message });
                    break;
                }
            }

            return(executedSteps);
        }
Ejemplo n.º 6
0
        public override void Deserialize(GenericReader reader)
        {
            base.Deserialize(reader);

            int version = reader.ReadEncodedInt();

            m_Mate = reader.ReadItem() as Communicator;

            m_On = OnStatus.Off;
        }
Ejemplo n.º 7
0
        private void SetStatus(string format, params object[] args)
        {
            var message    = string.Format(format, args);
            var diagnostic = new ParserDiagnostic();

            diagnostic.Message    = message;
            diagnostic.LineNumber = -1;

            OnStatus.Raise(this_, message);
            OnParserDiagnostic.Raise(this_, diagnostic);
        }
Ejemplo n.º 8
0
        private void HandleOnStatus(object sender, GenericArgs <StreamStatus> e)
        {
            var session = (StreamSession <StreamResponse>)sender;

            OnStatus?.Invoke(this, new StatusArgs(session.Kind, e.Data));

            if (e.Data == StreamStatus.WebError)
            {
                OnWebError?.Invoke(this, new WebErrorArgs(session.Kind,
                                                          session.ErrorStatus.Value, session.ErrorMessage));
            }
        }
Ejemplo n.º 9
0
        private void OnStatusChanged(OsuStatus last_status, OsuStatus status)
        {
            //clean
            prev_combo = combo_level = 0;

            if (last_status == OsuStatus.Rank && (status == OsuStatus.SelectSong || status == OsuStatus.MatchSetup))
            {
                OnStatus?.Invoke(true);
            }

            if (status == OsuStatus.Rank && (last_status == OsuStatus.SelectSong || last_status == OsuStatus.MatchSetup))
            {
                OnStatus?.Invoke(false);
            }
        }
Ejemplo n.º 10
0
        public override void OnDoubleClick(Mobile from)
        {
            string status = "";

            switch (m_On)
            {
            case OnStatus.Off: m_On = OnStatus.ReceiveOnly; status = "in Receive Only mode"; break;

            case OnStatus.ReceiveOnly: m_On = OnStatus.SendOnly; status = "in Send Only mode"; break;

            case OnStatus.SendOnly: m_On = OnStatus.TwoWay; status = "in Two-Way mode"; break;

            case OnStatus.TwoWay: m_On = OnStatus.Off; status = "Off"; break;
            }
            from.SendMessage("Communicator is now {0}.", status);
            InvalidateProperties();
        }
Ejemplo n.º 11
0
        public void onSessionStatusChanged(O2GSessionStatusCode status)
        {
            OnStatus?.Invoke(this, new StatusArgs((Status)(int)status));

            switch (status)
            {
            case O2GSessionStatusCode.Connected:
                IsConnected = true;
                syncSessionEvent.Set();
                break;

            case O2GSessionStatusCode.Disconnected:
                IsConnected = false;
                syncSessionEvent.Set();
                break;
            }
        }
Ejemplo n.º 12
0
        public void Parse(TextReader txt)
        {
            string line = null;

            while ((line = txt.ReadLine()) != null)
            {
                Thread.Sleep(100);

                if (!line.StartsWith("[{") || !line.EndsWith("}]"))
                {
                    OnBadLine?.Invoke(line);
                    continue;
                }

                if (line.StartsWith(@"[{""ev"":""status"",""status"":"))
                {
                    OnStatus?.Invoke(line);
                    continue;
                }

                var arrayWithoutSquareBrackets = line.AsSpan(1, line.Length - 1 - 1); // Trim '[' & ']'

                var array = arrayWithoutSquareBrackets;
                do
                {
                    var ixElementStart  = array.IndexOf('{') + 1;
                    var ixElementEnd    = array.IndexOf('}');
                    var lengthOfElement = ixElementEnd - ixElementStart;

                    var element = array.Slice(ixElementStart, lengthOfElement);

                    Process(element);

                    if (ixElementEnd == array.Length - 1)
                    {
                        break; // no elements remaining
                    }
                    else // Remove element from head of array
                    {
                        array = array.Slice(ixElementEnd + "},".Length);
                    }
                } while (array.Length > 0); // TODO
            }
        }
Ejemplo n.º 13
0
        public void onSessionStatusChanged(O2GSessionStatusCode status)
        {
            OnStatus?.Invoke(this, new GenericArgs <O2GSessionStatusCode>(status));

            switch (status)
            {
            case O2GSessionStatusCode.TradingSessionRequested:
                session.setTradingSession(sessionId, "");
                break;

            case O2GSessionStatusCode.Connected:
                Connected = true;
                syncSessionEvent.Set();
                break;

            case O2GSessionStatusCode.Disconnected:
                Connected = false;
                syncSessionEvent.Set();
                break;
            }
        }
 private void ReportStatus(MonteCarloTreeSearchNode rootNode)
 {
     // Update Status
     if (statusUpdate.ElapsedMilliseconds > millisecondsBetweenUpdates && OnStatus != null)
     {
         EngineStatus status = new EngineStatus();
         foreach (var child in rootNode.Children)
         {
             double eval = Math.Round((child.Visits > 0 ? 200.0 * child.Wins / child.Visits : 0) - 100.0, 2);
             string pv   = "";
             var    c    = child;
             while (c != null && c.Move >= 0 && c.Move <= 80)
             {
                 pv += /*(c.LastToMove == Player.One ? "b " : "o ") +*/ Constants.TileNames[c.Move] + " (" + c.Wins + "/" + c.Visits + ")   ";
                 c   = c.Children?.OrderBy(x => x.Visits)?.ThenBy(x => x.Wins)?.LastOrDefault();
             }
             status.Add(child?.Move ?? 80, eval, pv, child.Visits);
         }
         status.Sort();
         OnStatus?.Invoke(this, status);
         statusUpdate = Stopwatch.StartNew();
     }
 }
Ejemplo n.º 15
0
        public void ProcessMessage(string message)
        {
            if (message is null || message.Length < 3 || message[0] != '!')
            {
                message ??= "<null>";
                if (message.StartsWith("Error", StringComparison.InvariantCultureIgnoreCase))
                {
                    _logger?.LogError(message);
                }
                else if (message.StartsWith("Warn", StringComparison.InvariantCultureIgnoreCase))
                {
                    _logger?.LogWarn(message);
                }
                else
                {
                    _logger?.LogInfo(message);
                }
                return;
            }
            message = message.TrimStart('!');
            try {
                var responseBase = Deserialize <CrawlerResponseBase>(message);
                switch (responseBase.Type)
                {
                case "eot": OnEot?.Invoke(); break;

                case "status": OnStatus?.Invoke(Deserialize <CrawlerResponseStatus>(message)); break;

                case "edges": OnEdges?.Invoke(Deserialize <CrawlerResponseEdges>(message)); break;

                case "node": OnNode?.Invoke(Deserialize <CrawlerResponseNode>(message)); break;

                default: _logger?.LogWarn($"Unknown Message Type `{responseBase.Type ?? "<null>"}`"); break;
                }
            }
            catch (JsonException ex) { _logger?.LogWarn($"invalid json: {message}", ex); }
        }
Ejemplo n.º 16
0
        private void ProcessElement(ReadOnlySpan <char> element, out int processedElementLength)
        {
            if (element.ToString().Contains("},{"))
            {
                Debugger.Break();
            }

            if (element[1] == 'e' && element[2] == 'v' &&
                element[0] == '"' && element[3] == '"')
            {
                switch (element[6])
                {
                case 'Q':
                    Quote q = ProcessQuote(element, out processedElementLength);
                    OnQuote?.Invoke(q);
                    return;

                case 'T':
                    Trade t = ProcessTrade(element, out processedElementLength);
                    OnTrade?.Invoke(t);
                    return;

                case 's':
                    string status = "status";
                    if (element.Slice(6, status.Length).SequenceEqual(status))
                    {
                        OnStatus?.Invoke(element.ToString());
                        processedElementLength = element.IndexOf('}');
                        return;
                    }
                    break;
                }
            }
            OnUnknown?.Invoke(element.ToString());
            processedElementLength = element.IndexOf('}');
        }
Ejemplo n.º 17
0
		public NSUrlDownloadDelegate (EventHandler<NSUrlEventArgs> downloadCompleted, OnStatus progress)
		{
			_downloadCompleted = downloadCompleted;
			_progress = progress;
		}
Ejemplo n.º 18
0
 void OnStatusEvent(StatusID Res)
 {
     OnStatus?.Invoke(Res);
 }
Ejemplo n.º 19
0
 public ProgressStream(Stream s, int contentLength, OnStatus onStatus = null)
 {
     this._baseStream    = s;
     this.contentLength  = contentLength > 0?contentLength:predictedLength;
     this.statusCallback = onStatus;
 }
Ejemplo n.º 20
0
        private void DoWork()
        {
            O2GSession      session        = null;
            O2GTableManager tableManager   = null;
            StatusListener  statusListener = null;
            TableListener   tableListener  = null;

            bool canUnsubscribeSessionStatus = false;

            try
            {
                session = O2GTransport.createSession();

                session.useTableManager(O2GTableManagerMode.Yes, null);

                var sessionId = Guid.NewGuid().ToString("N");

                statusListener = new StatusListener(session, sessionId);

                statusListener.OnStatus += (s, e) =>
                {
                    var status = e.Item.ToStatus();

                    OnStatus?.Invoke(this, new GenericArgs <Status>(status));

                    if (status == Status.Disconnected)
                    {
                        OnDisconnected?.Invoke(this, EventArgs.Empty);
                    }
                };

                session.subscribeSessionStatus(statusListener);

                session.login(userName, password, URL, connection.ToString());

                if (statusListener.WaitEvents() && statusListener.Connected)
                {
                    tableListener = new TableListener(testingMode);

                    tableListener.OnOffer += (s, e) =>
                                             OnOffer?.Invoke(this, new GenericArgs <Offer>(e.Item));

                    // improve this plus get rid of response listener
                    tableListener.OnOfferIds += (s, e) =>
                    {
                        //var request = GetSetSubscriptionStatusRequest(session, e.Item);

                        //if (request == null)
                        //    throw new Exception("Cannot create request");

                        //var responseListener = new ResponseListener();

                        //session.subscribeResponse(responseListener);

                        //responseListener.SetRequestID(request.RequestID);

                        //session.sendRequest(request);

                        //if (!responseListener.WaitEvents())
                        //    throw new Exception("Response waiting timeout expired");
                    };

                    tableManager = session.getTableManager();

                    var managerStatus = tableManager.getStatus();

                    // max wait
                    while (managerStatus == O2GTableManagerStatus.TablesLoading)
                    {
                        Thread.Sleep(50);

                        managerStatus = tableManager.getStatus();
                    }

                    if (managerStatus == O2GTableManagerStatus.TablesLoadFailed)
                    {
                        throw new Exception("TableManager refresh failed!");
                    }

                    tableListener.SetSymbols(
                        Enum.GetValues(typeof(Symbol)).Cast <Symbol>().ToList());

                    tableListener.SubscribeEvents(tableManager);

                    O2GOffersTable offers = null;

                    offers = (O2GOffersTable)tableManager.getTable(O2GTableType.Offers);

                    tableListener.HandleOffers(offers);

                    cancelEvent.WaitOne();

                    OnCancelled?.Invoke(this, EventArgs.Empty);
                }
            }
            catch (Exception error)
            {
                OnError?.Invoke(this, new GenericArgs <Exception>(error));
            }
            finally
            {
                Shutdown(session, statusListener, tableListener, tableManager);

                if (canUnsubscribeSessionStatus)
                {
                    session.unsubscribeSessionStatus(statusListener);
                }

                if (session != null)
                {
                    session.Dispose();
                }
            }
        }
Ejemplo n.º 21
0
 public NSUrlUploadDelegate(EventHandler <NSUrlEventArgs> uploadCompleted, OnStatus progress)
 {
     _uploadCompleted = uploadCompleted;
     _progress        = progress;
 }
Ejemplo n.º 22
0
 /// <summary>
 /// Emitir evento de estado
 /// </summary>
 /// <param name="address">Dirección IP</param>
 /// <param name="found">Determina si se ha encontrado la IP</param>
 private void RaiseStatusEvent(IPAddress address, bool found)
 {
     OnStatus?.Invoke(this, new SweepStatus(address, found));
 }
Ejemplo n.º 23
0
        private int MonteCarloTreeSearch(Board rootState)
        {
            var rootNode = new MonteCarloTreeSearchNode(rootState, GetMoves);
            var forceWin = false;

            while (!cancel.Cancelled && !forceWin)
            {
                var node  = rootNode;
                var state = new Board(rootState);

                state.allowHash     = _allowHash;
                state.fastWinSearch = _allowFastWinSearch;

                if (_allowHash)
                {
                    state.winHashes = winHashes;
                }

                simulationCount++;

                // Select
                while (node.Untried.Count == 0 && node.Children.Count > 0)
                {
                    node = node.SelectChild(_ucbFactor);
                    state.MakeMove(node.Move);
                    visitedNodes++;
                }

                // Expand
                if (node.Untried.Count > 0)
                {
                    var move = node.Untried[random.Next(node.Untried.Count)];
                    state.MakeMove(move);
                    node = node.AddChild(state, move);
                    visitedNodes++;
                }

                // Simulate
                while (state.Winner == Player.Empty && state.Turn < VolcanoGame.Settings.TournamentAdjudicateMaxTurns)
                {
                    var moves = state.GetMoves();
                    if (moves.Count == 0)
                    {
                        break;
                    }
                    state.MakeMove(moves[random.Next(moves.Count)]);
                    visitedNodes++;
                }

                // Backpropagate
                while (node != null)
                {
                    node.Update(state.Winner == node.LastToMove ? 1.0 : 0.0);
                    node = node.Parent;
                    visitedNodes++;
                }

                // Cut Short
                if (_allowForcedWins)
                {
                    foreach (var child in rootNode.Children)
                    {
                        // If we have a potential move that has a 100% win rate and it's been visited a lot of times, stop searching
                        if (child.Visits > 500 && child.Wins == child.Visits)
                        {
                            forceWin = true;
                        }
                    }
                }

                // Update Status
                if (statusUpdate.ElapsedMilliseconds > millisecondsBetweenUpdates && OnStatus != null)
                {
                    EngineStatus status = new EngineStatus();
                    foreach (var child in rootNode.Children)
                    {
                        double eval = Math.Round((child.Visits > 0 ? 200.0 * child.Wins / child.Visits : 0) - 100.0, 2);
                        string pv   = "";
                        var    c    = child;
                        while (c != null && c.Move >= 0 && c.Move <= 80)
                        {
                            pv += Constants.TileNames[c.Move] + " (" + c.Wins + "/" + c.Visits + ")   ";
                            c   = c.Children?.OrderBy(x => x.Visits)?.ThenBy(x => x.Wins)?.LastOrDefault();
                        }
                        status.Add(child?.Move ?? 80, eval, pv, child.Visits);
                    }
                    status.Sort();
                    OnStatus?.Invoke(this, status);
                    statusUpdate = Stopwatch.StartNew();
                }
            }

            return(rootNode.Children.OrderBy(x => x.Visits).LastOrDefault().Move);
        }
Ejemplo n.º 24
0
        public void Fetch(Symbol symbol, DateTime date)
        {
            if (!symbol.IsDefinedEnum())
            {
                throw new ArgumentOutOfRangeException(nameof(symbol));
            }

            if (date.Kind != DateTimeKind.Unspecified)
            {
                throw new ArgumentException("\"date.Kind\" must be \"Unspecified\"!");
            }

            var ticks = new SortedDictionary <DateTime, Tick>();

            O2GSession session = null;

            try
            {
                session = O2GTransport.createSession();

                var statusListener = new StatusListener(session);

                statusListener.OnStatus += (s, e) =>
                                           OnStatus?.Invoke(this, new StatusArgs((Status)(int)e.Status));

                statusListener.OnError += (s, e) =>
                                          OnError?.Invoke(this, new ErrorArgs(e.Kind, e.Message));

                session.subscribeSessionStatus(statusListener);

                statusListener.Reset();

                session.login(userName, password, URL, connection);

                if (statusListener.WaitEvents() && statusListener.IsConnected)
                {
                    var canUnsubscribeResponse = false;

                    ResponseListener responseListener = null;

                    try
                    {
                        responseListener = new ResponseListener(session);

                        responseListener.OnRequestFailed += (s, e) =>
                                                            OnError?.Invoke(this, new ErrorArgs(ErrorKind.Session, e.ErrorMessage));

                        //????????????????????
                        responseListener.OnNoTicks += (s, e) =>
                        {
                        };

                        session.subscribeResponse(responseListener);

                        canUnsubscribeResponse = true;

                        GetTicks(ticks, symbol, date, session, responseListener);

                        var tickSet = new TickSet(symbol, date);

                        tickSet.Load(ticks.Values);

                        OnTickSet?.Invoke(this, new TickSetArgs(tickSet));
                    }
                    catch (Exception error)
                    {
                        OnError?.Invoke(this, new ErrorArgs(ErrorKind.Client, error.Message));
                    }
                    finally
                    {
                        statusListener.Reset();

                        session.logout();

                        statusListener.WaitEvents();

                        if (canUnsubscribeResponse)
                        {
                            session.unsubscribeResponse(responseListener);
                        }
                    }
                }

                session.unsubscribeSessionStatus(statusListener);
            }
            catch (TimeoutException error)
            {
                OnError?.Invoke(this, new ErrorArgs(ErrorKind.Timeout, error.Message));
            }
            catch (Exception error)
            {
                OnError?.Invoke(this, new ErrorArgs(ErrorKind.Client, error.Message));
            }
            finally
            {
                if (session != null)
                {
                    session.Dispose();
                }
            }
        }
Ejemplo n.º 25
0
        protected override void MessageHandler(string action, Variant param)
        {
            this.Log().Info("{0},{1}", Id, action);
            switch (action)
            {
            case "play":
                Dispose();
                Name = param[1];
                double start  = param[2] ?? -2000;
                double length = param[3] ?? -1000;
                try
                {
                    _listener = Handler.SubScribeStream(Peer, StreamId, Name, Writer, start, length);
                    _state    = State.Playing;
                }
                catch (Exception ex)
                {
                    Logger.ASSERT("{0}", ex);
                }
                var raw = Writer.WriterRawMessage();
                raw.Write((ushort)0);
                raw.Write(3);
                raw.Write(34);
                Writer.Flush(true);
                break;

            case "closeStream":
                Dispose();
                break;

            case "publish":
                Dispose();
                Name = param[1];
                var type = param[2] ?? "live";
                //if (message.Available)
                //{
                //    type = message.Read<string>();
                //}
                _publisher = Handler.PublishStream(Peer, StreamId, Name, type, Writer);
                if (_publisher != null)
                {
                    _state = State.Publishing;
                }
                break;

            case "receiveAudio":
                if (_listener != null)
                {
                    _listener.ReceiveAudio = param[1];
                }
                break;

            case "receiveVideo":
                if (_listener != null)
                {
                    _listener.ReceiveVideo = param[1];
                }
                break;

            case "onStatus":
                var obj = param[1];
                this.Log().Info(obj["code"]);
                OnStatus?.Invoke(param);
                break;

            default:

                if (_state == State.Publishing)
                {
                    //var streamMessage = Variant.Get();
                    //var pos = message.BaseStream.Position;
                    //streamMessage[Defines.RM_FLEXSTREAMSEND, Defines.RM_FLEXSTREAMSEND_UNKNOWNBYTE] = 0;
                    //streamMessage[Defines.RM_FLEXSTREAMSEND, Defines.RM_FLEXSTREAMSEND_PARAMS] = Variant.Get();
                    //streamMessage[Defines.RM_FLEXSTREAMSEND, Defines.RM_FLEXSTREAMSEND_PARAMS].Add(action);
                    //while (message.Available)
                    //{
                    //    streamMessage[Defines.RM_FLEXSTREAMSEND, Defines.RM_FLEXSTREAMSEND_PARAMS].Add(message.ReadVariant());
                    //}
                    using (var tempms = Utils.Rms.GetStream()) {
                        tempms.WriteByte(0);
                        tempms.WriteByte(AMF0Serializer.AMF0_SHORT_STRING);
                        var buffer = Encoding.UTF8.GetBytes(action);
                        tempms.Write((ushort)buffer.Length);
                        tempms.Write(buffer, 0, buffer.Length);
                        //message.BaseStream.Position = pos;
                        //////////message.BaseStream.CopyTo(tempms);
                        tempms.Position = 0;
                        _publisher.SendStreamMessage(new BufferWithOffset(tempms));
                        //Handler.SendStreamMessage();
                    }
                }
                else
                {
                    base.MessageHandler(action, param);
                }
                break;
            }
        }
Ejemplo n.º 26
0
		public NSUrlUploadDelegate (EventHandler<NSUrlEventArgs> uploadCompleted, OnStatus progress)
		{
			_uploadCompleted = uploadCompleted;
			_progress = progress;
		}
Ejemplo n.º 27
0
        private static void UpdateInternal(string msg)
        {
            LocalRunInfo  localRunInfo  = null;
            UpdateUrlInfo updateUrlInfo = null;

            try
            {
                OnStatus?.Invoke("正在读取本地配置...");
                localRunInfo = GetLocalRunInfo();

                OnStatus?.Invoke("正在验证更新地址...");
                if (string.IsNullOrEmpty(localRunInfo.UpdateUrl))
                {
                    OnNotSpecifyUpdateUrl?.Invoke(localRunInfo); return;
                }

                if ((updateUrlInfo = UpdateUrlInfo.Parse(localRunInfo.UpdateUrl)) == null)
                {
                    OnInvalidUpdateUrl?.Invoke(localRunInfo); return;
                }

                OnStatus?.Invoke("正在读取服务器...");
                var host          = updateUrlInfo.Host;
                var systemId      = updateUrlInfo.SystemId;
                var remoteRunInfo = GetRemoteRunInfo(GetRemoteInfoUrl(host, systemId));

                OnStatus?.Invoke("正在检测差异...");
                var initStart       = (localRunInfo.RunFiles.Count == 0);
                var fileDiffResults = CalcDiff(localRunInfo, remoteRunInfo).ToList();
                var filesToUpdate   = fileDiffResults.Where(f => f.Status == UpdateRunFileStatus.Update || f.Status == UpdateRunFileStatus.Delete).ToList();
                var progress        = 0;
                var total           = filesToUpdate.Count;

                if (total > 0)
                {
                    OnStatus?.Invoke("正在检测运行程序...");
                    if (IsThisAppRunning() ||
                        (!string.IsNullOrEmpty(localRunInfo.AppRunCmd) && IsMainAppRunning(localRunInfo)))
                    {
                        OnMainAppAlreadyRunning?.Invoke(localRunInfo);

                        return;
                    }
                }

                OnStatus?.Invoke("开始更新程序...");
                OnBeginUpdate?.Invoke(localRunInfo);

                var runDir            = Path.GetDirectoryName(Application.ExecutablePath);
                var thisExeName       = Path.GetFileName(Application.ExecutablePath);
                var runBat            = false;
                var runFileResults    = new DicIgnoreCase <string>();
                var failedUpdateFiles = new List <string>();
                var failedDeleteFiles = new List <string>();

                foreach (var file in filesToUpdate)
                {
                    if (Constants.BatFile.Equals(file.Path, StringComparison.OrdinalIgnoreCase))
                    {
                        runBat = true;
                    }

                    if (file.Status == UpdateRunFileStatus.Update)
                    {
                        var url        = GetRunFileUrl(host, systemId, file.Path);
                        var localPath  = Path.Combine(runDir, file.Path);
                        var updateSelf = file.Path.Equals(thisExeName, StringComparison.OrdinalIgnoreCase); // 自更新

                        OnProcessFile?.Invoke("正在安装文件:" + localPath);
                        var success = DownloadRunFile(url, localPath, possibllyInUse: updateSelf);

                        if (!success)
                        {
                            failedUpdateFiles.Add(file.Path);

                            // 对于更新失败的文件(非新增),新的配置文件应该仍包含更新前的文件标识
                            if (!string.IsNullOrEmpty(file.OldTag))
                            {
                                runFileResults.Add(file.Path, file.OldTag);
                            }
                        }
                        else
                        {
                            runFileResults.Add(file.Path, file.NewTag);
                        }
                    }
                    else if (file.Status == UpdateRunFileStatus.Delete)
                    { // 删除文件
                        var localPath = Path.Combine(runDir, file.Path);

                        OnProcessFile?.Invoke("正在删除文件:" + localPath);
                        if (!DeleteRunFile(localPath))
                        {
                            failedDeleteFiles.Add(file.Path);

                            // 对于删除失败的文件,新的配置文件应该仍包含旧的文件标识
                            runFileResults.Add(file.Path, file.OldTag);
                        }
                    }

                    OnProgress?.Invoke((++progress) * 1.0 / total);
                }

                foreach (var f in fileDiffResults.Where(f => f.Status == UpdateRunFileStatus.NotModified))
                {
                    runFileResults.Add(f.Path, f.OldTag);
                }

                localRunInfo.Ver      = remoteRunInfo.Ver;
                localRunInfo.RunFiles = runFileResults;

                OnComplete?.Invoke(localRunInfo, fileDiffResults, failedUpdateFiles, failedDeleteFiles, initStart, runBat, msg);
            }
            catch (Exception ex)
            {
                if (localRunInfo != null)
                {
                    LogHelper.LogErrorToServer($"客户端更新失败({msg})", ex, localRunInfo);
                }

                OnError?.Invoke(localRunInfo, ex);
            }
        }
Ejemplo n.º 28
0
 public Communicator()
     : base(0xE2E)
 {
     Weight = 4.0;
     m_On   = OnStatus.Off;
 }
Ejemplo n.º 29
0
        private void DoComparison()
        {
            using (StreamReader left = new StreamReader(File.Open(LeftFilename, FileMode.Open, FileAccess.Read)))
            {
                using (StreamReader right = new StreamReader(File.Open(RightFilename, FileMode.Open, FileAccess.Read)))
                {
                    List <string> messages = new List <string>();

                    if (left.EndOfStream)
                    {
                        messages.Add("Left file is empty.");
                    }
                    if (right.EndOfStream)
                    {
                        messages.Add("Right file is empty.");
                    }

                    if (messages.Count > 0)
                    {
                        this.HasError     = true;
                        this.ErrorMessage = string.Join(Environment.NewLine, messages.ToArray());
                        OnComplete?.Invoke(this);
                        return;
                    }

                    CSVLine leftLine  = new CSVLine(left.ReadLine());
                    CSVLine rightLine = new CSVLine(right.ReadLine());

                    if (leftLine.Columns.Count != rightLine.Columns.Count)
                    {
                        this.HasError     = true;
                        this.ErrorMessage = "Selected files do not have the same number of columns. Comparison not possible.";
                        OnComplete?.Invoke(this);
                        return;
                    }

                    int columnIndex = 0;
                    leftLine.Columns.ForEach(x =>
                    {
                        LeftHeaders.Add(new CSVHeader(columnIndex, x.Value));
                        columnIndex++;
                    });

                    columnIndex = 0;
                    rightLine.Columns.ForEach(x =>
                    {
                        RightHeaders.Add(new CSVHeader(columnIndex, x.Value));
                        columnIndex++;
                    });

                    int lineCounter = 1;
                    while (!(left.EndOfStream || right.EndOfStream))
                    {
                        leftLine  = new CSVLine(left.ReadLine());
                        rightLine = new CSVLine(right.ReadLine());

                        if (leftLine.Columns.Count != rightLine.Columns.Count)
                        {
                            HasError = true;
                            messages.Add($"Line {lineCounter}: Left file has {leftLine.Columns.Count} columns, but right file has {rightLine.Columns.Count} columns. Skipping comparison.");
                            ErrorMessage = string.Join(Environment.NewLine, messages.ToArray());
                            OnStatus?.Invoke(this);
                            lineCounter++;
                            continue;
                        }

                        for (columnIndex = 0; columnIndex < leftLine.Columns.Count; columnIndex++)
                        {
                            if (Differences.Keys.Contains(LeftHeaders[columnIndex].Description) && Differences[LeftHeaders[columnIndex].Description].Count >= _maxExamples)
                            {
                                continue;
                            }

                            if (leftLine.Columns[columnIndex].Value != rightLine.Columns[columnIndex].Value)
                            {
                                if (!Differences.Keys.Contains(LeftHeaders[columnIndex].Description))
                                {
                                    Differences.Add(LeftHeaders[columnIndex].Description, new List <CSVColumnDifference>());
                                }
                                Differences[LeftHeaders[columnIndex].Description].Add(new CSVColumnDifference(columnIndex, LeftHeaders[columnIndex].Description, leftLine.Columns[columnIndex].Value, rightLine.Columns[columnIndex].Value));
                            }
                        }

                        lineCounter++;
                    }

                    if (left.EndOfStream && !right.EndOfStream)
                    {
                        HasError = true;
                        messages.Add("Left file has fewer records.");
                        ErrorMessage = string.Join(Environment.NewLine, messages.ToArray());
                        OnComplete?.Invoke(this);
                        return;
                    }

                    if (right.EndOfStream && !left.EndOfStream)
                    {
                        HasError = true;
                        messages.Add("Right file has fewer records.");
                        ErrorMessage = string.Join(Environment.NewLine, messages.ToArray());
                        OnComplete?.Invoke(this);
                        return;
                    }

                    ErrorMessage = string.Join(Environment.NewLine, messages.ToArray());
                }
            }

            OnComplete?.Invoke(this);
        }
Ejemplo n.º 30
0
		public ProgressStream(Stream s, int contentLength, OnStatus onStatus = null)
		{
			this._baseStream = s;
			this.contentLength = contentLength>0?contentLength:predictedLength;
			this.statusCallback = onStatus;
		}
Ejemplo n.º 31
0
 public NSUrlDownloadDelegate(EventHandler <NSUrlEventArgs> downloadCompleted, OnStatus progress)
 {
     _downloadCompleted = downloadCompleted;
     _progress          = progress;
 }
Ejemplo n.º 32
0
 private static void SetStatus(string format, params object[] args)
 {
     OnStatus.Raise(typeof(VsComObjectUtility), string.Format(format, args));
 }
Ejemplo n.º 33
0
 private void Status(string message)
 {
     OnStatus?.Invoke(message, 1f - (ToExtract.Count / (float)Total));
 }