Inheritance: NSApplicationDelegate
示例#1
0
        public static AppDelegate Middleware(AppDelegate app)
        {
            return call =>
            {
                return app(call).Then<ResultParameters, ResultParameters>(
                    result =>
                    {
                        if (IsStatusWithNoNoEntityBody(result.Status)
                            || result.Headers.ContainsKey("Content-Length")
                            || result.Headers.ContainsKey("Transfer-Encoding"))
                        {
                            return TaskHelpers.FromResult(result);
                        }

                        if (result.Body == null)
                        {
                            result.Headers.SetHeader("Content-Length", "0");
                            return TaskHelpers.FromResult(result);
                        }

                        // Buffer the body
                        MemoryStream buffer = new MemoryStream();
                        return result.Body(buffer).Then<ResultParameters>(
                            () =>
                            {
                                buffer.Seek(0, SeekOrigin.Begin);
                                result.Headers.SetHeader("Content-Length", buffer.Length.ToString(CultureInfo.InvariantCulture));
                                result.Body = output => buffer.CopyToAsync(output);

                                return TaskHelpers.FromResult(result);
                            });

                    });
            };
        }
示例#2
0
        public static AppDelegate Middleware(AppDelegate app)
        {
            return
                (env, result, fault) =>
                    app(
                        env,
                        (status, headers, body) =>
                        {
                            if (IsStatusWithNoNoEntityBody(status) ||
                                headers.ContainsKey("Content-Length") ||
                                headers.ContainsKey("Transfer-Encoding"))
                            {
                                result(status, headers, body);
                            }
                            else
                            {
                                var token = CancellationToken.None;
                                object obj;
                                if (env.TryGetValue(typeof(CancellationToken).FullName, out obj) && obj is CancellationToken)
                                    token = (CancellationToken)obj;

                                var buffer = new DataBuffer();
                                body(
                                    buffer.Add,
                                    ex =>
                                    {
                                        buffer.End(ex);
                                        headers["Content-Length"] = new[] { buffer.GetCount().ToString() };
                                        result(status, headers, buffer.Body);
                                    },
                                    token);
                            }
                        },
                        fault);
        }
示例#3
0
 public static AppDelegate Middleware(AppDelegate app)
 {
     return
         (call, callback) =>
             app(
                 call,
                 (result, error) =>
                 {
                     if (error != null ||
                         IsStatusWithNoNoEntityBody(result.Status) ||
                         result.Headers.ContainsKey("Content-Length") ||
                         result.Headers.ContainsKey("Transfer-Encoding"))
                     {
                         callback(result, error);
                     }
                     else
                     {
                         var buffer = new DataBuffer();
                         result.Body.Invoke(
                             buffer.Add,
                             ex =>
                             {
                                 buffer.End(ex);
                                 result.Headers.SetHeader("Content-Length", buffer.GetCount().ToString());
                                 result.Body = buffer.Body;
                                 callback(result, null);
                             },
                             call.CallDisposed);
                     }
                 });
 }
示例#4
0
 public OAuthContext(AppDelegate next, IDictionary<string, object> env, ResultDelegate result, Action<Exception> fault)
 {
     m_next = next;
      m_env = env;
      m_result = result;
      m_fault = fault;
 }
示例#5
0
 public Server(AppDelegate app, IPAddress ipAddress, int port)
 {
     _app = app;
     _ipAddress = ipAddress;
     _port = port;
     _listener = new TcpListener(_ipAddress, _port);
 }
示例#6
0
 public static WebServiceHost Create(Uri baseUri, AppDelegate app)
 {
     var host = new WebServiceHost(new GateWcfService(app), baseUri);
     host.AddServiceEndpoint(typeof (GateWcfService), new WebHttpBinding(), "");
     host.Open();
     return host;
 }
        public CollisionGame()
        {
            // Set the title of the window
            Window.Title = "Cocos2D-XNA Tutorials: Collision Detection";

            graphics = new GraphicsDeviceManager(this);

            //#if MONOMAC
            //            Content.RootDirectory = "AngryNinjas/Content";
            //#else
            Content.RootDirectory = "Content";
            //#endif
            //
            //#if XBOX || OUYA
            //            graphics.IsFullScreen = true;
            //#else
            graphics.IsFullScreen = false;
            //#endif

            // Frame rate is 30 fps by default for Windows Phone.
            TargetElapsedTime = TimeSpan.FromTicks(333333 / 2);

            // Extend battery life under lock.
            //InactiveSleepTime = TimeSpan.FromSeconds(1);

            CCApplication application = new AppDelegate(this, graphics);
            Components.Add(application);
            //#if XBOX || OUYA
            //            CCDirector.SharedDirector.GamePadEnabled = true;
            //            application.GamePadButtonUpdate += new CCGamePadButtonDelegate(application_GamePadButtonUpdate);
            //#endif
        }
示例#8
0
文件: Static.cs 项目: anurse/gate
        public Static(AppDelegate app, string root = null, IEnumerable<string> urls = null)
        {
            this.app = app;

            if (root == null)
            {
                root = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "public");
            }

            if (!Directory.Exists(root))
            {
                throw new DirectoryNotFoundException(string.Format("Invalid root directory: {0}", root));
            }

            if (urls == null)
            {
                var rootDirectory = new DirectoryInfo(root);
                var files = rootDirectory.GetFiles("*").Select(fi => "/" + fi.Name);
                var directories = rootDirectory.GetDirectories().Select(di => "/" + di.Name);
                urls = files.Concat(directories);
            }

            this.urls = urls;

            fileServer = new FileServer(root);
        }
