Ejemplo n.º 1
0
        public Task <object> Sql(string command, object[] parameters)
        {
            EnsureExecutor();

            Dictionary <string, object> executionArgs = new Dictionary <string, object>();

            executionArgs["connectionString"] = _connectionString;
            executionArgs["command"]          = command;
            executionArgs["parameters"]       = Script.Or(parameters, null);
            if (_localFile)
            {
                executionArgs["localFile"] = true;
            }

            Deferred <object> deferred = Deferred.Create <object>();

            _executor(executionArgs, delegate(Exception e, object o) {
                if (e != null)
                {
                    deferred.Reject(e);
                }
                else
                {
                    deferred.Resolve(o);
                }
            });
            return(deferred.Task);
        }
Ejemplo n.º 2
0
        public Promise <MultiPlayerMessage> SendRequest(MultiPlayerMessage message, TimeSpan?timeout = null)
        {
            try
            {
                message.Sender    = ClientId;
                message.RequestId = Guid.NewGuid().ToString();
                var pendingRequest = new PendingRequest()
                {
                    Id = message.RequestId,
                    ResponseDeferred = Deferred <MultiPlayerMessage> .Create(),
                };

                if (timeout.HasValue)
                {
                    pendingRequest.Timeout = timeout.Value;
                }
                lock (pendingRequests)
                {
                    pendingRequests.Add(message.RequestId, pendingRequest);
                }
                SendMessage(message);
                return(pendingRequest.ResponseDeferred.Promise);
            }
            catch (Exception ex)
            {
                var d = Deferred <MultiPlayerMessage> .Create();

                d.Reject(ex);
                return(d.Promise);
            }
        }
Ejemplo n.º 3
0
        public static Promise <ConsoleString> ShowRichTextInput(ConsoleString message, bool allowEscapeToCancel = true, int maxHeight = 12, ConsoleString initialValue = null)
        {
            var d = Deferred <ConsoleString> .Create();

            ShowRichTextInput(message, (ret) => d.Resolve(ret), () => d.Resolve(null), allowEscapeToCancel, maxHeight, initialValue: initialValue);
            return(d.Promise);
        }
Ejemplo n.º 4
0
        public static Promise <T?> PickFromEnum <T>(ConsoleString message) where T : struct
        {
            Deferred <T?> deferred = Deferred <T?> .Create();

            var      enumVals    = Enum.GetValues(typeof(T));
            List <T> genericVals = new List <T>();

            foreach (T val in enumVals)
            {
                genericVals.Add(val);
            }

            var innerPromise = Pick(message, genericVals.Select(v => new DialogOption()
            {
                Id          = v.ToString(),
                DisplayText = v.ToString().ToConsoleString()
            }));

            innerPromise.Finally((p) =>
            {
                if (p.Exception != null)
                {
                    deferred.Reject(p.Exception);
                }
                else
                {
                    deferred.Resolve(innerPromise.Result != null ? (T)Enum.Parse(typeof(T), innerPromise.Result.Id) : default(T?));
                }
            });


            return(deferred.Promise);
        }
Ejemplo n.º 5
0
        protected override Task <object> ExecuteQuery(DataRequest request, Dictionary <string, object> options)
        {
            DataQuery query = request.Query;
            Dictionary <string, Dictionary <string, object> > set = GetDataSet(query);

            object result;

            if (query.IsLookup)
            {
                result = Script.Or(set[query.ID], null);
            }
            else
            {
                // TODO: Apply query

                List <Dictionary <string, object> > items = new List <Dictionary <string, object> >();
                foreach (KeyValuePair <string, Dictionary <string, object> > itemEntry in set)
                {
                    items.Add(itemEntry.Value);
                }

                result = items;
            }

            return(Deferred.Create <object>(result).Task);
        }
