Beispiel #1
0
        /// <summary>
        /// Run cold tasks, <maxParallel> at same time
        /// </summary>
        /// <param name="tasks">cold (not runned) tasks</param>
        /// <param name="maxParallel">max parallel tasks</param>
        /// <param name="callback">callback on task complete</param>
        /// <param name="cancellationToken">cancellationToken</param>
        public static async Task Run <TRESULT>(IEnumerable <Task <TRESULT> > tasks, int maxParallel, ResultCallback <TRESULT> callback, CancellationToken cancellationToken)
        {
            var taskList = new List <Task <TRESULT> >(maxParallel);

            foreach (var task in tasks)
            {
                if (cancellationToken.IsCancellationRequested)
                {
                    continue;
                }

                taskList.Add(task);
                task.Start();
                if (taskList.Count == maxParallel)
                {
                    var result = await Task.WhenAny(taskList).ConfigureAwait(false);

                    taskList.Remove(result);

                    callback?.Invoke(result.Result);
                }
            }

            while (taskList.Count > 0)
            {
                var result = await Task.WhenAny(taskList).ConfigureAwait(false);

                taskList.Remove(result);

                callback?.Invoke(result.Result);
            }
        }
Beispiel #2
0
        public CancelDelegate ReadGame(ResultCallback cb)
        {
            WebClient client = new WebClient();

            client.DownloadStringCompleted += (object sender, DownloadStringCompletedEventArgs e) => {
                bool result = false;
                try {
                    if (e.Cancelled)
                    {
                        Logging.Log("ReadGame cancelled");
                    }
                    else if (e.Error != null)
                    {
                        Logging.LogException(e.Error);
                    }
                    else
                    {
                        string json = e.Result;
                        Logging.Log("ReadGame: " + json);
                        Hashtable ht = MiniJSON.jsonDecode(json) as Hashtable;
                        checkError(ht);
                        game   = new Game(ht);
                        result = true;
                    }
                } catch (Exception exc) {
                    /* Job failed, but we still have to exit job state */
                    Logging.LogException(exc);
                }
                cb.Invoke(result);
            };
            client.DownloadStringAsync(Page("/game", "name={0}", inGame));
            return(client.CancelAsync);
        }
Beispiel #3
0
        /// <summary>
        /// Determines whether this instance is satisfied.
        /// </summary>
        internal RuleResult IsSatisfied()
        {
            var        val        = PropertyInfo.GetValue(Element) ?? string.Empty;
            bool       thisresult = _predicates.All(x => x(this, val.ToString()));
            RuleResult result;

            if (LastResult.HasValue)
            {
                result = LastResult.Value == thisresult
                                        ? RuleResult.ValidationNoChange
                                        : thisresult
                                                ? RuleResult.ValidationSuccess
                                                : RuleResult.ValidationFailure;
            }
            else
            {
                result = thisresult
                                        ? RuleResult.ValidationSuccess
                                        : RuleResult.ValidationFailure;
            }
            LastResult = thisresult;

            ResultCallback?.Invoke(Element, RuleName, result);

            return(result);
        }
Beispiel #4
0
        public CancelDelegate JoinGame(string game, string name, ResultCallback cb)
        {
            WebClient client = new WebClient();

            client.DownloadStringCompleted += (object sender, DownloadStringCompletedEventArgs e) => {
                bool result = false;
                try {
                    if (e.Cancelled)
                    {
                        Logging.Log("JoinGame cancelled");
                    }
                    else if (e.Error != null)
                    {
                        Logging.LogException(e.Error);
                    }
                    else
                    {
                        string json = e.Result;
                        Logging.Log("JoinGame: " + json);
                        var ht = Json.Deserialize(json) as Dictionary <string, object>;
                        checkError(ht);
                        inGame    = game;
                        ourName   = name;
                        this.game = new Game(ht);
                        result    = true;
                    }
                } catch (Exception exc) {
                    /* Job failed, but we still have to exit job state */
                    Logging.LogException(exc);
                }
                cb.Invoke(result);
            };
            client.DownloadStringAsync(Page("/join", "game={0}&name={1}", game, name));
            return(client.CancelAsync);
        }