示例#9
0
文件: Startup.cs 项目: dragan/gate
        static AppDelegate App(AppDelegate arg)
        {
            return call =>
            {
                ResultParameters result = new ResultParameters()
                {
                    Status = 200,
                    Headers = new Dictionary<string, string[]>(StringComparer.OrdinalIgnoreCase) { { "Content-Type", new[] { "text/plain" } } },
                    Properties = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase),
                    Body = stream =>
                    {
                        var bytes = Encoding.Default.GetBytes("This is a custom page");
                        stream.Write(bytes, 0, bytes.Length);

                        TaskCompletionSource<object> bodyTcs = new TaskCompletionSource<object>();
                        bodyTcs.TrySetResult(null);
                        return bodyTcs.Task;
                    }
                };

                TaskCompletionSource<ResultParameters> requestTcs = new TaskCompletionSource<ResultParameters>();
                requestTcs.TrySetResult(result);
                return requestTcs.Task;
            };
        }
示例#10
0
        public static IDisposable Create(AppDelegate app, int port, TextWriter output)
        {
            app = ExecutionContextPerRequest.Middleware(app);
            var endPoint = new IPEndPoint(IPAddress.Any, port);

            var schedulerDelegate = new NullSchedulerDelegate(output);
            var scheduler = KayakScheduler.Factory.Create(schedulerDelegate);

            var context = new Dictionary<string, object>
            {
                {"gate.Output", output},
            };
            var channel = new GateRequestDelegate(app, context);

            var server = KayakServer.Factory.CreateHttp(channel, scheduler);
            var listen = server.Listen(endPoint);

            var thread = new Thread(_ => scheduler.Start());
            thread.Start();

            return new Disposable(() =>
            {
                scheduler.Stop();
                thread.Join(5000);
                listen.Dispose();
                server.Dispose();
            });
        }
示例#11
0
 public Connection(IServerTrace trace, AppDelegate app, ISocket socket, Action<ISocket> disconnected)
 {
     _trace = trace;
     _app = app;
     _socket = socket;
     _disconnected = disconnected;
 }
示例#12
0
 public Connection(IFireflyService services, AppDelegate app, ISocket socket, Action<ISocket> disconnected)
 {
     _services = services;
     _app = app;
     _socket = socket;
     _socketSender = new SocketSender(_services, _socket);
     _disconnected = disconnected;
 }
示例#13
0
        public static void Start(ISchedulerDelegate schedulerDelegate, IPEndPoint listenEP, AppDelegate app, IDictionary<string, object> context)
        {
            var scheduler = KayakScheduler.Factory.Create(schedulerDelegate);
            var server = KayakServer.Factory.CreateGate(app, scheduler, context);

            using (server.Listen(listenEP))
                scheduler.Start();
        }
示例#14
0
        public static AppDelegate Middleware(AppDelegate app)
        {
            return call =>
            {
                Action<Exception, Action<byte[]>> showErrorMessage =
                    (ex, write) =>
                        ErrorPage(call, ex, text =>
                        {
                            var data = Encoding.ASCII.GetBytes(text);
                            write(data);
                        });

                Func<Exception, Task<ResultParameters>> showErrorPage = ex =>
                {
                    var response = new Response() { Status = "500 Internal Server Error", ContentType = "text/html" };
                    showErrorMessage(ex, data => response.Write(data));
                    return response.EndAsync();
                };

                try
                {
                    return app(call)
                        .Then(result =>
                        {
                            if (result.Body != null)
                            {
                                var nestedBody = result.Body;
                                result.Body = stream =>
                                {
                                    try
                                    {
                                        return nestedBody(stream).Catch(
                                            errorInfo =>
                                            {
                                                showErrorMessage(errorInfo.Exception, data => stream.Write(data, 0, data.Length));
                                                return errorInfo.Handled();
                                            });
                                    }
                                    catch (Exception ex)
                                    {
                                        showErrorMessage(ex, data => stream.Write(data, 0, data.Length));
                                        return TaskHelpers.Completed();
                                    }
                                };
                            }
                            return result;
                        })
                        .Catch(errorInfo =>
                        {
                            return errorInfo.Handled(showErrorPage(errorInfo.Exception).Result);
                        });
                }
                catch (Exception exception)
                {
                    return showErrorPage(exception);
                }
            };
        }
示例#15
0
文件: ErrorPage.cs 项目: ArloL/gate
        public static AppDelegate Middleware(AppDelegate app, Action<Exception> logError)
        {
            return (env, result, fault) =>
            {
                Action<Exception> onError = ex =>
                {
                    logError(ex);
                    result(
                        "500 Internal Server Error",
                        ResponseHeaders,
                        (write, end, cancel) =>
                        {
                            try
                            {
                                write(Body, null);
                                end(null);
                            }
                            catch (Exception error)
                            {
                                end(error);
                            }
                        });
                };

                try
                {
                    app(
                        env,
                        (status, headers, body) =>
                        {
                            // errors send from inside the body are
                            // logged, but not passed to the host. it's too
                            // late to change the status or send an error page.
                            onError = logError;
                            result(
                                status,
                                headers,
                                (write, end, cancel) =>
                                    body(
                                        write,
                                        ex =>
                                        {
                                            if (ex != null)
                                            {
                                                logError(ex);
                                            }
                                            end(ex);
                                        },
                                        cancel));
                        },
                        ex => onError(ex));
                }
                catch (Exception ex)
                {
                    onError(ex);
                }
            };
        }