Ejemplo n.º 6
0
        public ApiRequestObject(ApiRequest request)
        {
            Verb       = request.Verb;
            ActionName = request.ActionName;
            Arguments  = request.ActionArguments;
            Headers    = request.Headers;
            Data       = request.Data;

            Respond = delegate(object data, Dictionary <string, object> options) {
                options = Script.Or(options, new Dictionary <string, object>());

                HttpStatusCode statusCode = Script.Or((HttpStatusCode)options["statusCode"],
                                                      (data == null) ? HttpStatusCode.NoContent : HttpStatusCode.OK);

                ServerResponse response = new ServerResponse(statusCode);

                if (data != null)
                {
                    if (data is string)
                    {
                        response.AddTextContent((string)data, Script.Or((string)options["contentType"], "text/plain"));
                    }
                    else
                    {
                        response.AddObjectContent(data);
                    }
                }

                return(Deferred.Create <ServerResponse>(response).Task);
            };
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Does nothing
        /// </summary>
        /// <param name="soundId">unused</param>
        /// <returns>a promise that resolves immediately to a dummy disposable</returns>
        public Promise <IDisposable> Loop(string soundId)
        {
            var d = Deferred <IDisposable> .Create();

            d.Resolve(new DummyDisposable());
            return(d.Promise);
        }
Ejemplo n.º 8
0
 public Promise Play()
 {
     introDeferred = Deferred.Create();
     SpaceTime.QueueAction("GameIntro", PlaySceneInternal);
     SpaceTime.Start("PowerArgsGameIntro");
     return(introDeferred.Promise);
 }
Ejemplo n.º 9
0
        internal static Promise AcceptConnection(InProcClientNetworkProvider inProcClient, ServerInfo serverInfo)
        {
            var d = Deferred.Create();

            try
            {
                var server = servers[serverInfo.Server + ":" + serverInfo.Port];
                if (server.allowNewConnections)
                {
                    server.inProcClients.Add(inProcClient.ClientId, inProcClient);
                    server.ClientConnected.Fire(new MultiPlayerClientConnection()
                    {
                        ClientId = inProcClient.ClientId
                    });
                }
                else
                {
                    throw new IOException("new connections not allowed");
                }
                d.Resolve();
            }
            catch (Exception ex)
            {
                d.Reject(ex);
            }
            return(d.Promise);
        }
Ejemplo n.º 10
0
 public Promise Play()
 {
     introDeferred = Deferred.Create();
     SpaceTime.QueueAction(PlaySceneInternal);
     SpaceTime.Start();
     return(introDeferred.Promise);
 }
Ejemplo n.º 11
0
        public static Task <MongoWineRepository> Create(string dbHost, int dbPort, string dbName, string userName, string password)
        {
            Deferred <MongoWineRepository> deferred = Deferred.Create <MongoWineRepository>();

            Dictionary <string, object> serverOptions = new Dictionary <string, object>("auto_reconnect", true);
            Dictionary <string, object> dbOptions     = new Dictionary <string, object>("w", "0");

            MongoServer    dbServer    = new MongoServer(dbHost, dbPort, serverOptions);
            MongoConnector dbConnector = new MongoConnector(dbName, dbServer, dbOptions);

            dbConnector.Open(delegate(Exception openError, MongoDatabase db) {
                db.Authenticate(userName, password, delegate(Exception authError, bool success) {
                    if (success)
                    {
                        db.CreateCollection("wines", delegate(Exception collectionError, MongoCollection collection) {
                            if (collection != null)
                            {
                                MongoWineRepository repository = new MongoWineRepository(db, collection);
                                deferred.Resolve(repository);
                            }
                            else
                            {
                                deferred.Reject();
                            }
                        });
                    }
                    else
                    {
                        deferred.Reject();
                    }
                });
            });

            return(deferred.Task);
        }
Ejemplo n.º 12
0
        public Promise Connect(ServerInfo server)
        {
            var d = Deferred.Create();

            try
            {
                client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                if (IPAddress.TryParse(server.Server, out IPAddress ip))
                {
                    client.Connect(ip, server.Port);
                }
                else
                {
                    client.Connect(server.Server, server.Port);
                }
                this.ClientId = (client.LocalEndPoint as IPEndPoint).Address + ":" + (client.LocalEndPoint as IPEndPoint).Port;
                Thread t = new Thread(ListenForMessages);
                t.IsBackground = true;
                t.Start(d);
            }
            catch (Exception ex)
            {
                d.Reject(ex);
            }
            return(d.Promise);
        }
Ejemplo n.º 13
0
        public async Task TestWhenAllWithExceptions()
        {
            var promises = new List <Promise>();

            for (var i = 0; i < 10; i++)
            {
                var      myI = i;
                Deferred d   = Deferred.Create();
                promises.Add(d.Promise);
                Task.Factory.StartNew(() =>
                {
                    if (myI % 2 == 0)
                    {
                        d.Resolve();
                    }
                    else
                    {
                        d.Reject(new Exception("Failed"));
                    }
                });
            }
            try
            {
                await Promise.WhenAll(promises).AsAwaitable();

                Assert.Fail("An exception should have been thrown");
            }
            catch (PromiseWaitException ex)
            {
                Assert.AreEqual(5, ex.InnerExceptions.Count);
            }
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Shows a message and lets the user pick from a set of options defined by an enum
        /// </summary>
        /// <param name="message">the message to show</param>
        /// <param name="enumType">the enum type</param>
        /// <returns>A promise that resolves with the selected value or null if the dialog was cancelled. The promise never rejects.</returns>
        public static Promise <object> ShowEnumOptions(ConsoleString message, Type enumType)
        {
            Deferred <object> deferred = Deferred <object> .Create();

            var rawPromise = ShowMessage(new DialogButtonOptions()
            {
                Message = message,
                Mode    = DialogButtonsPresentationMode.Grid,
                Options = Enums.GetEnumValues(enumType).OrderBy(e => e.ToString()).Select(e => new DialogOption()
                {
                    Id = e.ToString(), DisplayText = e.ToString().ToConsoleString(), Value = e
                }).ToList()
            });

            rawPromise.Then((b) =>
            {
                if (b == null)
                {
                    deferred.Resolve(null);
                }
                else
                {
                    deferred.Resolve(b.Value);
                }
            });

            return(deferred.Promise);
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Starts the time simulation thread
        /// </summary>
        /// <param name="name">the name of the thread to start. This is useful when debugging.</param>
        /// <returns>A promise that represents the end of the time simulation</returns>
        public Promise Start(string name = "TimeThread")
        {
            runDeferred = Deferred.Create();
            runDeferred.Promise.Finally((p) => { runDeferred = null; });
            Thread t = new Thread(() =>
            {
                SynchronizationContext.SetSynchronizationContext(syncContext);
                IsRunning = true;
                try
                {
                    current = this;
                    Loop();
                }
                catch (StopTimeException)
                {
                    IsRunning = false;
                    runDeferred.Resolve();
                }
                catch (Exception ex)
                {
                    IsRunning = false;
                    UnhandledException.Fire(ex);
                    runDeferred.Reject(ex);
                }
            })
            {
                Name = name
            };

            t.Priority     = ThreadPriority.AboveNormal;
            t.IsBackground = true;
            t.Start();

            return(runDeferred.Promise);
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Shows a dialog with the given message and provides the user with a yes and no option
        /// </summary>
        /// <param name="message">the message to show</param>
        /// <returns>a promise that resolves if the yes option was cicked. it rejects if no was clicked or if the dialog was cancelled</returns>
        public static Promise ShowYesConfirmation(ConsoleString message)
        {
            var d             = Deferred.Create();
            var buttonPromise = ShowMessage(new DialogButtonOptions()
            {
                Message = message,
                Options = new List <DialogOption>()
                {
                    DialogButtonOptions.Yes,
                    DialogButtonOptions.No
                }
            });

            buttonPromise.Then((button) =>
            {
                if (button != null && button.Equals(DialogButtonOptions.Yes))
                {
                    d.Resolve();
                }
                else
                {
                    d.Reject(new Exception("No was selected"));
                }
            });
            return(d.Promise);
        }
Ejemplo n.º 17
0
        public Task <ServerResponse> ProcessRequest(ServerRequest request)
        {
            string     controllerName = request.Route.Parameters["controllerName"];
            Controller controller     = _endpoints.GetController(controllerName);

            if (controller == null)
            {
                return(Deferred.Create <ServerResponse>(ServerResponse.NotFound).Task);
            }

            ApiRequest apiRequest = new ApiRequest(controller, request.HttpRequest.Method, request.Route.Parameters["actionName"],
                                                   (Dictionary <string, string>)request.HttpRequest.Headers,
                                                   request.UrlData.Query);

            if (controller.SupportsRequest(apiRequest) == false)
            {
                return(Deferred.Create <ServerResponse>(ServerResponse.MethodNotAllowed).Task);
            }

            if ((request.HttpRequest.Method == HttpVerb.POST) || (request.HttpRequest.Method == HttpVerb.PUT))
            {
                Deferred <ServerResponse> deferred = Deferred.Create <ServerResponse>();

                request.GetData().ContinueWith(delegate(Task <object> dataTask) {
                    if (dataTask.Status == TaskStatus.Failed)
                    {
                        deferred.Reject(dataTask.Error);
                        return;
                    }

                    Task <ServerResponse> executeTask;
                    try {
                        apiRequest.Data = dataTask.Result;
                        executeTask     = ExecuteRequest(controller, apiRequest);
                    }
                    catch (Exception e) {
                        deferred.Resolve(ServerResponse.CreateServerError(e.Message));
                        return;
                    }

                    executeTask.ContinueWith(delegate(Task <ServerResponse> t) {
                        if (t.Status == TaskStatus.Done)
                        {
                            deferred.Resolve(t.Result);
                        }
                        else
                        {
                            deferred.Resolve(ServerResponse.CreateServerError(t.Error.Message));
                        }
                    });
                });

                return(deferred.Task);
            }
            else
            {
                return(ExecuteRequest(controller, apiRequest));
            }
        }
Ejemplo n.º 18
0
        public Promise OpenForNewConnections()
        {
            var d = Deferred.Create();

            allowNewConnections = true;
            d.Resolve();
            return(d.Promise);
        }
Ejemplo n.º 19
0
        public Promise CloseForNewConnections()
        {
            var d = Deferred.Create();

            allowNewConnections = false;
            d.Resolve();
            return(d.Promise);
        }
Ejemplo n.º 20
0
        public Test()
        {
            Deferred       deferredObject   = Deferred.Create();
            Deferred <int> deferredNumber   = Deferred.Create <int>();
            Deferred <int> availabledNumber = Deferred.Create <int>(10);

            deferredNumber.Reject();
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Shows the dialog on top of the current app
        /// </summary>
        /// <returns>a promise that resolves when this dialog is dismissed. This promise never rejects.</returns>
        private Promise Show()
        {
            ConsoleApp.AssertAppThread();
            var deferred = Deferred.Create();

            ConsoleApp.Current.LayoutRoot.Add(this);
            RemovedFromVisualTree.SubscribeForLifetime(deferred.Resolve, this);
            return(deferred.Promise);
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Shows a message and lets the user pick from a set of options defined by an enum
        /// </summary>
        /// <typeparam name="T">the enum type</typeparam>
        /// <param name="message">the message to show</param>
        /// <returns>A promise that resolves with the selected value or null if the dialog was cancelled. The promise never rejects.</returns>
        public static Promise <T?> ShowEnumOptions <T>(ConsoleString message) where T : struct
        {
            var d = Deferred <T?> .Create();

            var rawPromise = ShowEnumOptions(message, typeof(T));

            rawPromise.Then((o) => d.Resolve(o == null ? new T?() : (T)o));
            return(d.Promise);
        }
Ejemplo n.º 23
0
        /// <summary>
        /// Shows a dialog that presents the user with a message and a text box
        /// </summary>
        /// <param name="options">the options used to configure the dialog</param>
        /// <returns>a promise that resolves with the value of the text box at the time of dismissal. This promise never rejects.</returns>
        public static Promise <ConsoleString> ShowRichTextInput(RichTextDialogOptions options)
        {
            var d = Deferred <ConsoleString> .Create();

            var rawPromise = new Dialog(options).Show();

            rawPromise.Then(() => d.Resolve(options.TextBox.Value));
            return(d.Promise);
        }
Ejemplo n.º 24
0
        /// <summary>
        /// Shows a dialog with a message and a set of options for the user to choose from
        /// </summary>
        /// <param name="options">the options used to configure the dialog</param>
        /// <returns>a promise that resolves with the selected option or null if the dialog was cancelled. The promise never rejects.</returns>
        public static Promise <DialogOption> ShowMessage(DialogButtonOptions options)
        {
            var d = Deferred <DialogOption> .Create();

            var rawPromise = new Dialog(options).Show();

            rawPromise.Then(() => d.Resolve(options.SelectedOption));
            return(d.Promise);
        }
Ejemplo n.º 25
0
        protected override Task <object> ExecuteNonQuery(DataRequest request, Dictionary <string, object> options)
        {
            Dictionary <string, Dictionary <string, object> > set = GetDataSet(request.Query);
            string id = request.Query.ID;

            object result = false;

            if (request.Operation == DataOperation.Insert)
            {
                if (set.ContainsKey(id) == false)
                {
                    Dictionary <string, object> item = request.Item;
                    item["id"] = id;

                    set[id] = item;
                    result  = true;
                }
            }
            else if (request.Operation == DataOperation.Update)
            {
                if (set.ContainsKey(id))
                {
                    Dictionary <string, object> item = request.Item;
                    item["id"] = id;

                    set[id] = item;
                    result  = true;
                }
            }
            else if (request.Operation == DataOperation.Merge)
            {
                if (set.ContainsKey(id))
                {
                    Dictionary <string, object> existingItem = set[id];
                    Dictionary <string, object> updatedItem  = request.Item;

                    foreach (KeyValuePair <string, object> fieldEntry in updatedItem)
                    {
                        existingItem[fieldEntry.Key] = fieldEntry.Value;
                    }
                    existingItem["id"] = id;

                    result = true;
                }
            }
            else if (request.Operation == DataOperation.Delete_)
            {
                if (set.ContainsKey(id))
                {
                    set.Remove(id);
                    result = true;
                }
            }

            return(Deferred.Create <object>(result).Task);
        }
Ejemplo n.º 26
0
        /// <summary>
        /// Does nothing
        /// </summary>
        /// <param name="soundId">unused</param>
        public Promise <Lifetime> Play(string soundId)
        {
            var d = Deferred <Lifetime> .Create();

            var l = new Lifetime();

            l.Dispose();
            d.Resolve(l);
            return(d.Promise);
        }
Ejemplo n.º 27
0
        /// <summary>
        /// Queues up a request to paint the app.  The system will dedupe multiple paint requests when there are multiple in the pump's work queue
        /// <returns>a promise that resolves after the paint happens</returns>
        /// </summary>
        public Promise Paint()
        {
            var d = Deferred.Create();

            QueueAction(new PaintMessage(PaintInternal)
            {
                Deferred = d
            });
            return(d.Promise);
        }
Ejemplo n.º 28
0
            protected override Promise <List <T> > FetchRangeAsync(int min, int count)
            {
                var d = Deferred <List <T> > .Create();

                new Thread(() =>
                {
                    Thread.Sleep(50);
                    d.Resolve(items.Skip(min).Take(count).ToList());
                }).Start();
                return(d.Promise);
            }
Ejemplo n.º 29
0
            protected override Promise <int> FetchCountAsync()
            {
                var d = Deferred <int> .Create();

                new Thread(() =>
                {
                    Thread.Sleep(50);
                    d.Resolve(items.Count);
                }).Start();
                return(d.Promise);
            }
Ejemplo n.º 30
0
        /// <summary>
        /// Puts the given action into the work queue, but skips it to the front of the queue
        /// </summary>
        /// <param name="a">the action code to run</param>
        /// <returns>a promise that will resolve when the work is done</returns>
        protected Promise QueueActionInFront(Action a)
        {
            var d           = Deferred.Create();
            var pumpMessage = new PumpMessage(a)
            {
                Deferred = d
            };

            QueueActionInFront(pumpMessage);
            return(d.Promise);
        }