Beispiel #5
0
        private void _parseLoop()
        {
            // tread loop
            while (true)
            {
                // gets data for parse
                var fParse = _emptyEnumerable;
                lock (_sync)
                {
                    if (_cache.Any())
                    {
                        fParse = _cache.Dequeue();
                    }
                }

                // parse all extracted packets
                foreach (var packet in fParse)
                {
                    using (var memStream = new MemoryStream(packet.Payload, false))
                        using (var reader = new BinaryReader(memStream, Encoding.ASCII))
                        {
                            var action      = (ZServerParserAction)reader.ReadByte();
                            var game        = (ZGame)reader.ReadByte();
                            var serverId    = reader.ReadZUInt32();
                            var serverModel = BuildServerModel(game, serverId);

                            if (_gameContext != game)
                            {
                                ResultCallback?.Invoke(null, ZServerParserAction.Ignore);
                                continue;
                            }

                            switch (action)
                            {
                            case ZServerParserAction.Add:
                                ParseIntoServerModel(serverModel, reader);

                                break;

                            case ZServerParserAction.PlayersList:
                                ParsePlayers(_myId, serverModel, reader);

                                break;

                            case ZServerParserAction.Remove: break;
                            }

                            // handle parsed data
                            ResultCallback?.Invoke(serverModel, action);
                        }
                }

                Thread.Sleep(100);
            }
        }
Beispiel #6
0
            // Thread function which will calculate the sum of the numbers.
            public void CalculateSum()
            {
                int res = 0;

                for (int i = 1; i <= _number; i++)
                {
                    res += i;
                }

                // Before the end of the thread function call the callback method.
                _callback?.Invoke(res);
            }
Beispiel #7
0
        public CancelDelegate Sync(ResultCallback cb)
        {
            RISMilestone   stone = monitor.CheckAll();
            CancelDelegate cd    = () => {};

            if (stone != null)
            {
                cd += Report(stone, (bool ok) => {
                    if (ok)
                    {
                        cd += Sync(cb);
                    }
                    else
                    {
                        cb.Invoke(false);
                    }
                });
                return(cd);
            }
            cd += SyncTail((bool ok) => {
                if (ok)
                {
                    List <RISMilestone> toResolve = monitor.ToResolve();
                    if (toResolve.Count > 0)
                    {
                        cd += Resolve(toResolve, cb);
                    }
                    else
                    {
                        cb.Invoke(true);
                    }
                }
                else
                {
                    cb.Invoke(false);
                }
            });
            return(cd);
        }
Beispiel #8
0
 private void button1_Click(object sender, EventArgs e)
 {
     try
     {
         Item = new DownloadItem(textBoxFrom.Text, textBoxFile.Text);
     }
     catch (Exception ex)
     {
         labelError.Text = "Error: " + ex.Message;
         return;
     }
     ResultCallback?.Invoke(this);
     Close();
 }
Beispiel #9
0
        private IEnumerator ExecuteRequest(WWW www, ResultCallback callback)
        {
            float elapsedTime = 0.0f;

            while (!www.isDone)
            {
                elapsedTime += Time.deltaTime;

                if (elapsedTime >= WAIT_TIMEOUT)
                {
                    if (callback != null)
                    {
                        callback(true, "{\"status\":400,\"message\":\"local timeout!\"}");
                    }

                    yield break;
                }

                yield return(null);
            }

            if (!www.isDone || !string.IsNullOrEmpty(www.error) || string.IsNullOrEmpty(www.text))
            {
                if (callback != null)
                {
                    callback(true, "{\"status\":400,\"message\":\"" + www.error + "\"}");
                }

                yield break;
            }

            var response = www.text;

            try {
                JSONNode json = SimpleJSON.JSON.Parse(response);

                if (json["status"] != null && json["status"].AsInt != 200)
                {
                    callback?.Invoke(true, response);
                    yield break;
                }
            } catch (Exception ex) {
                Debug.LogException(ex);
            }

            if (callback != null)
            {
                callback(false, response);
            }
        }
Beispiel #10
0
        public CancelDelegate PartGame(ResultCallback cb)
        {
            WebClient client = new WebClient();

            client.DownloadStringCompleted += (object sender, DownloadStringCompletedEventArgs e) => {
                bool result = false;
                try {
                    if (e.Cancelled)
                    {
                        Logging.Log("PartGame cancelled");
                    }
                    else if (e.Error != null)
                    {
                        Logging.LogException(e.Error);
                    }
                    else
                    {
                        string json = e.Result;
                        Logging.Log("PartGame: " + json);
                        Hashtable ht = MiniJSON.jsonDecode(json) as Hashtable;
                        if (ht.Contains("err"))
                        {
                            if (ht.Contains("code") && (int)ht["code"] == ENOENT)
                            {
                                Logging.Log("Player was already parted");
                            }
                            else                             /* real error, let's throw */
                            {
                                checkError(ht);
                            }
                        }
                        inGame    = null;
                        ourName   = null;
                        this.game = null;
                        result    = true;
                    }
                } catch (Exception exc) {
                    /* Job failed, but we still have to exit job state */
                    Logging.LogException(exc);
                }
                cb.Invoke(result);
            };
            client.DownloadStringAsync(Page("/part", "game={0}&name={1}", inGame, ourName));
            return(client.CancelAsync);
        }