示例#16
0
文件: Cascade.cs 项目: dragan/gate
        public static AppDelegate Middleware(AppDelegate app, IEnumerable<AppDelegate> apps)
        {
            // sequence to attempt is {apps[0], apps[n], app}
            // or {apps[0], apps[n]} if app is null
            apps = (apps ?? new AppDelegate[0]).Concat(new[] { app ?? NotFound.Call }).ToArray();

            // the first non-404 result will the the one to take effect
            // any subsequent apps are not called
            return call =>
            {
                var iter = apps.GetEnumerator();
                iter.MoveNext();

                TaskCompletionSource<ResultParameters> tcs = new TaskCompletionSource<ResultParameters>();

                Action loop = () => { };
                loop = () =>
                {
                    var threadId = Thread.CurrentThread.ManagedThreadId;
                    for (var hot = true; hot; )
                    {
                        hot = false;
                        iter.Current.Invoke(call)
                            .Then(result =>
                            {
                                if (result.Status == 404 && iter.MoveNext())
                                {
                                    // ReSharper disable AccessToModifiedClosure
                                    if (threadId == Thread.CurrentThread.ManagedThreadId)
                                    {
                                        hot = true;
                                    }
                                    else
                                    {
                                        loop();
                                    }
                                    // ReSharper restore AccessToModifiedClosure
                                }
                                else
                                {
                                    tcs.TrySetResult(result);
                                }
                            })
                            .Catch(errorInfo =>
                            {
                                tcs.TrySetException(errorInfo.Exception);
                                return errorInfo.Handled();
                            });
                    }
                    threadId = 0;
                };

                loop();

                return tcs.Task;
            };
        }
示例#17
0
文件: UrlMapper.cs 项目: anurse/gate
        public static AppDelegate Create(AppDelegate app, IDictionary<string, AppDelegate> map)
        {
            if (app == null)
                throw new ArgumentNullException("app");

            var mapper = new UrlMapper(app);
            mapper.Remap(map);
            return mapper.Call;
        }
示例#18
0
 static AppDelegate Middleware(AppDelegate app)
 {
     return (env, result, fault) =>
     {
         var owin = new Environment(env);
         owin.Body = Wrap(owin.Body);
         app(env, result, fault);
     };
 }
示例#19
0
        public FFTBufferManager(int maxFPS, AppDelegate appDelegate)
        {
            this.appDelegate = appDelegate;
            this.maxFPS = maxFPS;

            mAudioBufferSize = maxFPS;
            NeedsNewAudioData = true;
            mAudioBuffer = new int[mAudioBufferSize];
        }
示例#20
0
        public Listener(IPEndPoint listeningEndpoint, ISchedulerDelegate schedulerDelegate)
        {
            _listeningEndpoint = listeningEndpoint;
            _schedulerDelegate = schedulerDelegate;
            _applicationDelegate = AppBuilder.BuildConfiguration(x => RunExtensions.Run(x.RescheduleCallbacks(), _host.ExecuteRequest));

            _scheduler = KayakScheduler.Factory.Create(_schedulerDelegate);
            _server = KayakServer.Factory.CreateGate(_applicationDelegate, _scheduler, null);
        }
示例#21
0
文件: Cascade.cs 项目: anurse/gate
        public static AppDelegate Middleware(AppDelegate app, IEnumerable<AppDelegate> apps)
        {
            // sequence to attempt is {apps[0], apps[n], app}
            // or {apps[0], apps[n]} if app is null
            apps = (apps ?? new AppDelegate[0]).Concat(new[] { app ?? NotFound.Call }).ToArray();

            // the first non-404 result will the the one to take effect
            // any subsequent apps are not called
            return (call, callback) =>
            {
                var iter = apps.GetEnumerator();
                iter.MoveNext();

                Action loop = () => { };
                loop = () =>
                {
                    var threadId = Thread.CurrentThread.ManagedThreadId;
                    for (var hot = true; hot; )
                    {
                        hot = false;
                        iter.Current.Invoke(
                            call,
                            (result, error) =>
                            {
                                try
                                {
                                    if (result.Status == 404 && iter.MoveNext())
                                    {
                                        // ReSharper disable AccessToModifiedClosure
                                        if (threadId == Thread.CurrentThread.ManagedThreadId)
                                        {
                                            hot = true;
                                        }
                                        else
                                        {
                                            loop();
                                        }
                                        // ReSharper restore AccessToModifiedClosure
                                    }
                                    else
                                    {
                                        callback(result, error);
                                    }
                                }
                                catch (Exception ex)
                                {
                                    callback(default(ResultParameters), ex);
                                }
                            });
                    }
                    threadId = 0;
                };

                loop();
            };
        }
示例#22
0
 public Frame(AppDelegate app, Func<ArraySegment<byte>, Action, bool> produceData, Action<bool> produceEnd)
 {
     _app = app;
     _produceData = produceData;
     _produceEnd = () =>
     {
         if (!_messageBody.Drain(() => produceEnd(_keepAlive)))
             produceEnd(_keepAlive);
     };
 }
