public override bool ProcessRequestAsync(IRequest request, ICallback callback) { Task.Run(() => { using (callback) { var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://samples.mplayerhq.hu/SWF/zeldaADPCM5bit.swf"); var httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse(); // Get the stream associated with the response. var receiveStream = httpWebResponse.GetResponseStream(); var mime = httpWebResponse.ContentType; var stream = new MemoryStream(); receiveStream.CopyTo(stream); httpWebResponse.Close(); //Reset the stream position to 0 so the stream can be copied into the underlying unmanaged buffer stream.Position = 0; //Populate the response values - No longer need to implement GetResponseHeaders (unless you need to perform a redirect) ResponseLength = stream.Length; MimeType = mime; StatusCode = (int)HttpStatusCode.OK; Stream = stream; callback.Continue(); } }); return true; }
//New: //To upgrade: store the response stream in a class field, then call callback.Continue() instead of the old `requestCompletedCallback`. //See here for example of new usage: https://github.com/cefsharp/CefSharp/blob/cefsharp/43/CefSharp.Example/CefSharpSchemeHandler.cs public bool ProcessRequestAsync(IRequest request, ICallback callback) { try { Task.Run(delegate { // Base to dispose of callback as it wraps a managed resource using (callback) { var u = new Uri(request.Url); var filepath = u.Authority + u.AbsolutePath; FileInfo = new FileInfo(filepath); // When processing complete call continue callback.Continue(); } }); return true; } catch { return false; } }
public bool ProcessRequestAsync(IRequest request, ICallback callback) { // The 'host' portion is entirely ignored by this scheme handler. var uri = new Uri(request.Url); var fileName = uri.AbsolutePath.Substring(1); // remove starting slash var resourceName = "CefSharpSample.EmbeddedResources." + fileName; if (AvailableFiles.Contains(resourceName)) { Task.Run(() => { using (callback) { stream = ResourceAssembly.GetManifestResourceStream(resourceName); var fileExtension = Path.GetExtension(fileName); mimeType = ResourceHandler.GetMimeType(fileExtension); callback.Continue(); } }); return true; } else { callback.Dispose(); } return false; }
public void open(JObject options, ICallback callback) { if (options != null) { var requestData = new RequestData { Title = options.Value<string>("title"), Text = options.Value<string>("share_text"), Url = options.Value<string>("share_URL"), }; if (requestData.Text == null && requestData.Title == null && requestData.Url == null) { return; } RunOnDispatcher(() => { lock (_queue) { _queue.Enqueue(requestData); } try { DataTransferManager.ShowShareUI(); callback.Invoke("OK"); } catch { callback.Invoke("not_available"); } }); } }
public bool ProcessRequestAsync(IRequest request, ICallback callback) { // The 'host' portion is entirely ignored by this scheme handler. var uri = new Uri(request.Url); var fileName = uri.AbsolutePath; string resource; if (ResourceDictionary.TryGetValue(fileName, out resource) && !string.IsNullOrEmpty(resource)) { Task.Run(() => { var bytes = Encoding.UTF8.GetBytes(resource); stream = new MemoryStream(bytes); var fileExtension = Path.GetExtension(fileName); mimeType = ResourceHandler.GetMimeType(fileExtension); callback.Continue(); }); return true; } return false; }
public bool ProcessRequestAsync(IRequest request, ICallback callback) { // The 'host' portion is entirely ignored by this scheme handler. var uri = new Uri(request.Url); var fileName = uri.AbsolutePath; var localFilePath = "./LocalFiles" + fileName; if (File.Exists(localFilePath)) { Task.Run(() => { using (callback) { stream = File.OpenRead(localFilePath); var fileExtension = Path.GetExtension(fileName); mimeType = ResourceHandler.GetMimeType(fileExtension); callback.Continue(); } }); return true; } else { callback.Dispose(); } return false; }
public static void TableState(ICallback to, GameTable table) { var conns = GetUsers(to); if (conns == null) return; Hub.Clients.Clients(conns).TableState(table); }
public static void PlayerMove(ICallback to, int userid, List<Guid> fromObject, Guid toObject, int shipsCount, int animationDuration) { var conns = GetUsers(to); if (conns == null) return; Hub.Clients.Clients(conns).PlayerMove(userid, fromObject, toObject, shipsCount, animationDuration); }
public void AddGeoFences( HashSet<GeoFence> geoFences, ICallback callback ) { if( fencesToCallback.Count != 0 ) throw new BackendlessException( ExceptionMessage.GEOFENCES_MONITORING ); foreach( GeoFence geoFence in geoFences ) AddGeoFence( geoFence, callback ); }
public SprocCall Sproc(FunctionName function, ICallback callback = null) { if (function == null) throw new ArgumentNullException(nameof(function)); var call = new SprocCall(this, function); AddCall(call, callback); return call; }
public async void FindServers(ICallback callback) { // Get the timeout value from the query string var result = await new ServerLocator(_logger).FindServers(1000).ConfigureAwait(false); var json = _json.SerializeToString(result); _stream = new MemoryStream(Encoding.UTF8.GetBytes(json)); callback.Continue(); }
public void Transceive(IList<MemoryStream> request, ICallback<IList<MemoryStream>> callback) { if (request == null) throw new ArgumentNullException("request"); try { IList<MemoryStream> response = Transceive(request); callback.HandleResult(response); } catch (IOException e) { callback.HandleException(e); } }
public void Encode(Packet obj, ICallback callback) { var log = LogManager.GetLogger(Global.CallerName()); log.Info(string.Format("encoding packet {0}", obj)); if (BINARY_EVENT == obj.Type || BINARY_ACK == obj.Type) { EncodeAsBinary(obj, callback); } else { String encoding = EncodeAsString(obj); callback.Call(new object[] { encoding }); } }
public void showAlert( JObject config, ICallback errorCallback, ICallback actionCallback) { var message = config.Value<string>("message") ?? ""; var messageDialog = new MessageDialog(message) { Title = config.Value<string>("title"), }; if (config.ContainsKey(DialogModuleHelper.KeyButtonPositive)) { messageDialog.Commands.Add(new UICommand { Label = config.Value<string>(DialogModuleHelper.KeyButtonPositive), Id = DialogModuleHelper.KeyButtonPositiveValue, Invoked = target => OnInvoked(target, actionCallback), }); } if (config.ContainsKey(DialogModuleHelper.KeyButtonNegative)) { messageDialog.Commands.Add(new UICommand { Label = config.Value<string>(DialogModuleHelper.KeyButtonNegative), Id = DialogModuleHelper.KeyButtonNegativeValue, Invoked = target => OnInvoked(target, actionCallback), }); } RunOnDispatcher(async () => { if (_isInForeground) { await messageDialog.ShowAsync().AsTask().ConfigureAwait(false); } else { _pendingDialog = messageDialog; } }); }
public bool ProcessRequestAsync(IRequest request, ICallback callback) { // The 'host' portion is entirely ignored by this scheme handler. var uri = new Uri(request.Url); var fileName = uri.AbsolutePath; if(string.Equals(fileName, "/PostDataTest.html", StringComparison.OrdinalIgnoreCase)) { var postDataElement = request.PostData.Elements.FirstOrDefault(); var resourceHandler = ResourceHandler.FromString("Post Data: " + (postDataElement == null ? "null" : postDataElement.GetBody())); stream = (MemoryStream)resourceHandler.Stream; mimeType = "text/html"; callback.Continue(); return true; } string resource; if (ResourceDictionary.TryGetValue(fileName, out resource) && !string.IsNullOrEmpty(resource)) { Task.Run(() => { using (callback) { var bytes = Encoding.UTF8.GetBytes(resource); stream = new MemoryStream(bytes); var fileExtension = Path.GetExtension(fileName); mimeType = ResourceHandler.GetMimeType(fileExtension); callback.Continue(); } }); return true; } else { callback.Dispose(); } return false; }
static IList<string> GetUsers(ICallback to, params ICallback[] exclude) { if (to == null) return null; var result = new List<string>(); var ignoreList = new List<string>(); exclude.ToList().ForEach(i1 => i1.ConnectionIDs.ForEach(ignoreList.Add)); foreach (var item in to.ConnectionIDs) { if (!ignoreList.Contains(item)) result.Add(item); } if (result.Count == 0) return null; return result; }
public void showAlert( JObject config, ICallback errorCallback, ICallback actionCallback) { var message = config.Value<string>("message") ?? ""; var title = config.Value<string>("title") ?? ""; bool containsTitle = config.ContainsKey("title"); bool containsPositive = config.ContainsKey(DialogModuleHelper.KeyButtonPositive); bool containsNegative = config.ContainsKey(DialogModuleHelper.KeyButtonNegative); if (containsPositive && containsNegative) { var result = MessageBox.Show(message, title, MessageBoxButton.OKCancel); if (result == MessageBoxResult.OK) { actionCallback.Invoke(DialogModuleHelper.ActionButtonClicked, DialogModuleHelper.KeyButtonPositiveValue); } else { actionCallback.Invoke(DialogModuleHelper.ActionButtonClicked, DialogModuleHelper.KeyButtonNegativeValue); } } else if (containsPositive) { var result = MessageBox.Show(message, title, MessageBoxButton.OK); if (result == MessageBoxResult.OK) { actionCallback.Invoke(DialogModuleHelper.ActionButtonClicked, DialogModuleHelper.KeyButtonPositiveValue); } } else if (containsTitle) { MessageBox.Show(message, title); } else { MessageBox.Show(message); } }
public bool ProcessRequestAsync(IRequest request, ICallback callback) { var uri = new Uri(request.Url); var fileName = uri.ToString().Substring(6); Uri u = ResourceHelper.GetResourceUri(fileName); if (u != null) { Task.Run(() => { using (callback) { try { StreamResourceInfo info = Application.GetResourceStream(u); byte[] buffer = new byte[info.Stream.Length]; info.Stream.Read(buffer, 0, buffer.Length); stream = new MemoryStream(buffer); var fileExtension = Path.GetExtension(fileName); mimeType = ResourceHandler.GetMimeType(fileExtension); callback.Continue(); } catch { //todo: unknown image } } }); return true; } else { callback.Dispose(); } return false; }
public bool ProcessRequestAsync(IRequest request, ICallback callback) { var uri = new Uri(request.Url); var file = uri.Authority + uri.AbsolutePath; if (!File.Exists(file)) return false; var bytes = File.ReadAllBytes(file); stream = new MemoryStream(bytes); switch (Path.GetExtension(file)) { case ".html": mimeType = "text/html"; break; case ".js": mimeType = "text/javascript"; break; case ".png": mimeType = "image/png"; break; case ".appcache": case ".manifest": mimeType = "text/cache-manifest"; break; case ".css": mimeType = "text/css"; break; default: mimeType = "application/octet-stream"; break; } callback.Continue(); return true; }
bool IResourceHandler.ProcessRequestAsync(IRequest request, ICallback callback) { Task.Run(() => { using (callback) { var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://samples.mplayerhq.hu/SWF/zeldaADPCM5bit.swf"); var httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse(); // Get the stream associated with the response. var receiveStream = httpWebResponse.GetResponseStream(); mime = httpWebResponse.ContentType; stream = new MemoryStream(); receiveStream.CopyTo(stream); httpWebResponse.Close(); callback.Continue(); } }); return true; }
public Redo(IRobotWare root, ICallback callback, IParameterManager mgr) : base(root, callback, mgr) { }
/// <summary> /// Invoked by React to create a new node with a given tag, class name and properties. /// </summary> /// <param name="config">the animation configuration properties.</param> /// <param name="success">Success callback.</param> /// <param name="error">Error callback.</param> public void ConfigureNextLayoutAnimation(JObject config, ICallback success, ICallback error) { _operationsQueue.EnqueueConfigureLayoutAnimation(config, success, error); }
/// <summary> /// Show a pop-up menu. /// </summary> /// <param name="reactTag"> /// The tag of the anchor view (the pop-up menu is displayed next to /// this view); this needs to be the tag of a native view (shadow views /// cannot be anchors). /// </param> /// <param name="items">The menu items as an array of strings.</param> /// <param name="error"> /// Callback used if there is an error displaying the menu. /// </param> /// <param name="success"> /// Callback used with the position of the selected item as the first /// argument, or no arguments if the menu is dismissed. /// </param> public void ShowPopupMenu(int reactTag, string[] items, ICallback error, ICallback success) { AssertViewExists(reactTag); _operationsQueue.EnqueueShowPopupMenu(reactTag, items, error, success); }
/// <summary> /// Read the request, then process it through the OWEN pipeline /// then populate the response properties. /// </summary> /// <param name="request">request</param> /// <param name="callback">callback</param> /// <returns>always returns true as we'll handle all requests this handler is registered for.</returns> public override CefReturnValue ProcessRequestAsync(IRequest request, ICallback callback) { // PART 1 - Read the request - here we read the request and create a dictionary // that follows the OWEN standard var responseStream = new MemoryStream(); var requestBody = Stream.Null; if (request.Method == "POST") { using (var postData = request.PostData) { if (postData != null) { var postDataElements = postData.Elements; var firstPostDataElement = postDataElements.First(); var bytes = firstPostDataElement.Bytes; requestBody = new MemoryStream(bytes, 0, bytes.Length); //TODO: Investigate how to process multi part POST data //var charSet = request.GetCharSet(); //foreach (var element in elements) //{ // if (element.Type == PostDataElementType.Bytes) // { // var body = element.GetBody(charSet); // } //} } } } //var cancellationTokenSource = new CancellationTokenSource(); //var cancellationToken = cancellationTokenSource.Token; var uri = new Uri(request.Url); var requestHeaders = ToDictionary(request.Headers); //Add Host header as per http://owin.org/html/owin.html#5-2-hostname requestHeaders.Add("Host", new[] { uri.Host + (uri.Port > 0 ? (":" + uri.Port) : "") }); //http://owin.org/html/owin.html#3-2-environment //The Environment dictionary stores information about the request, //the response, and any relevant server state. //The server is responsible for providing body streams and header collections for both the request and response in the initial call. //The application then populates the appropriate fields with response data, writes the response body, and returns when done. //Keys MUST be compared using StringComparer.Ordinal. var owinEnvironment = new Dictionary <string, object>(StringComparer.Ordinal) { //Request http://owin.org/html/owin.html#3-2-1-request-data { "owin.RequestBody", requestBody }, { "owin.RequestHeaders", requestHeaders }, { "owin.RequestMethod", request.Method }, { "owin.RequestPath", uri.AbsolutePath }, { "owin.RequestPathBase", "/" }, { "owin.RequestProtocol", "HTTP/1.1" }, //To conform to the OWIN spec we need to remove the leading '?' { "owin.RequestQueryString", string.IsNullOrEmpty(uri.Query) ? string.Empty : uri.Query.Substring(1) }, { "owin.RequestScheme", uri.Scheme }, //Response http://owin.org/html/owin.html#3-2-2-response-data { "owin.ResponseHeaders", new Dictionary <string, string[]>(StringComparer.OrdinalIgnoreCase) }, { "owin.ResponseBody", responseStream }, //Other Data { "owin.Version", "1.0.0" }, //{"owin.CallCancelled", cancellationToken} }; //PART 2 - Spawn a new task to execute the OWIN pipeline //We execute this in an async fashion and return true so other processing //can occur Task.Run(async() => { //Call into the OWEN pipeline try { await appFunc(owinEnvironment); //Response has been populated - reset the position to 0 so it can be read responseStream.Position = 0; int statusCode; if (owinEnvironment.ContainsKey("owin.ResponseStatusCode")) { statusCode = Convert.ToInt32(owinEnvironment["owin.ResponseStatusCode"]); //TODO: Improve status code mapping - see if CEF has a helper function that can be exposed //StatusText = StatusCodeToStatusTextMapping[response.StatusCode]; } else { statusCode = (int)HttpStatusCode.OK; //StatusText = "OK"; } //Grab a reference to the ResponseHeaders var responseHeaders = (Dictionary <string, string[]>)owinEnvironment["owin.ResponseHeaders"]; //Populate the response properties Stream = responseStream; ResponseLength = responseStream.Length; StatusCode = statusCode; if (responseHeaders.ContainsKey("Content-Type")) { var contentType = responseHeaders["Content-Type"].First(); MimeType = contentType.Split(';').First(); } else { MimeType = DefaultMimeType; } //Add the response headers from OWIN to the Headers NameValueCollection foreach (var responseHeader in responseHeaders) { //It's possible for headers to have multiple values foreach (var val in responseHeader.Value) { Headers.Add(responseHeader.Key, val); } } } catch (Exception ex) { int statusCode = (int)HttpStatusCode.InternalServerError; var responseData = GetByteArray("Error: " + ex.ToString(), System.Text.Encoding.UTF8, true); //Populate the response properties Stream = new MemoryStream(responseData); ResponseLength = responseData.Length; StatusCode = statusCode; MimeType = "text/html"; } //Once we've finished populating the properties we execute the callback //Callback wraps an unmanaged resource, so let's explicitly Dispose when we're done using (callback) { callback.Continue(); } }); return(CefReturnValue.ContinueAsync); }
protected internal override void Fx(int cell, ICallback callback) { MagicMissile.PurpleLight(CurUser.Sprite.Parent, CurUser.pos, cell, callback); Sample.Instance.Play(Assets.SND_ZAP); }
/// <summary> /// Вызов внутренней "магии" Moq для подписки на нужный Callback (вариант с возвращаемым значением). /// </summary> /// <param name="mock"> /// <see cref="Moq"/>, для которого нужно вызвать "магию". /// </param> /// <param name="action"> /// <see cref="Action{T}"/> с ref-параметром. /// </param> /// <typeparam name="TMock"> /// Moq для какого типа. /// </typeparam> /// <typeparam name="TReturn"> /// Тип возвращаемого значения. /// </typeparam> /// <returns> /// Возвращаем структуру для поддержки цепочечного вызова функции. /// </returns> private static IReturnsThrows <TMock, TReturn> RefCallbackInternal <TMock, TReturn>(ICallback <TMock, TReturn> mock, object action) where TMock : class { mock.GetType().Assembly.GetType("Moq.MethodCall").InvokeMember("SetCallbackWithArguments", BindingFlags.InvokeMethod | BindingFlags.NonPublic | BindingFlags.Instance, null, mock, new[] { action }); return(mock as IReturnsThrows <TMock, TReturn>); }
/// <summary> /// Метод расширения для <see cref="Moq"/>, который позволяет подписываться на Callback методов с двумя параметрами, первый из которых ref-объект (вариант без возвращаемого значения). /// </summary> /// <param name="mock"><see cref="Moq"/>, для которого нужно вызвать Callback.</param> /// <param name="action"><see cref="Action{T, T}"/> с ref-параметром.</param> /// <typeparam name="TRef">Тип параметров передаваемых по ссылке.</typeparam> /// <typeparam name="TParam">Тип обычных параметров.</typeparam> /// <returns>Результат выполнения Callback.</returns> public static ICallbackResult RefValCallback <TRef, TParam>(this ICallback mock, RefValAction <TRef, TParam> action) { return(RefCallbackInternal(mock, action)); }
/// <summary> /// Метод расширения для <see cref="Moq"/>, который позволяет подписываться на Callback методов, параметром которых является ref-объект (вариант без возвращаемого значения). /// </summary> /// <param name="mock"> /// <see cref="Moq"/>, для которого нужно вызвать Callback. /// </param> /// <param name="action"> /// <see cref="Action{T}"/> с ref-параметром. /// </param> /// <typeparam name="TRef"> /// Тип ref-параметра. /// </typeparam> /// <returns> /// Результат выполнения Callback. /// </returns> public static ICallbackResult RefCallback <TRef>(this ICallback mock, RefAction <TRef> action) { return(RefCallbackInternal(mock, action)); }
public ComponentClose(IRobotWare root, ICallback callback, IParameterManager mgr) : base(root, callback, mgr) { }
public void StartAnimatingNode(int animationId, int animatedNodeTag, JObject animationConfig, ICallback endCallback) { var node = GetNode(animatedNodeTag); var valueNode = node as ValueAnimatedNode; if (valueNode == null) { throw new InvalidOperationException( Invariant($"Animated node with tag '{animatedNodeTag}' is not a value node.")); } var type = animationConfig.Value <string>("type"); var animation = default(AnimationDriver); switch (type) { case "decay": animation = new DecayAnimationDriver(animationId, valueNode, endCallback, animationConfig); break; case "frames": animation = new FrameBasedAnimationDriver(animationId, valueNode, endCallback, animationConfig); break; case "spring": animation = new SpringAnimationDriver(animationId, valueNode, endCallback, animationConfig); break; default: throw new InvalidOperationException(Invariant($"Unsupported animation type: '{type}'")); } _activeAnimations[animationId] = animation; }
public void Foo(ICallback callback) { callback.Invoke(_callbackArgs); }
/// <summary> /// Find the touch target child native view in the supplied root view /// hierarchy, given a React target location. /// </summary> /// <param name="reactTag">The root tag to traverse.</param> /// <param name="targetX">The target X-coordinate.</param> /// <param name="targetY">The target Y-coordinate.</param> /// <param name="callback"> /// Callback invoked with the identified child view React ID and /// measurement information. If no view was found, callback will be /// invoked with no data. /// </param> /// <remarks> /// This method is currently used only by the Element Inspector dev tool. /// </remarks> public void FindSubViewIn(int reactTag, double targetX, double targetY, ICallback callback) { _operationsQueue.EnqueueFindTargetForTouch(reactTag, targetX, targetY, callback); }
public void Foo(ICallback bar, int foo) { }
/// <summary> /// Вызов внутренней "магии" Moq для подписки на нужный Callback (вариант без возвращаемого значения). /// </summary> /// <param name="mock"> /// <see cref="Moq"/>, для которого нужно вызвать "магию". /// </param> /// <param name="action"> /// <see cref="Action{T}"/> с ref-параметром. /// </param> /// <returns> /// Результат выполнения Callback. /// </returns> private static ICallbackResult RefCallbackInternal(ICallback mock, object action) { mock.GetType().Assembly.GetType("Moq.MethodCall") .InvokeMember("SetCallbackWithArguments", BindingFlags.InvokeMethod | BindingFlags.NonPublic | BindingFlags.Instance, null, mock, new[] { action }); return((ICallbackResult)mock); }
public bool ProcessRequestAsync(IRequest request, ICallback callback) { FindServers(callback); return true; }
/// <summary> /// Метод расширения для <see cref="Moq"/>, который позволяет подписываться на Callback методов, параметром которых является ref-объект (вариант с возвращаемым значением). /// </summary> /// <param name="mock"> /// <see cref="Moq"/>, для которого нужно вызвать Callback. /// </param> /// <param name="action"> /// <see cref="Action{T}"/> с ref-параметром. /// </param> /// <typeparam name="TMock"> /// Moq для какого типа. /// </typeparam> /// <typeparam name="TReturn"> /// Тип возвращаемого значения. /// </typeparam> /// <typeparam name="TRef"> /// Тип ref-параметра. /// </typeparam> /// <returns> /// Возвращаем структуру для поддержки цепочечного вызова функции. /// </returns> public static IReturnsThrows <TMock, TReturn> RefCallback <TMock, TReturn, TRef>(this ICallback <TMock, TReturn> mock, RefAction <TRef> action) where TMock : class { return(RefCallbackInternal(mock, action)); }
public FaceSliverSelect(IRobotWare root, ICallback callback, IParameterManager mgr) : base(root, callback, mgr) { ColorLabel.Visible = ColorSwatch.Visible = false; }
private void OnInvoked(IUICommand target, ICallback callback) { callback.Invoke(DialogModuleHelper.ActionButtonClicked, target.Id); }
public void showAlert( JObject config, ICallback errorCallback, ICallback actionCallback) { var message = config.Value <string>("message") ?? ""; var messageDialog = new MessageDialog(message) { Title = config.Value <string>("title"), }; MessageDialogInfo dialogInfo = new MessageDialogInfo { MessageDialog = messageDialog, ErrorCallback = (string error) => errorCallback.Invoke(error) }; if (config.ContainsKey(DialogModuleHelper.RootViewHint)) { dialogInfo.RootViewHint = config.Value <int>(DialogModuleHelper.RootViewHint); } uint commandIndex = 0; if (config.ContainsKey(DialogModuleHelper.KeyButtonPositive)) { messageDialog.Commands.Add(new UICommand { Label = config.Value <string>(DialogModuleHelper.KeyButtonPositive), Id = DialogModuleHelper.KeyButtonPositiveValue, Invoked = target => OnInvoked(target, actionCallback), }); commandIndex++; } if (config.ContainsKey(DialogModuleHelper.KeyButtonNegative)) { messageDialog.Commands.Add(new UICommand { Label = config.Value <string>(DialogModuleHelper.KeyButtonNegative), Id = DialogModuleHelper.KeyButtonNegativeValue, Invoked = target => OnInvoked(target, actionCallback), }); // Use this command for Escape (we don't use the DialogModuleHelper.ActionDismissed since // it's hard to detect the condition messageDialog.CancelCommandIndex = commandIndex; commandIndex++; } DispatcherHelpers.RunOnDispatcher(() => { if (_isInForeground) { ShowDialog(dialogInfo); } else { _pendingDialog = dialogInfo; } }); }
public override IRunnable Create(IRobotWare root, ICallback callback, IParameterManager mgr) { return(new ProcessStart(root, callback, mgr)); }
/// <summary> /// Determines the width, height, and location relative to the window /// of the given view and returns the values via an asynchronous callback. /// </summary> /// <param name="reactTag">The view tag to measure.</param> /// <param name="callback">The callback.</param> public void MeasureInWindow(int reactTag, ICallback callback) { _operationsQueue.EnqueueMeasureInWindow(reactTag, callback); }
public static void Callback <T1, T2, T3, T4, T5>(this ICallback iCallBack, Action <T1, T2, T3, T4, T5> action) { }
public override bool ProcessRequestAsync(IRequest request, ICallback callback) { try { var httpClient = new HttpClient(); foreach (var header in request.Headers.AllKeys) { if (header.ToLower() != "content-type") { httpClient.DefaultRequestHeaders.Add(header, request.Headers.GetValues(header)); } } var url = request.Url; if (_config.VideoQuality != VideoQuality.Auto) { url = _pattern.Replace(url, _config.VideoQuality.ToProgressive(), 1); } HttpResponseMessage response = null; if (request.Method == "OPTIONS") { response = httpClient.SendAsync(new HttpRequestMessage(HttpMethod.Options, url)).Result; } if (request.Method == "GET") { response = httpClient.GetAsync(url).Result; } if (request.Method == "POST") { var content = request.PostData?.Elements.FirstOrDefault()?.GetBody(); var httpContent = new StringContent2(content, Encoding.UTF8, "application/json"); response = httpClient.PostAsync(url, httpContent).Result; } if (request.Method == "PUT") { var content = request.PostData?.Elements.FirstOrDefault()?.GetBody(); var httpContent = new StringContent2(content, Encoding.UTF8, "application/json"); response = httpClient.PutAsync(url, httpContent).Result; } // 知らん if (response == null) { throw new NotSupportedException(); } StatusCode = response.StatusCode.GetHashCode(); MimeType = response.Content.Headers.ContentType.MediaType; Stream = response.Content.ReadAsStreamAsync().Result; foreach (var header in response.Content.Headers) { foreach (var value in header.Value) { Headers.Set(header.Key, value); } } foreach (var header in response.Headers) { foreach (var value in header.Value) { Headers.Set(header.Key, value); } } callback.Continue(); } catch (Exception e) { Debug.WriteLine(e.Message); } return(true); }
private int time = 0; // Amount of time to sleep. #endregion Fields #region Constructors /* ** Name: Timer ** ** Description: ** Class constructor. Defines the amount of time in the ** timer and the object which will perform the desired ** action when notified that the time has expired. ** ** The time parameter is taken to be seconds if positive ** and milli-seconds if negative. The timer should be ** started by calling the start() method. ** ** Input: ** time Length of timer (negative for milli-seconds). ** callback Object to be notified when time expired. ** ** Output: ** None. ** ** Returns: ** void. ** ** History: ** 16-Nov-99 (gordy) ** Created.*/ public Timer(int time, ICallback callback) { this.time = time; this.callback = callback; }
/// <summary> /// Similar to <see cref="Measure(int, ICallback)"/> and /// <see cref="MeasureLayout(int, int, ICallback, ICallback)"/>, /// measures relative to the immediate parent. /// </summary> /// <param name="tag">The view tag.</param> /// <param name="errorCallback">Called in case of error.</param> /// <param name="successCallback">Called with the measurements.</param> public void MeasureLayoutRelativeToParent(int tag, ICallback errorCallback, ICallback successCallback) { try { MeasureLayoutRelativeToParent(tag, _measureBuffer); var relativeX = _measureBuffer[0]; var relativeY = _measureBuffer[1]; var width = _measureBuffer[2]; var height = _measureBuffer[3]; successCallback.Invoke(relativeX, relativeY, width, height); } catch (Exception e) { errorCallback.Invoke(e); } }
/// <summary> /// Sets up the Layout Animation Manager. /// </summary> /// <param name="config"></param> /// <param name="success"></param> /// <param name="error"></param> public void ConfigureLayoutAnimation(JObject config, ICallback success, ICallback error) { _layoutAnimator.InitializeFromConfig(config); }
public void Foo(ICallback foo, int bar, string qux) { }
private void OnInvoked(Object error, Object success, ICallback callback) { callback.Invoke(error, success); }
/// <summary> /// Shows a <see cref="PopupMenu"/>. /// </summary> /// <param name="tag"> /// The tag of the anchor view (the <see cref="PopupMenu"/> is /// displayed next to this view); this needs to be the tag of a native /// view (shadow views cannot be anchors). /// </param> /// <param name="items">The menu items as an array of strings.</param> /// <param name="success"> /// A callback used with the position of the selected item as the first /// argument, or no arguments if the menu is dismissed. /// </param> public void ShowPopupMenu(int tag, string[] items, ICallback success) { DispatcherHelpers.AssertOnDispatcher(); var view = ResolveView(tag); var menu = new PopupMenu(); for (var i = 0; i < items.Length; ++i) { menu.Commands.Add(new UICommand( items[i], cmd => { success.Invoke(cmd.Id); }, i)); } // TODO: figure out where to popup the menu // TODO: add continuation that calls the callback with empty args throw new NotImplementedException(); }
public void configureNextLayoutAnimation(JObject config, ICallback success, ICallback error) { _uiImplementation.ConfigureNextLayoutAnimation(config, success, error); }
public DirectoryCreate(IRobotWare root, ICallback callback, IParameterManager mgr) : base(root, callback, mgr) { Initialise(); }
public void showPopupMenu(int reactTag, string[] items, ICallback error, ICallback success) { _uiImplementation.ShowPopupMenu(reactTag, items, error, success); }
public static void SetCharResult(ICallback to, List<char> helpkeys, string proverb, long time, int incorrect, string oponentProverb, int oponentIncorrect) { var conns = GetUsers(to); if (conns == null) return; Hub.Clients.Clients(conns).SetCharResult(helpkeys, proverb, time,incorrect, oponentProverb, oponentIncorrect); }
public void measureInWindow(int reactTag, ICallback callback) { _uiImplementation.MeasureInWindow(reactTag, callback); }
public DualItemIOBase(IRobotWare root, ICallback callback, IParameterManager mgr, BrowserTypes browsers) : base(root, callback, mgr) { mControl.Initialise(root, callback, mgr, browsers); }
public Player(string name, ICallback callback) { this.name = name; this.callback = callback; this.hand = new Hand(); }