Beispiel #11
0
        public CancelDelegate Resolve(List <RISMilestone> stones, ResultCallback cb)
        {
            WebClient      client = new WebClient();
            CancelDelegate cd     = () => {};
            RISMilestone   stone  = stones[0];

            stones.RemoveAt(0);
            Logging.LogFormat("Resolving {0}", stone.name);
            client.DownloadStringCompleted += (object sender, DownloadStringCompletedEventArgs e) => {
                bool result = false;
                try {
                    if (e.Cancelled)
                    {
                        Logging.Log("Resolve(Sync) cancelled");
                    }
                    else if (e.Error != null)
                    {
                        Logging.LogException(e.Error);
                    }
                    else
                    {
                        string json = e.Result;
                        Logging.Log("Resolve: " + json);
                        Hashtable ht = MiniJSON.jsonDecode(json) as Hashtable;
                        checkError(ht);
                        Result r = new Result(ht, ourName);
                        stone.Resolve(r.first);
                        result = true;
                    }
                } catch (Exception exc) {
                    /* Job failed, but we still have to exit job state */
                    Logging.LogException(exc);
                }
                if (result && stones.Count > 0)
                {
                    cd += Resolve(stones, cb);
                    return;
                }
                cb.Invoke(result);
            };
            client.DownloadStringAsync(Page("/result", "game={0}&contract={1}", inGame, stone.name));
            cd += client.CancelAsync;
            return(cd);
        }
Beispiel #12
0
        public CancelDelegate Report(RISMilestone stone, ResultCallback cb)
        {
            WebClient client = new WebClient();

            Logging.LogFormat("Reporting {0} completed at {1}", stone.name, stone.completed.ToString());
            client.DownloadStringCompleted += (object sender, DownloadStringCompletedEventArgs e) => {
                bool result = false;
                try {
                    if (e.Cancelled)
                    {
                        Logging.Log("Report(Sync) cancelled");
                    }
                    else if (e.Error != null)
                    {
                        Logging.LogException(e.Error);
                    }
                    else
                    {
                        string json = e.Result;
                        Logging.Log("Report: " + json);
                        Hashtable ht = MiniJSON.jsonDecode(json) as Hashtable;
                        checkError(ht);
                        Result r = new Result(ht, ourName);
                        if (r.date != null)
                        {
                            stone.reported = true;
                        }
                        stone.Resolve(r.first);
                        result = true;
                    }
                } catch (Exception exc) {
                    /* Job failed, but we still have to exit job state */
                    Logging.LogException(exc);
                }
                cb.Invoke(result);
            };
            client.DownloadStringAsync(Page("/completed", "game={0}&player={1}&year={2:D}&day={3:D}&contract={4}",
                                            inGame, ourName, stone.completed.year, stone.completed.day, stone.name));
            return(client.CancelAsync);
        }
Beispiel #13
0
        public CancelDelegate ListGames(ResultCallback cb)
        {
            KerbalMonitor.CountDeadKerbals();
            WebClient client = new WebClient();

            client.DownloadStringCompleted += (object sender, DownloadStringCompletedEventArgs e) => {
                bool result = false;
                try {
                    if (e.Cancelled)
                    {
                        Logging.Log("ListGames cancelled");
                    }
                    else if (e.Error != null)
                    {
                        Logging.LogException(e.Error);
                    }
                    else
                    {
                        string json = e.Result;
                        Logging.Log("ListGames: " + json);
                        Hashtable ht = MiniJSON.jsonDecode(json) as Hashtable;
                        checkError(ht);
                        gameList = new Dictionary <string, GameListEntry>();
                        foreach (DictionaryEntry de in ht)
                        {
                            gameList.Add(de.Key.ToString(), new GameListEntry(de.Value as Hashtable));
                        }
                        Logging.LogFormat("Listed {0} games", gameList.Count);
                        result = true;
                    }
                } catch (Exception exc) {
                    /* Job failed, but we still have to exit job state */
                    Logging.LogException(exc);
                }
                cb.Invoke(result);
            };
            client.DownloadStringAsync(Page("/"));
            return(client.CancelAsync);
        }