示例#23
0
        public static IServer CreateGate(this IServerFactory factory, AppDelegate app, IScheduler scheduler, IDictionary<string, object> context)
        {
            if (context == null)
                context = new Dictionary<string, object>();

            if (!context.ContainsKey("kayak.Scheduler"))
                context["kayak.Scheduler"] = scheduler;

            return factory.CreateHttp(new GateRequestDelegate(app, context), scheduler);
        }
示例#24
0
 public static AppDelegate LogToConsole(AppDelegate app)
 {
     return
         (env, result, fault) =>
         {
             var req = new Request(env);
             Console.WriteLine(req.Method + " " + req.PathBase + req.Path);
             app(env, result, fault);
         };
 }
示例#25
0
        public static AppDelegate Middleware(AppDelegate app)
        {
            return (call, callback) =>
            {
                Action<Exception, Action<ArraySegment<byte>>> showErrorMessage =
                    (ex, write) =>
                        ErrorPage(call, ex, text =>
                        {
                            var data = Encoding.ASCII.GetBytes(text);
                            write(new ArraySegment<byte>(data));
                        });

                Action<Exception> showErrorPage = ex =>
                {
                    var response = new Response(callback) { Status = "500 Internal Server Error", ContentType = "text/html" };
                    response.Start(() =>
                    {
                        showErrorMessage(ex, data => response.Write(data));
                        response.End();
                    });
                };

                try
                {
                    app(call, (result, error) =>
                    {
                        if (error != null)
                        {
                            showErrorPage(error);
                        }
                        else
                        {
                            var body = result.Body;
                            result.Body = (write, end, cancel) =>
                            {
                                showErrorPage = ex =>
                                {
                                    if (ex != null)
                                    {
                                        showErrorMessage(ex, data => write(data, null));
                                    }
                                    end(null);
                                };
                                body.Invoke(write, showErrorPage, cancel);
                            };
                            callback(result, null);
                        }
                    });
                }
                catch (Exception exception)
                {
                    showErrorPage(exception);
                }
            };
        }
示例#26
0
文件: Startup.cs 项目: ArloL/gate
 static AppDelegate App(AppDelegate arg)
 {
     return (env, result, fault) => result("200 OK",
         new Dictionary<string, string[]>(StringComparer.OrdinalIgnoreCase) { { "Content-Type", new[] { "text/plain" } } },
         (write, end, cancel) =>
         {
             var bytes = Encoding.Default.GetBytes("This is a custom page");
             write(new ArraySegment<byte>(bytes), null);
             end(null);
         });
 }
示例#27
0
        public static AppDelegate Middleware(AppDelegate app)
        {
            return (env, result, fault) =>
            {
                Action<Exception, Action<ArraySegment<byte>>> showErrorMessage =
                    (ex, write) =>
                        ErrorPage(env, ex, text =>
                        {
                            var data = Encoding.ASCII.GetBytes(text);
                            write(new ArraySegment<byte>(data));
                        });

                Action<Exception> showErrorPage = ex =>
                {
                    var response = new Response(result) { Status = "500 Internal Server Error", ContentType = "text/html" };
                    response.Start(() =>
                    {
                        showErrorMessage(ex, data => response.Write(data));
                        response.End();
                    });
                };

                try
                {
                    app(
                        env,
                        (status, headers, body) =>
                            result(
                                status,
                                headers,
                                (write, flush, end, token) =>
                                {
                                    showErrorPage = ex =>
                                    {
                                        if (ex != null)
                                        {
                                            showErrorMessage(ex, data => write(data));
                                        }
                                        end(null);
                                    };
                                    body(
                                        write,
                                        flush,
                                        showErrorPage,
                                        token);
                                }),
                        ex => showErrorPage(ex));
                }
                catch (Exception exception)
                {
                    showErrorPage(exception);
                }
            };
        }
示例#28
0
        public static AppDelegate Middleware(AppDelegate app)
        {
            return (env, result, fault) =>
            {
                var req = new Request(env);
                string method;
                if (req.Headers.TryGetValue("x-http-method-override", out method))
                    req.Method = method;

                app(env, result, fault);
            };
        }
示例#29
0
        public static AppDelegate Middleware(AppDelegate app)
        {
            return call =>
            {
                var req = new Request(call);
                var method = req.Headers.GetHeader("x-http-method-override");
                if (!string.IsNullOrWhiteSpace(method))
                    req.Method = method;

                return app(call);
            };
        }
示例#30
0
 public static AppDelegate Middleware(AppDelegate app, string contentType)
 {
     return (env, result, fault) => app(
         env,
         (status, headers, body) =>
         {
             if (!headers.Any(kv => string.Equals(kv.Key, "Content-Type", StringComparison.OrdinalIgnoreCase)))
                 headers.Add("Content-Type", contentType);
             result(status, headers, body);
         },
         fault);
 }
示例#31
0
 public MainWindowAdapter(AppDelegate appDelegate) : base("MainWindow")
 {
     this.appDelegate = appDelegate;
 }
示例#32
0
 protected override void OnStartup(StartupEventArgs e)
 {
     appDelegate = new AppDelegate();
     appDelegate.start();
 }
示例#33
0
    ///----------------------------------------------------------------------------------------------
    /// <summary>
    /// 更新完成处理
    /// </summary>
    ///----------------------------------------------------------------------------------------------
    private void OnUpdateComplete( )
    {
        AppDelegate pCompent = gameObject.AddComponent <AppDelegate>() as AppDelegate;

        mComplete = true;
    }
