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 void Reject(string code, string message, string stack, JToken userInfo) { _reject?.Invoke(new JObject { { "code", code ?? DefaultError }, { "message", message }, { "stack", stack }, { "userInfo", userInfo }, }); }
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); } }
/// <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); } }
public async void clear(ICallback callback) { await Task.Run(() => { lock (_gate) { var localFolder = ApplicationData.Current.LocalFolder; var storageItem = localFolder.TryGetItemAsync(DirectoryName).AsTask().Result; if (storageItem != null) { storageItem.DeleteAsync().AsTask().Wait(); } } }); callback.Invoke(); }
public void Reject(string code, string message, Exception e) { if (_reject != null) { var errorData = e?.Data; var userInfo = errorData != null ? JToken.FromObject(errorData) : null; _reject.Invoke(new JObject { { "code", code ?? DefaultError }, { "message", message }, { "stack", e?.StackTrace }, { "userInfo", userInfo }, }); } }
/// <summary> /// Enqueues an operation to find a touch target. /// </summary> /// <param name="tag">The parent view to search from.</param> /// <param name="targetX">The x-coordinate of the touch event.</param> /// <param name="targetY">The y-coordinate of the touch event.</param> /// <param name="callback">The callback.</param> public void EnqueueFindTargetForTouch( int tag, double targetX, double targetY, ICallback callback) { // Called on layout manager thread UIViewOperationQueueInstance queue = GetQueueByTag(tag, true); if (queue == null) { // This is called bypassing the optimizer, so we need to fake a result for layout only nodes. callback.Invoke(); return; } queue.EnqueueFindTargetForTouch(tag, targetX, targetY, callback); }
public async void clear(ICallback callback) { await _mutex.WaitAsync().ConfigureAwait(false); try { var storageFolder = await GetAsyncStorageFolder(false).ConfigureAwait(false); if (storageFolder != null) { await storageFolder.DeleteAsync().ConfigureAwait(false); } } finally { _mutex.Release(); } callback.Invoke(); }
public void showPhotos(ICallback errorCallback, ICallback successCallback) { RunOnDispatcher(async() => { try { FileOpenPicker openPicker = new FileOpenPicker(); openPicker.ViewMode = PickerViewMode.Thumbnail; openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary; openPicker.FileTypeFilter.Add(".jpg"); openPicker.FileTypeFilter.Add(".jpeg"); openPicker.FileTypeFilter.Add(".png"); StorageFile file = await openPicker.PickSingleFileAsync(); if (file != null) { byte[] fileBytes = null; using (var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read)) { fileBytes = new byte[stream.Size]; using (var reader = new DataReader(stream)) { await reader.LoadAsync((uint)stream.Size); reader.ReadBytes(fileBytes); } } successCallback.Invoke(fileBytes); } else { errorCallback.Invoke("not_available image"); } } catch { errorCallback.Invoke("not_available"); } }); }
public static void Go(ICallback callback, ICallback continueWith = null) { if (callback != null) { var task = new Task(callback.Invoke); task.ContinueWith(t => { if (continueWith != null) { continueWith.Invoke(); } if (t != null) { t.Dispose(); } }); task.Start(); } }
public async void clear(ICallback callback) { await _mutex.WaitAsync().ConfigureAwait(false); try { var localFolder = ApplicationData.Current.LocalFolder; var storageItem = await localFolder.TryGetItemAsync(DirectoryName).AsTask().ConfigureAwait(false); if (storageItem != null) { await storageItem.DeleteAsync().AsTask().ConfigureAwait(false); } } finally { _mutex.Release(); } callback.Invoke(); }
public async void openCamera(ICallback successCallback, ICallback errorCallback) { RunOnDispatcher(async() => { CameraCaptureUI captureUI = new CameraCaptureUI(); captureUI.PhotoSettings.Format = CameraCaptureUIPhotoFormat.Jpeg; StorageFile photo = await captureUI.CaptureFileAsync(CameraCaptureUIMode.Photo); if (photo == null) { // User cancelled photo capture errorCallback.Invoke("User cancelled photo capture"); return; } else { successCallback.Invoke(photo); } }); }
public void close( JObject config, ICallback doneCallback, ICallback errorCallback ) { try { string dbname = config.Value <string>("path") ?? ""; Database db = databases[dbname]; db.closedb(); databases.Remove(dbname); databaseKeys.Remove(dbname); doneCallback.Invoke(); //Debug.WriteLine("Closed Database"); } catch (Exception e) { errorCallback.Invoke(e.Message); Debug.WriteLine("Close database failed " + e.ToString()); } }
/// <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 async void getCurrentPosition( JObject options, ICallback success, ICallback error) { var locationOptions = LocationOptions.FromJson(options); var geolocator = new Geolocator { DesiredAccuracy = locationOptions.HighAccuracy ? PositionAccuracy.High : PositionAccuracy.Default, MovementThreshold = locationOptions.DistanceFilter, }; try { // TODO: Enable retrieval from position history using `MaximumAge` filter var task = geolocator.GetGeopositionAsync().AsTask(); var completedTask = await Task.WhenAny( task, Task.Delay(TimeSpan.FromMilliseconds(locationOptions.Timeout))).ConfigureAwait(false); if (completedTask == task) { var geoposition = await task.ConfigureAwait(false); success.Invoke(ConvertGeoposition(geoposition)); } else { error.Invoke("Location request timed out"); } } catch (Exception ex) { error.Invoke($"Location request failed with exception: {ex}"); } }
public void delete(DeleteOptions options, ICallback success, ICallback error) { QueueWithCancellation(async() => { var dbFileName = options.Path; if (dbFileName == null) { error.Invoke("You must specify database path"); return; } if (_openDBs.ContainsKey(dbFileName)) { var dbInfo = _openDBs[dbFileName]; _openDBs.Remove(dbFileName); if (_sqliteAPI.Close(dbInfo.Handle) != SQLite.Net.Interop.Result.OK) { System.Diagnostics.Debug.WriteLine("SQLitePluginModule: Error closing database: " + dbInfo.Path); } } var absoluteDbPath = ResolveDbFilePath(dbFileName); try { var dbFile = await Windows.Storage.StorageFile.GetFileFromPathAsync(absoluteDbPath); await dbFile.DeleteAsync(); } catch (FileNotFoundException) { error.Invoke("The database does not exist on that path"); return; } success.Invoke("DB deleted"); }); }
public async void openGallery(ICallback successCallback, ICallback errorCallback) { RunOnDispatcher(async() => { FileOpenPicker openPicker = new FileOpenPicker(); openPicker.ViewMode = PickerViewMode.Thumbnail; openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary; openPicker.FileTypeFilter.Add(".jpg"); openPicker.FileTypeFilter.Add(".jpeg"); openPicker.FileTypeFilter.Add(".png"); StorageFile file = await openPicker.PickSingleFileAsync(); if (file != null) { // Application now has read/write access to the picked file successCallback.Invoke(file); } else { errorCallback.Invoke("File not selected"); } }); }
public async void captureImage(ICallback errorCallback, ICallback successCallback) { RunOnDispatcher(async() => { try { CameraCaptureUI capture = new CameraCaptureUI(); capture.PhotoSettings.Format = CameraCaptureUIPhotoFormat.Jpeg; capture.PhotoSettings.CroppedAspectRatio = new Size(3, 5); capture.PhotoSettings.MaxResolution = CameraCaptureUIMaxPhotoResolution.HighestAvailable; storeFile = await capture.CaptureFileAsync(CameraCaptureUIMode.Photo); if (storeFile != null) { byte[] fileBytes = null; using (var stream = await storeFile.OpenAsync(Windows.Storage.FileAccessMode.Read)) { fileBytes = new byte[stream.Size]; using (var reader = new DataReader(stream)) { await reader.LoadAsync((uint)stream.Size); reader.ReadBytes(fileBytes); } } successCallback.Invoke(fileBytes); } else { errorCallback.Invoke("image not_available"); } } catch (Exception error) { errorCallback.Invoke(error); } }); }
/// <summary> /// 配置项值变更时的回调处理 /// </summary> public void Callback() { try { ICallback callback = null; if (this.ConfigClassMapper == null) { callback = ConfigCallbackManager.GetCallback(this.Name); } else { this.RefreshConfigObject(); callback = ConfigCallbackManager.GetCallback(this.ConfigClassMapper.ConfigNodeName); } if (callback != null) { callback.Invoke(); } } catch (Exception ex) { LogManager.GetLogger().Error(string.Format("DisconfClient.ConfigStorageItem.Callback,Name:{0}", this.Name), ex); } }
public async void getAllKeys(ICallback callback) { var keys = new JArray(); await _mutex.WaitAsync().ConfigureAwait(false); try { var localFolder = ApplicationData.Current.LocalFolder; var storageItem = await localFolder.TryGetItemAsync(DirectoryName).AsTask().ConfigureAwait(false); if (storageItem != null) { var directory = await localFolder.GetFolderAsync(DirectoryName).AsTask().ConfigureAwait(false); var items = await directory.GetItemsAsync().AsTask().ConfigureAwait(false); foreach (var item in items) { var itemName = item.Name; var itemLength = itemName.Length; var extLength = FileExtension.Length; if (itemName.EndsWith(FileExtension) && itemLength > extLength) { keys.Add(item.Name.Substring(0, itemLength - extLength)); } } } } finally { _mutex.Release(); } callback.Invoke(null, keys); }
public void Resolve(object value) { _resolve?.Invoke(value); }
public void Foo(ICallback callback) { callback.Invoke(_callbackArgs); }
private void OnInvoked(IUICommand target, ICallback callback) { callback.Invoke(DialogModuleHelper.ActionButtonClicked, target.Id); }
public async void backgroundExecuteSqlBatch( JObject config, ICallback doneCallback, ICallback errorCallback ) { try { string dbname = config.Value <JObject>("dbargs").Value <string>("dbname") ?? ""; if (!databaseKeys.Keys.Contains(dbname)) { throw new Exception("Database does not exist"); } if (!databases.Keys.Contains(dbname)) { try { await reOpenDatabases(); if (!databases.Keys.Contains(dbname)) { throw new Exception("Resume Didn't Work"); } } catch (Exception e) { throw new Exception("Failed to reopendatabase" + e.ToString()); } } JArray executes = config.Value <JArray>("executes"); Database db = databases[dbname]; JArray results = new JArray(); long totalChanges = db.TotalChanges; string q = ""; foreach (JObject e in executes) { try { q = e.Value <string>("qid"); string s = e.Value <string>("sql"); JArray pj = e.Value <JArray>("params"); IReadOnlyList <Object> p = pj.ToObject <IReadOnlyList <Object> >(); JArray rows = JArray.Parse(await db.AllAsyncVector(s, p)); long rowsAffected = db.TotalChanges - totalChanges; totalChanges = db.TotalChanges; JObject result = new JObject(); result["rowsAffected"] = rowsAffected; result["rows"] = rows; result["insertId"] = db.LastInsertRowId; JObject resultInfo = new JObject(); resultInfo["type"] = "success"; resultInfo["qid"] = q; resultInfo["result"] = result; results.Add(resultInfo); } catch (Exception err) { JObject resultInfo = new JObject(); JObject result = new JObject(); result["code"] = -1; result["message"] = err.Message; resultInfo["type"] = "error"; resultInfo["qid"] = q; resultInfo["result"] = result; results.Add(resultInfo); } } doneCallback.Invoke(results); //Debug.WriteLine("Done Execute Sql Batch"); } catch (Exception e) { errorCallback.Invoke(e.Message); Debug.WriteLine("Error in background execute Sql batch" + e.ToString()); } finally { } }
public void getOrientation(ICallback callback) { callback.Invoke( DisplayInformation.GetForCurrentView().CurrentOrientation ); }
public void getMessage(ICallback callback) { callback.Invoke(testMessage); }
private void OnInvoked(Object error, Object success, ICallback callback) { callback.Invoke(error, success); }
public void open(OpenOptions options, ICallback success, ICallback error) { QueueWithCancellation(async() => { var dbFileName = options.Name; if (dbFileName == null) { error.Invoke("You must specify database name"); return; } if (_openDBs.ContainsKey(dbFileName)) { success.Invoke("Database opened"); return; } var assetFileOp = ResolveAssetFile(options.AssetFileName, dbFileName); var assetFile = assetFileOp == null ? null : await assetFileOp; // NoMutex means SQLite can be safely used by multiple threads provided that no // single database connection is used simultaneously in two or more threads. SQLite.Net.Interop.SQLiteOpenFlags sqlOpenFlags = SQLite.Net.Interop.SQLiteOpenFlags.NoMutex; string absoluteDbPath; if (options.ReadOnly && assetFileOp != null) { sqlOpenFlags |= SQLite.Net.Interop.SQLiteOpenFlags.ReadOnly; absoluteDbPath = assetFile.Path; } else { sqlOpenFlags |= SQLite.Net.Interop.SQLiteOpenFlags.ReadWrite | SQLite.Net.Interop.SQLiteOpenFlags.Create; absoluteDbPath = ResolveDbFilePath(dbFileName); // Option to create from resource (pre-populated) if db does not exist: if (assetFileOp != null) { try { await CopyDbAsync(assetFile, dbFileName); } catch (Exception) { // CopyDbAsync throws when the file already exists. } } } SQLite.Net.Interop.IDbHandle dbHandle; if (_sqliteAPI.Open(GetNullTerminatedUtf8(absoluteDbPath), out dbHandle, (int)sqlOpenFlags, IntPtr.Zero) == SQLite.Net.Interop.Result.OK) { _openDBs[dbFileName] = new OpenDB(dbHandle, absoluteDbPath); success.Invoke("Database opened"); } else { error.Invoke("Unable to open DB"); } }); }
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; } }); }
private void OnInvoked(IUICommand target, ICallback callback) { callback.Invoke(ActionButtonClicked, target.Id); }
public void getCurrentAppState(ICallback success, ICallback error) { success.Invoke(CreateAppStateEventMap()); }
public async void multiSet(string[][] keyValueArray, ICallback callback) { if (keyValueArray == null || keyValueArray.Length == 0) { callback.Invoke(AsyncStorageHelpers.GetInvalidKeyError(null)); return; } var error = default(JObject); await _mutex.WaitAsync().ConfigureAwait(false); try { foreach (var pair in keyValueArray) { if (pair.Length != 2) { error = AsyncStorageHelpers.GetInvalidValueError(null); break; } if (pair[0] == null) { error = AsyncStorageHelpers.GetInvalidKeyError(null); break; } if (pair[1] == null) { error = AsyncStorageHelpers.GetInvalidValueError(pair[0]); break; } error = await SetAsync(pair[0], pair[1]).ConfigureAwait(false); if (error != null) { break; } } } catch (Exception ex) { error = AsyncStorageHelpers.GetError(ex); } finally { _mutex.Release(); } if (error != null) { RnLog.Warn(ReactConstants.RNW, $"Error in AsyncStorageModule.multiSet: {error}"); callback.Invoke(error); } else { callback.Invoke(); } }