Beispiel #14
0
        public CancelDelegate SyncTail(ResultCallback cb)
        {
            WebClient client = new WebClient();

            client.DownloadStringCompleted += (object sender, DownloadStringCompletedEventArgs e) => {
                bool result = false;
                try {
                    if (e.Cancelled)
                    {
                        Logging.Log("Sync cancelled");
                    }
                    else if (e.Error != null)
                    {
                        Logging.LogException(e.Error);
                    }
                    else
                    {
                        string json = e.Result;
                        Logging.Log("Sync: " + json);
                        Hashtable ht = MiniJSON.jsonDecode(json) as Hashtable;
                        checkError(ht);
                        game   = new Game(ht);
                        result = true;
                    }
                } catch (Exception exc) {
                    /* Job failed, but we still have to exit job state */
                    Logging.LogException(exc);
                }
                cb.Invoke(result);
            };
            YDate date = new YDate(Planetarium.GetUniversalTime());
            int   kia  = KerbalMonitor.CountDeadKerbals();

            client.DownloadStringAsync(Page("/sync", "game={0}&player={1}&year={2:D}&day={3:D}&kia={4:D}", inGame, ourName, date.year, date.day, kia));
            return(client.CancelAsync);
        }
 void GotPartialResult(string result)
 {
     Debug.Log("GotPartialResult " + result);
     onPartialResults.Invoke(result);
 }
 public static void Try <T>(this ResultCallback <T> callback, Result <T> param)
 {
     callback?.Invoke(param);
 }
 public static void TryOk <T>(this ResultCallback <T> callback, T value)
 {
     callback?.Invoke(Result <T> .CreateOk(value));
 }
 public static void TryError <T>(this ResultCallback <T> callback, ErrorCode errorCode)
 {
     callback?.Invoke(Result <T> .CreateError(errorCode));
 }
 public static void Try(this ResultCallback callback, Result param)
 {
     callback?.Invoke(param);
 }
 public static void TryOk(this ResultCallback callback)
 {
     callback?.Invoke(Result.CreateOk());
 }
 public static void TryError(this ResultCallback callback, ErrorCode errorCode, string errorMessage = null)
 {
     callback?.Invoke(Result.CreateError(errorCode, errorMessage));
 }
 public static void TryError(this ResultCallback callback, Error error)
 {
     callback?.Invoke(Result.CreateError(error));
 }
 void GotFinalResult(string result)
 {
     Debug.Log("GotFinalResult " + result);
     onFinalResults.Invoke(result);
 }
        /// <summary>
        /// Get active parties based on the pagination result.
        /// </summary>
        /// <param name="paging">The processed paging response.</param>
        /// <param name="paginationType">Which page that will be opened.</param>
        /// <param name="callback">Returns a Result via callback when completed.</param>
        public void GetActiveParties(Paging paging, PaginationType paginationType, ResultCallback <ActivePartiesData> callback)
        {
            Report.GetFunctionLog(this.GetType().Name);

            if (!this.session.IsValid())
            {
                callback.TryError(ErrorCode.IsNotLoggedIn);
                return;
            }

            string pagingUrl = "";

            switch (paginationType)
            {
            case PaginationType.FIRST:
                pagingUrl = paging.first;
                break;

            case PaginationType.NEXT:
                pagingUrl = paging.next;
                break;

            case PaginationType.PREVIOUS:
                pagingUrl = paging.previous;
                break;
            }

            var OnInvalidPagination = Result <ActivePartiesData> .CreateError(ErrorCode.NotFound, "Provided pagination type is empty.");

            var questionMarkIndex = pagingUrl.LastIndexOf("?");

            if (string.IsNullOrEmpty(pagingUrl) || questionMarkIndex == -1)
            {
                callback.Invoke(OnInvalidPagination);
                return;
            }

            pagingUrl = pagingUrl.Substring(questionMarkIndex + 1, pagingUrl.Length - (questionMarkIndex + 1));
            var queryParams = pagingUrl.Split('&');

            int limit  = 0;
            int offset = 0;

            foreach (var param_ in queryParams)
            {
                int limitIndex  = param_.IndexOf("limit=");
                int offsetIndex = param_.IndexOf("offset=");
                if (limitIndex > -1)
                {
                    var value = param_.Substring(limitIndex + 6, param_.Length - (limitIndex + 6));
                    limit = Convert.ToInt32(value);
                }
                else if (offsetIndex > -1)
                {
                    var value = param_.Substring(offsetIndex + 7, param_.Length - (offsetIndex + 7));
                    offset = Convert.ToInt32(value);
                }
            }

            this.coroutineRunner.Run(
                this.api.GetActiveParties(
                    this.namespace_,
                    this.session.AuthorizationToken,
                    limit,
                    offset,
                    callback));
        }