示例#34
0
 public static void Run(AppDelegate app)
 {
     _app = app;
 }
示例#35
0
 public LoginService(AppDelegate appDelegate)
 {
     _appDelegate = appDelegate;
 }
示例#36
0
 public void StopSession()
 {
     AppDelegate.GetInstance().StopListening();
 }
示例#37
0
 public RootPresenter(UIWindow window, AppDelegate appDelegate) : base(window, appDelegate)
 {
 }
示例#38
0
        public IDisposable Create(AppDelegate app, EndPoint endpoint)
        {
            _services.Trace.Event(TraceEventType.Start, TraceMessage.ServerFactory);

            var listenSocket = new Socket(endpoint.AddressFamily, SocketType.Stream, ProtocolType.IP);

            listenSocket.Bind(endpoint);
            listenSocket.Listen(-1);

            WaitCallback connectionExecute = connection =>
            {
                _services.Trace.Event(TraceEventType.Verbose, TraceMessage.ServerFactoryConnectionExecute);
                ((Connection)connection).Execute();
            };

            var    stop        = false;
            var    acceptEvent = new SocketAsyncEventArgs();
            Action accept      = () =>
            {
                while (!stop)
                {
                    _services.Trace.Event(TraceEventType.Verbose, TraceMessage.ServerFactoryAcceptAsync);

                    if (listenSocket.AcceptAsync(acceptEvent))
                    {
                        return;
                    }

                    _services.Trace.Event(TraceEventType.Verbose, TraceMessage.ServerFactoryAcceptCompletedSync);

                    if (acceptEvent.SocketError != SocketError.Success)
                    {
                        _services.Trace.Event(TraceEventType.Error, TraceMessage.ServerFactoryAcceptSocketError);
                    }

                    if (acceptEvent.SocketError == SocketError.Success &&
                        acceptEvent.AcceptSocket != null)
                    {
                        ThreadPool.QueueUserWorkItem(
                            connectionExecute,
                            new Connection(
                                _services,
                                app,
                                new SocketWrapper(acceptEvent.AcceptSocket),
                                OnDisconnect));
                    }
                    acceptEvent.AcceptSocket = null;
                }
            };

            acceptEvent.Completed += (_, __) =>
            {
                _services.Trace.Event(TraceEventType.Verbose, TraceMessage.ServerFactoryAcceptCompletedAsync);

                if (acceptEvent.SocketError == SocketError.Success &&
                    acceptEvent.AcceptSocket != null)
                {
                    ThreadPool.QueueUserWorkItem(
                        connectionExecute,
                        new Connection(
                            _services,
                            app,
                            new SocketWrapper(acceptEvent.AcceptSocket),
                            OnDisconnect));
                }
                acceptEvent.AcceptSocket = null;
                accept();
            };
            accept();

            return(new Disposable(
                       () =>
            {
                _services.Trace.Event(TraceEventType.Stop, TraceMessage.ServerFactory);

                stop = true;
                listenSocket.Close();
                acceptEvent.Dispose();
            }));
        }
示例#39
0
        public IDisposable Create(AppDelegate app, int port, string hostname)
        {
            var ipAddress = Dns.GetHostAddresses(hostname).First();

            return(Create(app, new IPEndPoint(ipAddress, port)));
        }
示例#40
0
 public IDisposable Create(AppDelegate app, int port)
 {
     return(Create(app, new IPEndPoint(IPAddress.Any, port)));
 }
示例#41
0
        public SearchForm(RootElement _root, SearchRequest req = null) : base(new RootElement("Root"), true)
        {
            Root      = (_root != null) ? _root : GetRoot("root");
            searchReq = (req == null) ? new SearchRequest() : req;

            AppDelegate app = (AppDelegate)UIApplication.SharedApplication.Delegate;

            TableView.AutoresizingMask = UIViewAutoresizing.None;
            service         = app.searchService;
            yearsList       = service.GetYearList();
            maxPriceList    = service.GetMaxPricelist();
            minPriceList    = service.GetMinPricelist();
            minDistanceList = service.GetMinDistancelist();
            maxDistanceList = service.GetMaxDistancelist();
            maxPriceList    = service.GetMaxDistancelist();

            //TODO add to storage
            if (colors == null)
            {
                colors = service.GetColors();
                //colors = task.Result;
            }

            Name = new EntryElement("Name", "Create Search Name", string.Empty);
            Name.ReturnKeyType = UIReturnKeyType.Done;
            Name.ShouldReturn += () => {
                Name.ResignFirstResponder(true);
                return(true);
            };
            //Name.ShouldReturn
            Name.EntryEnded += (s, e) => {
                searchReq.name = Name.Value;
                //this.View.EndEditing(true);
            };

            Type              = GetSearchType();
            Model             = GetCarModel();
            Make              = GetCarMake();
            Zip               = new EntryElement("Zip", "Postal Code", string.Empty);
            Distance          = GetDistance();
            Trim              = GetTrim();
            Exterior          = GetExterior();
            Interior          = GetInterior();
            Seller            = GetSeller();
            SearchAuctions    = new BooleanElement("Search Auctions", true);
            SendNotifications = new BooleanElement("Send Notifications", true);

            SendNotifications.ValueChanged += (sender, e) => {
                searchReq.notify = SendNotifications.Value;
                if (this.RequestUpdated != null)
                {
                    this.RequestUpdated(this, new PostDataEvent {
                        Data = searchReq
                    });
                }
            };

            SearchAuctions.ValueChanged += (sender, e) => {
                searchReq.auctions = SearchAuctions.Value;
                if (this.RequestUpdated != null)
                {
                    this.RequestUpdated(this, new PostDataEvent {
                        Data = searchReq
                    });
                }
            };


            //header footer view for sections
            Header = GetHeader();
            Footer = GetFooter();

            View.BackgroundColor = UIColor.White;
        }
示例#42
0
        private void SetupLayout()
        {
            // Perform any additional setup after loading the view, typically from a nib.

            loginButton.TouchUpInside += (sender, e) =>
            {
                if (UserData.IsUserLoggedIn)
                {
                    LogOffUser();
                }
                else
                {
                    var userCprInput = userNameTextField.Text;
                    // If user cpr nr is valid
                    if (ValidateCpr(userCprInput))
                    {
                        new System.Threading.Thread(() =>
                        {
                            // Send cpr til web api for yderligere validering (er patient indlagt/udskrevet?)
                            // Hvis Response kode er OK betyder det er patient er indlagt og ikke udskrevet endnu

                            try
                            {
                                var manager = new LoginManager();
                                var cpr     = manager.GetPatient(userCprInput);

                                if (cpr == null)
                                {
                                    throw new Exception(Strings.ErrorPatientNotValid);
                                }
                            }
                            // Response kode er forskellig fra OK, hvilket kan betyde en netværksfejl eller at patient ikke er indlagt (antager vi).
                            catch (Exception ex)
                            {
                                Console.WriteLine("Login failed with error: " + ex.Message);

                                this.InvokeOnMainThread(() =>
                                {
                                    var errorMessage = ex.Message.Equals(Strings.ErrorPatientNotValid) ? Strings.ErrorPatientNotValid : Strings.ErrorNoNetwork;

                                    new UIAlertView(Strings.ErrorLogin, errorMessage, null, null, "OK").Show();
                                });

                                // Fortsæt ikke programmet, hvis login fejlede
                                return;
                            }


                            // Skriv evt. en besked til bruger om at login gik OK
                            this.InvokeOnMainThread(() =>
                            {
                                // Show the overlay (loading screen)
                                AppDelegate.ShowLoadingScreen(this, Strings.SpinnerDataReading);
                            });

                            // Hent kategorier for den pågældende patient/afdeling/sygehus
                            try
                            {
                                Categories = DataHandler.LoadCategoriesFromWeb();
                                //Categories = DataHandler.LoadCategoriesTESTDATA();

                                // Delete categories from web
                                DataHandler.DeleteCategoriesFromLocalDatabase(new LocalDB());

                                // If data loading from web not succeded, nothing will be saved to the local database (Categories instance will be null)
                                DataHandler.SaveCategoriesToLocalDatabase(new LocalDB(), Categories);
                            }
                            // Mislykkedes at hente kategorier fra web, indlæser fra lokal database (i næste view)
                            catch (Exception ex)
                            {
                                Console.WriteLine("ERROR loading data: " + ex.Message + "...loading from local database");

                                this.InvokeOnMainThread(() =>
                                {
                                    new UIAlertView(Strings.Error, Strings.ErrorReading, null, Strings.OK, null).Show();
                                });
                            }

                            this.InvokeOnMainThread(() =>
                            {
                                // Login user
                                LoginInUser();
                                // Hide the overlay (loading screen)
                                AppDelegate.loadingOverlay.Hide();

                                // Go to valgmuligheder
                                GoToCategories();
                            });
                        }).Start();
                    }
                }
            };

            this.userNameTextField.ShouldReturn += (textField) =>
            {
                textField.ResignFirstResponder();
                return(true);
            };
        }
示例#43
0
 private void ToggleSoundCallBack(Toggle toggleSound) => AppDelegate.SharedManager().SetSoundStatus(toggleSound.isOn);
示例#44
0
 private void ToggleVibrationCallBack(Toggle toggleVibration) => AppDelegate.SharedManager().SetSoundStatus(toggleVibration.isOn);
示例#45
0
 public EmailProvider(ApplicationSettings settings, AppDelegate application)
 {
     _settings    = settings;
     _application = application;
 }
示例#46
0
 public NavigationPresenter(UIWindow window, AppDelegate appDelegate) : base(window, appDelegate)
 {
 }
示例#47
0
 public Stream GetDummyStream()
 {
     return(AppDelegate.GetStream());
 }
示例#48
0
        public void Initialize(IList <string> args, bool isDocumentApp)
        {
            Console.CancelKeyPress += (sender, e) => Exit(0);

            NSApplication.Init();

            _dispatcher = _dispatcher ?? new Dispatcher(Thread.CurrentThread);
            Fusion.Application.MainThread = _dispatcher;

            Fusion.Application.PerFrame = Observable.Interval(
                TimeSpan.FromSeconds(1.0 / 60.0),
                new SynchronizationContextScheduler(SynchronizationContext.Current));

            var app = new AppDelegate(isDocumentApp);

            NSApplication.SharedApplication.Delegate = app;

            //TODO do we really need to retain this object?
                        #pragma warning disable 0219
            var documentController = new NSDocumentController();
                        #pragma warning restore 0219

            NSApplication.CheckForIllegalCrossThreadCalls = false;
            AppDelegate.ThrowOnTerminate = false;

            Desktop = new MacDialog <object>();

            EffectsImplementation.Initialize(_dispatcher);

            // Make so that the window popups with focus.
            NSApplication.SharedApplication.ActivateIgnoringOtherApps(true);

            MacEnvironment.Initialize(new MacEnvironmentImpl());
            DraggingImplementation.Initialize(_dispatcher);
            MenuBuilder.Initialize(_dispatcher);
            LayeringImplementation.Initialize(_dispatcher);
            LabelImplementation.Initialize(_dispatcher);
            SliderImplementation.Initialize(_dispatcher);
            LineImplementation.Initialize(_dispatcher);
            CircleImplementation.Initialize(_dispatcher);
            RectangleImplementation.Initialize(_dispatcher);
            TextBoxImplementation.Initialize(_dispatcher);
            CursorsImplementation.Initialize(_dispatcher);
            ToolTipImplementation.Initialize(_dispatcher);
            ContextMenuImplementation.Initialize(_dispatcher);
            DropDownImplementation.Initialize(_dispatcher);
            ButtonImplementation.Initialize(_dispatcher);
            ColorPickerImplementation.Initialize(_dispatcher);
            ScrollingImplementation.Initialize(_dispatcher);
            LogViewImplementation.Initialize(_dispatcher);
            Transformation.Initialize();
            ImageImplementation.Initialize(_dispatcher);
            OverlayImplementation.Initialize(_dispatcher);
            PointerImplementation.Initialize(_dispatcher);
            KeyboardImplementation.Initialize(_dispatcher);
            WebViewImplementation.Initialize(_dispatcher);
            LayoutTrackerImplementation.Initialize();
            FileDialogs.Initialize();

            // TODO: Fix this!!!
            Clipping.Initialize((control, clip) => control);

            // This notification occurs a _lot_, but is the most specific one I was able to find that would
            //  allow us to be notified when the first responder changes consistently
            NSNotificationCenter.DefaultCenter.AddObserver(new NSString("NSApplicationDidUpdateNotification"), _ => {
                var keyWindow = NSApplication.SharedApplication.KeyWindow;
                _firstResponder.OnNext(keyWindow != null ? keyWindow.FirstResponder : null);
            });

            app.Terminates.Subscribe(_ =>
            {
                if (Terminating != null)
                {
                    Terminating();
                }
            });

            EditMenu =

                /*CreateFirstResponderMenuItem(name: "Undo", hotkey: HotKey.Create(Fusion.ModifierKeys.Meta, Key.Z), selectorName: "undo:")
                 + CreateFirstResponderMenuItem(name: "Redo", hotkey: HotKey.Create(Fusion.ModifierKeys.Meta | Fusion.ModifierKeys.Shift, Key.Z), selectorName: "redo:")
                 + MenuItem.CreateSeparator()
                 + */CreateFirstResponderMenuItem(name: "Cut", hotkey: HotKey.Create(Fusion.ModifierKeys.Meta, Key.X), selectorName: "cut:")
                + CreateFirstResponderMenuItem(name: "Copy", hotkey: HotKey.Create(Fusion.ModifierKeys.Meta, Key.C), selectorName: "copy:")
                + CreateFirstResponderMenuItem(name: "Paste", hotkey: HotKey.Create(Fusion.ModifierKeys.Meta, Key.V), selectorName: "paste:")
                + CreateFirstResponderMenuItem(name: "Paste and Match Style", hotkey: HotKey.Create(Fusion.ModifierKeys.Meta | Fusion.ModifierKeys.Shift, Key.V), selectorName: "pasteAsPlainText:")
                + CreateFirstResponderMenuItem(name: "Delete", hotkey: HotKey.Create(Fusion.ModifierKeys.Meta, Key.Backspace), selectorName: "delete:")
                + CreateFirstResponderMenuItem(name: "Select All", hotkey: HotKey.Create(Fusion.ModifierKeys.Meta, Key.A), selectorName: "selectAll:");
        }
示例#49
0
 public ModalCardPresenter(UIWindow window, AppDelegate appDelegate) : base(window, appDelegate)
 {
 }
 public bool SetAlarmAt(string medicineName, TimeSpan medicationTime)
 {
     App.AppLogger.D($"Medicine Name: {medicineName}, Medication Time {medicationTime}");
     AppDelegate.SendNotification(medicineName, medicationTime);
     return(true);
 }
        public string IsNetworkAvailable()
        {
            AppDelegate appDelegate = new AppDelegate();

            return(appDelegate.updateStatus());
        }
示例#52
0
        //private readonly GraphicsDeviceManager graphics;

        public Game1()
        {
            CCApplication application = new AppDelegate(this);

            Components.Add(application);
        }
示例#53
0
文件: Handler.cs 项目: ikvm/crosswalk
 public Handler(AppDelegate app)
 {
     _app = app;
 }
 private void ClkHandlerLoadSavedGame(object sender, EventArgs args)
 {
     AppDelegate.LoadSavedGame();
     System.Diagnostics.Debug.WriteLine("inside BtnClkHandlerLoadSavedGame");
 }
示例#55
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            AppDelegate app = UIApplication.SharedApplication.Delegate as AppDelegate;

            //this.NavigationItem.TitleView = CreateNavTitle (PostViewModel.Post.FirstCategoryName);

            this.NavigationController.NavigationBarHidden = false;

            this.NavigationItem.SetLeftBarButtonItem(
                new UIBarButtonItem(UIImage.FromBundle("back")
                                    , UIBarButtonItemStyle.Plain
                                    , (sender, args) => {
                this.NavigationController.NavigationBarHidden = true;
                PostViewModel.BackCommand.Execute(null);
            }), true);



            this.webViewPost.ScrollView.Delegate = this;
//			this.NavigationItem.SetRightBarButtonItem(
//				new UIBarButtonItem(UIImage.FromBundle("comment")
//					, UIBarButtonItemStyle.Plain
//					, (sender, args) => {
//						PostViewModel.ShowCommentCommand.Execute(null);
//
//					}), true);
//
//			this.NavigationItem.SetRightBarButtonItem(
//				new UIBarButtonItem(UIImage.FromBundle("comment")
//					, UIBarButtonItemStyle.Plain
//					, (sender, args) => {
//						PostViewModel.ShowCommentCommand.Execute(null);
//
//					}), true);

            // Perform any additional setup after loading the view, typically from a nib.
            this.CreateBindingSet <PostView, PostViewModel>().Bind(this).For(v => v.IsLikedThisPost).To(vm => vm.IsLikedThisPost).Apply();

            this.CreateBindingSet <PostView, PostViewModel>().Bind(this).For(v => v.Html).To(vm => vm.Html).Apply();
            this.CreateBinding(lbLikeCount).For("Text").To <PostViewModel> (vm => vm.Like_count).Apply();
            this.CreateBinding(lbCommentCount).For("Text").To <PostViewModel> (vm => vm.Comment_count).Apply();

            this.CreateBinding(btnCommentBottom).For("TouchUpInside").To <PostViewModel> (vm => vm.ShowCommentCommand).Apply();
            this.CreateBinding(lbCommentCount).For("Tap").To <PostViewModel> (vm => vm.ShowCommentCommand).Apply();
            this.CreateBinding(lbCommentBotom).For("Tap").To <PostViewModel> (vm => vm.ShowCommentCommand).Apply();

            this.CreateBinding(btnLike).For("TouchUpInside").To <PostViewModel> (vm => vm.LikeCommand).Apply();
            this.CreateBinding(btnUnlike).For("TouchUpInside").To <PostViewModel> (vm => vm.UnLikeCommand).Apply();

            this.CreateBinding(pgrLoading).For("Hidden").To <PostViewModel> (vm => vm.IsLoading).WithConversion("Visibility").Apply();
            this.CreateBinding(btnLike).For("Hidden").To <PostViewModel> (vm => vm.IsUnLikedThisPost).WithConversion("Visibility").Apply();
            this.CreateBinding(btnUnlike).For("Hidden").To <PostViewModel> (vm => vm.IsLikedThisPost).WithConversion("Visibility").Apply();


            webViewPost.ShouldStartLoad = (w, urlRequest, navigationType) => {
                if (navigationType == UIWebViewNavigationType.LinkClicked)
                {
                    UIApplication.SharedApplication.OpenUrl(urlRequest.Url);
                    return(false);
                }
                return(true);
            };
            //webViewPost.LoadHtmlString ();
            PostViewModel.LoadPost();

            Relayout();
        }
 public void UnregisterPush()
 {
     AppDelegate.UnregisterPushNotifications();
 }
示例#57
0
 public PageSheetPresenter(UIWindow window, AppDelegate appDelegate) : base(window, appDelegate)
 {
 }
 public void RegisterPush()
 {
     AppDelegate.RegisterNotifications();
 }
示例#59
0
 public void InitGamePanel()
 {
     txtLevelNo.gameObject.SetActive(true);
     txtLevelNo.text = "Level " + (AppDelegate.SharedManager().tempLevelCounter + 1).ToString();
 }
示例#60
0
        private async void OnStart()
        {
            output.WriteSplash();
            while (true)
            {
                historyProvider.Reset();
                output.WriteScopeBegin(hostEnv);
                string command = hostInput.ReadCommandLine();
                if (command == null)
                {
                    break;
                }
                IInputCollection inputCollection = Input.Internal.Input.Parse(command);
                if (inputCollection.ContainsError)
                {
                    output.WriteError(inputCollection.ErrorMessage);
                }
                else
                {
                    foreach (var desc in pool.GetDescriptors())
                    {
                        desc.EnterScope();
                    }

                    object      inputObject       = null;
                    int         index             = 0;
                    int         changeIndex       = inputCollection.Inputs.Count - 1;
                    bool        isInPipe          = inputCollection.Inputs.Count > 1;
                    bool        writeDefaultValue = !isInPipe;
                    HostContext context           = null;
                    foreach (IInput input in inputCollection.Inputs)
                    {
                        context = new HostContext(input, inputObject, isInPipe, index, writeDefaultValue);
                        AppDelegate app = appBuilder.Build();
                        await app(context);

                        if (context.ErrorOccured)
                        {
                            output.WriteError(context.Exception);
                            break;
                        }

                        if (context.WriteResult)
                        {
                            output.WriteObject(context.Result);
                        }
                        inputObject = context.Result;
                        if (inputObject != null)
                        {
                            inputObject = ObjectHelper.TryGetValue(inputObject);
                        }
                        index++;
                        if (index >= changeIndex)
                        {
                            writeDefaultValue = true;
                        }
                    }

                    foreach (var desc in pool.GetDescriptors())
                    {
                        desc.LeaveScope();
                    }
                }
                historyProvider.Add(inputCollection.Raw);
            }
        }