public void pickContact(string arguments) { string[] args = JSON.JsonHelper.Deserialize<string[]>(arguments); // Use custom contact picker because WP8 api doesn't provide its' own // contact picker, only PhoneNumberChooser or EmailAddressChooserTask var task = new ContactPickerTask(); var desiredFields = JSON.JsonHelper.Deserialize<string[]>(args[0]); task.Completed += delegate(Object sender, ContactPickerTask.PickResult e) { if (e.TaskResult == TaskResult.OK) { string strResult = e.Contact.ToJson(desiredFields); var result = new PluginResult(PluginResult.Status.OK) { Message = strResult }; DispatchCommandResult(result); } if (e.TaskResult == TaskResult.Cancel) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, "Operation cancelled.")); } }; task.Show(); }
async public void Reclaim(string options) { PluginResult result; if (barcodeScanner != null) { claimedBarcodeScanner = await barcodeScanner.ClaimScannerAsync(); if (claimedBarcodeScanner != null) { await claimedBarcodeScanner.EnableAsync(); claimedBarcodeScanner.DataReceived += DataReceived; result = new PluginResult(PluginResult.Status.NO_RESULT); result.KeepCallback = true; } else { result = new PluginResult(PluginResult.Status.ERROR, "Barcode Scanner could not get claimed"); } } else { result = new PluginResult(PluginResult.Status.ERROR, "Barcode Scanner Object not exists"); } DispatchCommandResult(result); }
public void close(string options = "") { if (browser != null) { Deployment.Current.Dispatcher.BeginInvoke(() => { PhoneApplicationFrame frame = Application.Current.RootVisual as PhoneApplicationFrame; if (frame != null) { PhoneApplicationPage page = frame.Content as PhoneApplicationPage; if (page != null) { Grid grid = page.FindName("LayoutRoot") as Grid; if (grid != null) { grid.Children.Remove(browser); } page.ApplicationBar = null; } } browser = null; string message = "{\"type\":\"exit\"}"; PluginResult result = new PluginResult(PluginResult.Status.OK, message); result.KeepCallback = false; this.DispatchCommandResult(result); }); } }
private void DeviceStatus_PowerSourceChanged(object sender, EventArgs e) { isPlugged = DeviceStatus.PowerSource.ToString().CompareTo("External") == 0; PluginResult result = new PluginResult(PluginResult.Status.OK, GetCurrentBatteryStateFormatted()); result.KeepCallback = true; DispatchCommandResult(result); }
public void execute_statment(string options) { string callbackId; options = options.Replace("{}", ""); /// empty objects screw up the Deserializer try { /// query params string[] args = JSON.JsonHelper.Deserialize<string[]>(options); /// to test maybe is not an integer but a JSONObject EntryExecuteStatment entryExecute = JSON.JsonHelper.Deserialize<EntryExecuteStatment>(args[0]); string query = entryExecute.query; /// to test not sure that's work List<object> param = entryExecute.param; callbackId = args[1]; if (mbTilesActions != null && mbTilesActions.isOpen()) { string result = mbTilesActions.executeStatment(query, param); PluginResult pluginResult = new PluginResult(PluginResult.Status.OK); pluginResult.Message = result; DispatchCommandResult(pluginResult, callbackId); } else { DispatchCommandResult(new PluginResult(PluginResult.Status.IO_EXCEPTION), callbackId); } } catch (Exception) { DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION)); } }
public void start(string options) { // Register power changed event handler DeviceStatus.PowerSourceChanged += powerChanged; PluginResult result = new PluginResult(PluginResult.Status.NO_RESULT); result.KeepCallback = true; DispatchCommandResult(result); }
public void DispatchCommandResult(PluginResult result) { if (this.OnCommandResult != null) { this.OnCommandResult(this, result); this.OnCommandResult = null; } }
public void start(string options) { // Register power changed event handler DeviceStatus.PowerSourceChanged += powerChanged; #if WP8 battery.RemainingChargePercentChanged += Battery_RemainingChargePercentChanged; #endif PluginResult result = new PluginResult(PluginResult.Status.NO_RESULT); result.KeepCallback = true; DispatchCommandResult(result); }
public void DispatchCommandResult(PluginResult result) { if (this.OnCommandResult != null) { this.OnCommandResult(this, result); if (!result.KeepCallback) { this.Dispose(); } } }
public void Method(string options) { string upperCase = JSON.JsonHelper.Deserialize<string[]>(options)[0].ToUpper(); PluginResult result; if (upperCase != "") { result = new PluginResult(PluginResult.Status.OK, upperCase); } else { result = new PluginResult(PluginResult.Status.ERROR, upperCase); } DispatchCommandResult(result); }
public void download(string options) { string url; string filePath; string callbackId; try { url = JSON.JsonHelper.Deserialize<string[]>(options)[0]; filePath = JSON.JsonHelper.Deserialize<string[]>(options)[1]; callbackId = JSON.JsonHelper.Deserialize<string[]>(options)[2]; } catch (ArgumentException ex) { XLog.WriteError("download arguments occur Exception JSON_EXCEPTION " + ex.Message); DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION)); return; } string workspace = this.app.GetWorkSpace(); string target = XUtils.ResolvePath(workspace, filePath); if (null == target) { FileTransfer.FileTransferError error = new FileTransfer.FileTransferError(FILE_NOT_FOUND_ERR, url, filePath, 0); PluginResult result = new PluginResult(PluginResult.Status.ERROR, error); DispatchCommandResult(result); return; } String abstarget = XUtils.BuildabsPathOnIsolatedStorage(target); if (!url.StartsWith("http://")) { FileTransfer.FileTransferError error = new FileTransfer.FileTransferError(INVALID_URL_ERR, url, filePath, 0); PluginResult result = new PluginResult(PluginResult.Status.ERROR, error); DispatchCommandResult(result); return; } EventHandler<PluginResult> DispatchPluginResult = delegate(object sender, PluginResult result) { DispatchCommandResult(result, callbackId); }; FileTransferManager.AddFileTranferTask(url, abstarget, workspace, DispatchPluginResult, COMMAND_DOWNLOAD); }
public void Band(string options) { string title = ""; string message = ""; string[] args = JSON.JsonHelper.Deserialize<string[]>(options); title = args[0].ToString(); message = args[1].ToString(); PluginResult result; if (title != "" && message != "") { result = new PluginResult(PluginResult.Status.OK, args); } else { result = new PluginResult(PluginResult.Status.ERROR, args); } DispatchCommandResult(result); }
/// <summary> /// Handler for barcode scanner task. /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The scan result.</param> private void TaskCompleted(object sender, BarcodeScannerTask.ScanResult e) { PluginResult result; switch (e.TaskResult) { case TaskResult.OK: result = new PluginResult(PluginResult.Status.OK); result.Message = JsonHelper.Serialize(new BarcodeResult(e.Barcode)); break; case TaskResult.Cancel: // If scan is cancelled we return PluginResult.Status.OK with Message contains cancelled: true // See plugin docs https://github.com/MSOpenTech/BarcodeScanner#using-the-plugin result = new PluginResult(PluginResult.Status.OK); result.Message = JsonHelper.Serialize(new BarcodeResult()); break; default: result = new PluginResult(PluginResult.Status.ERROR); break; } this.DispatchCommandResult(result); }
async public void Enable(string options) { PluginResult result; if (barcodeScanner == null) { barcodeScanner = await Windows.Devices.PointOfService.BarcodeScanner.GetDefaultAsync(); if (claimedBarcodeScanner == null) { claimedBarcodeScanner = await barcodeScanner.ClaimScannerAsync(); if (claimedBarcodeScanner != null) { await claimedBarcodeScanner.EnableAsync(); claimedBarcodeScanner.DataReceived += DataReceived; result = new PluginResult(PluginResult.Status.NO_RESULT); result.KeepCallback = true; } else { result = new PluginResult(PluginResult.Status.ERROR, "Barcode Scanner could not get claimed"); } } else { result = new PluginResult(PluginResult.Status.ERROR, "Claimed Barcode Scanner Object already there"); } } else { result = new PluginResult(PluginResult.Status.ERROR, "Barcode Scanner Object already there"); } DispatchCommandResult(result); }
public async void search(string searchCriteria) { string[] args = JSON.JsonHelper.Deserialize <string[]>(searchCriteria); ContactSearchParams searchParams = new ContactSearchParams(); try { searchParams.fields = JSON.JsonHelper.Deserialize <string[]>(args[0]); searchParams.options = JSON.JsonHelper.Deserialize <SearchOptions>(args[1]); } catch (Exception) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, INVALID_ARGUMENT_ERROR)); return; } if (searchParams.options == null) { searchParams.options = new SearchOptions(); searchParams.options.filter = ""; searchParams.options.multiple = true; } if (searchParams.options.multiple == true) { var contactPicker = new Windows.ApplicationModel.Contacts.ContactPicker(); contactPicker.CommitButtonText = "Select"; contactPicker.SelectionMode = Windows.ApplicationModel.Contacts.ContactSelectionMode.Contacts; IReadOnlyList <ContactInformation> contacts = await contactPicker.PickMultipleContactsAsync(); string strResult = ""; foreach (ContactInformation contact in contacts) { strResult += FormatJSONContact(contact, null) + ","; } PluginResult result = new PluginResult(PluginResult.Status.OK); result.Message = "[" + strResult.TrimEnd(',') + "]"; DispatchCommandResult(result); } else { var contactPicker = new Windows.ApplicationModel.Contacts.ContactPicker(); contactPicker.CommitButtonText = "Select"; contactPicker.SelectionMode = Windows.ApplicationModel.Contacts.ContactSelectionMode.Contacts; ContactInformation contact = await contactPicker.PickSingleContactAsync(); string strResult = ""; if (contact != null) { strResult += FormatJSONContact(contact, null) + ","; } PluginResult result = new PluginResult(PluginResult.Status.OK); result.Message = "[" + strResult.TrimEnd(',') + "]"; DispatchCommandResult(result); } }
void browser_NavigationFailed(object sender, System.Windows.Navigation.NavigationFailedEventArgs e) { string message = "{\"type\":\"error\",\"url\":\"" + e.Uri.OriginalString + "\"}"; PluginResult result = new PluginResult(PluginResult.Status.ERROR, message); result.KeepCallback = true; this.DispatchCommandResult(result, NavigationCallbackId); }
public void injectScriptCode(string options) { string[] args = JSON.JsonHelper.Deserialize<string[]>(options); bool bCallback = false; if (bool.TryParse(args[1], out bCallback)) { }; string callbackId = args[2]; if (browser != null) { Deployment.Current.Dispatcher.BeginInvoke(() => { var res = browser.InvokeScript("eval", new string[] { args[0] }); if (bCallback) { PluginResult result = new PluginResult(PluginResult.Status.OK, res.ToString()); result.KeepCallback = false; this.DispatchCommandResult(result); } }); } }
void PushChannel_ShellToastNotificationReceived(object sender, NotificationEventArgs e) { StringBuilder message = new StringBuilder(); string relativeUri = string.Empty; Toast toast = new Toast(); if (e.Collection.ContainsKey("wp:Text1")) { toast.Title = e.Collection["wp:Text1"]; } if (e.Collection.ContainsKey("wp:Text2")) { toast.Subtitle = e.Collection["wp:Text2"]; } if (e.Collection.ContainsKey("wp:Param")) { toast.Param = e.Collection["wp:Param"]; } PluginResult result = new PluginResult(PluginResult.Status.OK, toast); Deployment.Current.Dispatcher.BeginInvoke(() => { PhoneApplicationFrame frame = Application.Current.RootVisual as PhoneApplicationFrame; if (frame != null) { PhoneApplicationPage page = frame.Content as PhoneApplicationPage; if (page != null) { CordovaView cView = page.FindName("CordovaView") as CordovaView; // was: PGView if (cView != null) { cView.Browser.Dispatcher.BeginInvoke((ThreadStart)delegate() { try { cView.Browser.InvokeScript("execScript", this.toastCallback + "(" + result.Message + ")"); } catch (Exception ex) { Debug.WriteLine("ERROR: Exception in InvokeScriptCallback :: " + ex.Message); } }); } } } }); }
/// <summary> /// Initializes a new instance of the <see cref="PluginExecutionResult" /> class. /// </summary> /// <param name="result">The <see cref="PluginResult" /> representing the execution outcome.</param> /// <param name="message">The message describing the result of the execution.</param> public PluginExecutionResult(PluginResult result, string message) : this(result) { Message = message; }
/// <summary> /// Starts listening for acceleration sensor /// </summary> /// <returns>status of listener</returns> public void start(string options) { if ((currentStatus == Running) || (currentStatus == Starting)) { return; } try { lock (accelerometer) { accelerometer.CurrentValueChanged += accelerometer_CurrentValueChanged; accelerometer.Start(); this.SetStatus(Starting); } long timeout = 2000; while ((currentStatus == Starting) && (timeout > 0)) { timeout = timeout - 100; Thread.Sleep(100); } if (currentStatus != Running) { this.SetStatus(ErrorFailedToStart); DispatchCommandResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, ErrorFailedToStart)); return; } } catch (Exception) { this.SetStatus(ErrorFailedToStart); DispatchCommandResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, ErrorFailedToStart)); return; } PluginResult result = new PluginResult(PluginResult.Status.NO_RESULT); result.KeepCallback = true; DispatchCommandResult(result); }
/// <summary> /// Sensor listener event /// </summary> private void accelerometer_CurrentValueChanged(object sender, SensorReadingEventArgs<AccelerometerReading> e) { this.SetStatus(Running); if (accelOptions != null) { if (((DateTime.Now - lastValueChangedTime).TotalMilliseconds) > accelOptions.Frequency) { lastValueChangedTime = DateTime.Now; PluginResult result = new PluginResult(PluginResult.Status.OK, GetCurrentAccelerationFormatted()); result.KeepCallback = true; DispatchCommandResult(result); } } if (watchers.Count == 0) { accelerometer.Stop(); this.SetStatus(Stopped); } }
private void contacts_SearchCompleted(object sender, ContactsSearchEventArgs e) { ContactSearchParams searchParams = (ContactSearchParams)e.State; List <Contact> foundContacts = null; // used for comparing strings, "" instantiates with InvariantCulture CultureInfo culture = new CultureInfo(""); // make the search comparisons case insensitive. CompareOptions compare_option = CompareOptions.IgnoreCase; // if we have multiple search fields if (!String.IsNullOrEmpty(searchParams.options.filter) && searchParams.fields.Count() > 1) { foundContacts = new List <Contact>(); if (searchParams.fields.Contains("emails")) { foundContacts.AddRange(from Contact con in e.Results from ContactEmailAddress a in con.EmailAddresses where culture.CompareInfo.IndexOf(a.EmailAddress, searchParams.options.filter, compare_option) >= 0 select con); } if (searchParams.fields.Contains("displayName")) { foundContacts.AddRange(from Contact con in e.Results where culture.CompareInfo.IndexOf(con.DisplayName, searchParams.options.filter, compare_option) >= 0 select con); } if (searchParams.fields.Contains("name")) { foundContacts.AddRange( from Contact con in e.Results where con.CompleteName != null && ( (con.CompleteName.FirstName != null && culture.CompareInfo.IndexOf(con.CompleteName.FirstName, searchParams.options.filter, compare_option) >= 0) || (con.CompleteName.LastName != null && culture.CompareInfo.IndexOf(con.CompleteName.LastName, searchParams.options.filter, compare_option) >= 0) || (con.CompleteName.MiddleName != null && culture.CompareInfo.IndexOf(con.CompleteName.MiddleName, searchParams.options.filter, compare_option) >= 0) || (con.CompleteName.Nickname != null && culture.CompareInfo.IndexOf(con.CompleteName.Nickname, searchParams.options.filter, compare_option) >= 0) || (con.CompleteName.Suffix != null && culture.CompareInfo.IndexOf(con.CompleteName.Suffix, searchParams.options.filter, compare_option) >= 0) || (con.CompleteName.Title != null && culture.CompareInfo.IndexOf(con.CompleteName.Title, searchParams.options.filter, compare_option) >= 0) || (con.CompleteName.YomiFirstName != null && culture.CompareInfo.IndexOf(con.CompleteName.YomiFirstName, searchParams.options.filter, compare_option) >= 0) || (con.CompleteName.YomiLastName != null && culture.CompareInfo.IndexOf(con.CompleteName.YomiLastName, searchParams.options.filter, compare_option) >= 0)) select con); } if (searchParams.fields.Contains("phoneNumbers")) { foundContacts.AddRange(from Contact con in e.Results from ContactPhoneNumber a in con.PhoneNumbers where culture.CompareInfo.IndexOf(a.PhoneNumber, searchParams.options.filter, compare_option) >= 0 select con); } if (searchParams.fields.Contains("urls")) { foundContacts.AddRange(from Contact con in e.Results from string a in con.Websites where culture.CompareInfo.IndexOf(a, searchParams.options.filter, compare_option) >= 0 select con); } } else { foundContacts = new List <Contact>(e.Results); } //List<string> contactList = new List<string>(); string strResult = ""; IEnumerable <Contact> distinctContacts = foundContacts.Distinct(); foreach (Contact contact in distinctContacts) { strResult += FormatJSONContact(contact, null) + ","; //contactList.Add(FormatJSONContact(contact, null)); if (!searchParams.options.multiple) { break; // just return the first item } } PluginResult result = new PluginResult(PluginResult.Status.OK); result.Message = "[" + strResult.TrimEnd(',') + "]"; DispatchCommandResult(result); }
public void sync(string options) { TransferOptions downloadOptions = null; HttpWebRequest webRequest = null; string callbackId; try { // options.src, options.type, options.headers, options.id string[] optionStrings = JSON.JsonHelper.Deserialize <string[]>(options); downloadOptions = new TransferOptions(); downloadOptions.Url = optionStrings[0]; bool trustAll = false; downloadOptions.TrustAllHosts = trustAll; downloadOptions.Id = optionStrings[1]; downloadOptions.FilePath = "content_sync/downloads/" + downloadOptions.Id; if (String.Equals(optionStrings[2], "replace")) { downloadOptions.Type = Replace; } else { downloadOptions.Type = Merge; } downloadOptions.Headers = optionStrings[3]; bool copyCordovaAssets = false; bool.TryParse(optionStrings[4], out copyCordovaAssets); downloadOptions.CopyCordovaAssets = copyCordovaAssets; downloadOptions.CallbackId = callbackId = optionStrings[5]; } catch (Exception) { DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION)); return; } try { // not sure if we still need this // is the URL a local app file? if (downloadOptions.Url.StartsWith("x-wmapp0") || downloadOptions.Url.StartsWith("file:")) { using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication()) { string cleanUrl = downloadOptions.Url.Replace("x-wmapp0:", "").Replace("file:", "").Replace("//", ""); // pre-emptively create any directories in the FilePath that do not exist string directoryName = getDirectoryName(downloadOptions.FilePath); if (!string.IsNullOrEmpty(directoryName) && !isoFile.DirectoryExists(directoryName)) { isoFile.CreateDirectory(directoryName); } // just copy from one area of iso-store to another ... if (isoFile.FileExists(downloadOptions.Url)) { isoFile.CopyFile(downloadOptions.Url, downloadOptions.FilePath); } else { // need to unpack resource from the dll Uri uri = new Uri(cleanUrl, UriKind.Relative); var resource = Application.GetResourceStream(uri); if (resource != null) { // create the file destination if (!isoFile.FileExists(downloadOptions.FilePath)) { var destFile = isoFile.CreateFile(downloadOptions.FilePath); destFile.Close(); } using (FileStream fileStream = new IsolatedStorageFileStream(downloadOptions.FilePath, FileMode.Create, FileAccess.Write, isoFile)) { long totalBytes = resource.Stream.Length; int bytesRead = 0; using (BinaryReader reader = new BinaryReader(resource.Stream)) { using (BinaryWriter writer = new BinaryWriter(fileStream)) { int BUFFER_SIZE = 1024; byte[] buffer; while (true) { buffer = reader.ReadBytes(BUFFER_SIZE); // fire a progress event ? bytesRead += buffer.Length; if (buffer.Length > 0) { writer.Write(buffer); DispatchSyncProgress(bytesRead, totalBytes, 1, callbackId); } else { writer.Close(); reader.Close(); fileStream.Close(); break; } } } } } } } } string result = "{ \"localPath\": \"" + downloadOptions.FilePath + "\" , \"Id\" : \"" + downloadOptions.Id + "\"}"; if (result != null) { DispatchCommandResult(new PluginResult(PluginResult.Status.OK, result), callbackId); } else { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, 0), callbackId); } return; } else { // otherwise it is web-bound, we will actually download it //Debug.WriteLine("Creating WebRequest for url : " + downloadOptions.Url); webRequest = (HttpWebRequest)WebRequest.Create(downloadOptions.Url); } } catch (Exception /*ex*/) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new SyncError(InvalidUrlError, downloadOptions.Url, null, 0))); return; } if (downloadOptions != null && webRequest != null) { DownloadRequestState state = new DownloadRequestState(); state.options = downloadOptions; state.request = webRequest; InProcDownloads[downloadOptions.Id] = state; if (!string.IsNullOrEmpty(downloadOptions.Headers)) { Dictionary <string, string> headers = parseHeaders(downloadOptions.Headers); foreach (string key in headers.Keys) { webRequest.Headers[key] = headers[key]; } } try { webRequest.BeginGetResponse(new AsyncCallback(downloadCallback), state); } catch (WebException) { // eat it } // dispatch an event for progress ( 0 ) lock (state) { if (!state.isCancelled) { var plugRes = new PluginResult(PluginResult.Status.OK, new SyncProgress()); plugRes.KeepCallback = true; plugRes.CallbackId = callbackId; DispatchCommandResult(plugRes, callbackId); } } } }
//cranberrygame end: AdmobPluginDelegate //cranberrygame start: Plugin /* * public CallbackContext getCallbackContextKeepCallback() * { * return callbackContextKeepCallback; * } * * public CordovaInterface getCordova() * { * return cordova; * } * * public CordovaWebView getWebView() * { * return webView; * } */ public void DispatchCommandResult(PluginResult pr) { base.DispatchCommandResult(pr, CurrentCommandCallbackIdKeepCallback); }
public void download(string options) { TransferOptions downloadOptions = null; HttpWebRequest webRequest = null; string callbackId; try { // source, target, trustAllHosts, this._id, headers string[] optionStrings = JSON.JsonHelper.Deserialize <string[]>(options); downloadOptions = new TransferOptions(); downloadOptions.Url = optionStrings[0]; downloadOptions.FilePath = optionStrings[1]; bool trustAll = false; bool.TryParse(optionStrings[2], out trustAll); downloadOptions.TrustAllHosts = trustAll; downloadOptions.Id = optionStrings[3]; downloadOptions.Headers = optionStrings[4]; downloadOptions.CallbackId = callbackId = optionStrings[5]; } catch (Exception) { DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION)); return; } try { // is the URL a local app file? if (downloadOptions.Url.StartsWith("x-wmapp0") || downloadOptions.Url.StartsWith("file:")) { using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication()) { // just copy from one area of iso-store to another ... if (isoFile.FileExists(downloadOptions.Url)) { isoFile.CopyFile(downloadOptions.Url, downloadOptions.FilePath); } else { // need to unpack resource from the dll string cleanUrl = downloadOptions.Url.Replace("x-wmapp0:", "").Replace("file:", ""); Uri uri = new Uri(cleanUrl, UriKind.Relative); var resource = Application.GetResourceStream(uri); if (resource != null) { // create the file destination if (!isoFile.FileExists(downloadOptions.FilePath)) { var destFile = isoFile.CreateFile(downloadOptions.FilePath); destFile.Close(); } using (FileStream fileStream = new IsolatedStorageFileStream(downloadOptions.FilePath, FileMode.Open, FileAccess.Write, isoFile)) { long totalBytes = resource.Stream.Length; int bytesRead = 0; using (BinaryReader reader = new BinaryReader(resource.Stream)) { using (BinaryWriter writer = new BinaryWriter(fileStream)) { int BUFFER_SIZE = 1024; byte[] buffer; while (true) { buffer = reader.ReadBytes(BUFFER_SIZE); // fire a progress event ? bytesRead += buffer.Length; if (buffer.Length > 0) { writer.Write(buffer); DispatchFileTransferProgress(bytesRead, totalBytes, callbackId); } else { writer.Close(); reader.Close(); fileStream.Close(); break; } } } } } } } } File.FileEntry entry = File.FileEntry.GetEntry(downloadOptions.FilePath); if (entry != null) { DispatchCommandResult(new PluginResult(PluginResult.Status.OK, entry), callbackId); } else { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, File.NOT_FOUND_ERR), callbackId); } return; } else { // otherwise it is web-bound, we will actually download it //Debug.WriteLine("Creating WebRequest for url : " + downloadOptions.Url); webRequest = (HttpWebRequest)WebRequest.Create(downloadOptions.Url); } } catch (Exception /*ex*/) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new FileTransferError(InvalidUrlError, downloadOptions.Url, null, 0))); return; } if (downloadOptions != null && webRequest != null) { DownloadRequestState state = new DownloadRequestState(); state.options = downloadOptions; state.request = webRequest; InProcDownloads[downloadOptions.Id] = state; if (!string.IsNullOrEmpty(downloadOptions.Headers)) { Dictionary <string, string> headers = parseHeaders(downloadOptions.Headers); foreach (string key in headers.Keys) { webRequest.Headers[key] = headers[key]; } } try { webRequest.BeginGetResponse(new AsyncCallback(downloadCallback), state); } catch (WebException) { // eat it } // dispatch an event for progress ( 0 ) lock (state) { if (!state.isCancelled) { var plugRes = new PluginResult(PluginResult.Status.OK, new FileTransferProgress()); plugRes.KeepCallback = true; plugRes.CallbackId = callbackId; DispatchCommandResult(plugRes, callbackId); } } } }
private void contacts_SearchCompleted(object sender, ContactsSearchEventArgs e) { ContactSearchParams searchParams = (ContactSearchParams)e.State; List <Contact> foundContacts = null; // if we have multiple search fields if (searchParams.options.filter.Length > 0 && searchParams.fields.Count() > 1) { foundContacts = new List <Contact>(); if (searchParams.fields.Contains("emails")) { foundContacts.AddRange(from Contact con in e.Results from ContactEmailAddress a in con.EmailAddresses where a.EmailAddress.Contains(searchParams.options.filter) select con); } if (searchParams.fields.Contains("displayName")) { foundContacts.AddRange(from Contact con in e.Results where con.DisplayName.Contains(searchParams.options.filter) select con); } if (searchParams.fields.Contains("name")) { foundContacts.AddRange(from Contact con in e.Results where con.CompleteName != null && con.CompleteName.ToString().Contains(searchParams.options.filter) select con); } if (searchParams.fields.Contains("phoneNumbers")) { foundContacts.AddRange(from Contact con in e.Results from ContactPhoneNumber a in con.PhoneNumbers where a.PhoneNumber.Contains(searchParams.options.filter) select con); } if (searchParams.fields.Contains("urls")) { foundContacts.AddRange(from Contact con in e.Results from string a in con.Websites where a.Contains(searchParams.options.filter) select con); } } else { foundContacts = new List <Contact>(e.Results); } //List<string> contactList = new List<string>(); string strResult = ""; IEnumerable <Contact> distinctContacts = foundContacts.Distinct(); foreach (Contact contact in distinctContacts) { strResult += FormatJSONContact(contact, null) + ","; //contactList.Add(FormatJSONContact(contact, null)); if (!searchParams.options.multiple) { break; // just return the first item } } PluginResult result = new PluginResult(PluginResult.Status.OK); result.Message = "[" + strResult.TrimEnd(',') + "]"; DispatchCommandResult(result); }
private void bw_DoWork(object sender, DoWorkEventArgs e) { Byte[] result = new Byte[10000]; BackgroundWorker worker = sender as BackgroundWorker; ThreadArguments ta = e.Argument as ThreadArguments; int resLen = Scanner.MWBscanGrayscaleImage(ta.pixels, ta.width, ta.height, result); //ignore positive result if closing is in progress if (isClosing) { resLen = -1; } if (resLen > 0 && resultDisplayed) { resLen = -1; } MWResult mwResult = null; if (resLen > 0 && Scanner.MWBgetResultType() == Scanner.MWB_RESULT_TYPE_MW) { MWResults results = new MWResults(result); if (results.count > 0) { mwResult = results.getResult(0); result = mwResult.bytes; } } if (lastTime != null && lastTime.Ticks > 0) { long timePrev = lastTime.Ticks; long timeNow = DateTime.Now.Ticks; long timeDifference = (timeNow - timePrev) / 10000; //System.Diagnostics.Debug.WriteLine("frame time: {0}", timeDifference); } lastTime = DateTime.Now; //ignore results shorter than 4 characters for barcodes with weak checksum if (mwResult != null && mwResult.bytesLength > 4 || (mwResult != null && mwResult.bytesLength > 0 && mwResult.type != Scanner.FOUND_39 && mwResult.type != Scanner.FOUND_25_INTERLEAVED && mwResult.type != Scanner.FOUND_25_STANDARD)) { Scanner.MWBsetDuplicate(mwResult.bytes, mwResult.bytesLength); resultDisplayed = true; String typeName = BarcodeHelper.getBarcodeName(mwResult); Deployment.Current.Dispatcher.BeginInvoke(delegate() { BarcodeHelper.scannerResult = new ScannerResult(); BarcodeHelper.resultAvailable = true; BarcodeHelper.scannerResult.code = mwResult.text; BarcodeHelper.scannerResult.type = BarcodeHelper.getBarcodeName(mwResult); BarcodeHelper.scannerResult.isGS1 = mwResult.isGS1; if (mwResult.locationPoints != null) { BarcodeHelper.scannerResult.location = "{\"p1\":{\"x\":" + floatToStrDot(mwResult.locationPoints.p1.x) + ", \"y\":" + floatToStrDot(mwResult.locationPoints.p1.y) + "}," + "\"p2\":{\"x\":" + floatToStrDot(mwResult.locationPoints.p2.x) + ", \"y\":" + floatToStrDot(mwResult.locationPoints.p2.y) + "}," + "\"p3\":{\"x\":" + floatToStrDot(mwResult.locationPoints.p3.x) + ", \"y\":" + floatToStrDot(mwResult.locationPoints.p3.y) + "}," + "\"p4\":{\"x\":" + floatToStrDot(mwResult.locationPoints.p4.x) + ", \"y\":" + floatToStrDot(mwResult.locationPoints.p4.y) + "}}"; } else { BarcodeHelper.scannerResult.location = "false"; } BarcodeHelper.scannerResult.imageWidth = mwResult.imageWidth; BarcodeHelper.scannerResult.imageHeight = mwResult.imageHeight; Byte[] binArray = new Byte[mwResult.bytesLength]; for (int i = 0; i < mwResult.bytesLength; i++) { binArray[i] = mwResult.bytes[i]; } BarcodeHelper.scannerResult.bytes = binArray; stopCamera(); string resultString = "{\"code\":" + JsonHelper.Serialize(BarcodeHelper.scannerResult.code) + "," + "\"type\":" + JsonHelper.Serialize(BarcodeHelper.scannerResult.type) + "," + "\"bytes\":" + JsonHelper.Serialize(BarcodeHelper.scannerResult.bytes) + "," + "\"isGS1\":" + JsonHelper.Serialize(BarcodeHelper.scannerResult.isGS1) + "," + "\"location\":" + BarcodeHelper.scannerResult.location + "," + "\"imageWidth\":" + BarcodeHelper.scannerResult.imageWidth + "," + "\"imageHeight\":" + BarcodeHelper.scannerResult.imageHeight + "}"; PluginResult pResult = new PluginResult(PluginResult.Status.OK, resultString); pResult.KeepCallback = true; MWBarcodeScanner.mwbScanner.DispatchCommandResult(pResult, MWBarcodeScanner.kallbackID); if (param_CloseScannerOnDecode) { isClosing = true; if (isPage) { NavigationService.GoBack(); } else { MWBarcodeScanner.mwbScanner.stopScanner(""); } resultDisplayed = false; } isProcessing = false; }); } else { isProcessing = false; } activeThreads--; }
private void updateConnectionType(string type) { // This should also implicitly fire offline/online events as that is handled on the JS side if (this.HasCallback) { PluginResult result = new PluginResult(PluginResult.Status.OK, type); result.KeepCallback = true; DispatchCommandResult(result); } }
public void DispatchCommandResult(PluginResult result, string callbackId = "") { if (!string.IsNullOrEmpty(callbackId)) { result.CallbackId = callbackId; } else { result.CallbackId = this.CurrentCommandCallbackId; } if (ResultHandlers.ContainsKey(result.CallbackId)) { ResultHandlers[result.CallbackId](this, result); } else if (this.OnCommandResult != null) { OnCommandResult(this, result); } else { Debug.WriteLine("Failed to locate callback for id : " + result.CallbackId); } if (!result.KeepCallback) { this.Dispose(); } }
private void OnOutboxChanged(object sender, MessageStoreChangedEventArgs e) { if (outboxChangeCallbacks.Count == 0) { return; } try { JObject json = new JObject(); switch (e.Action) { case CommonTime.Notification.MessageAction.Sending: { json["action"] = "SENDING"; break; } case CommonTime.Notification.MessageAction.Sent: { json["action"] = "SENT"; break; } case CommonTime.Notification.MessageAction.SendFailed: { json["action"] = "FAILED"; break; } case CommonTime.Notification.MessageAction.SendFailedWillRetry: { json["action"] = "FAILED_WILL_RETRY"; break; } default: { return; } } json["message"] = MessageFactory.Instance.MakeJObject(e.Message); PluginResult result = new PluginResult(PluginResult.Status.OK); result.Message = json.ToString(); result.KeepCallback = true; foreach (string callbackId in outboxChangeCallbacks.Values) { DispatchCommandResult(result, callbackId); } } catch (Exception ex) { Logger.WarnFormat("An error occurred while processing outbox change: {0}", ex.Message); } }
/// <summary> /// Sensor listener event /// </summary> private void accelerometer_CurrentValueChanged(object sender, SensorReadingEventArgs<AccelerometerReading> e) { this.SetStatus(Running); PluginResult result = new PluginResult(PluginResult.Status.OK, GetCurrentAccelerationFormatted()); result.KeepCallback = true; DispatchCommandResult(result); }
/// <summary> /// Initializes a new instance of the <see cref="PluginExecutionResult" /> class. /// </summary> /// <param name="result">The <see cref="PluginResult" /> representing the execution outcome.</param> /// <param name="exception">The exception whose message describes the result of the execution.</param> /// <param name="category">The category used for grouping similar messages together.</param> /// <exception cref="ArgumentNullException"><paramref name="exception" /> is null.</exception> public PluginExecutionResult(PluginResult result, Exception exception, string category) : this(result, exception) { Category = category; }
public void unzip(string options) { string[] optionStrings; string srcFilePath; string destPath = ""; string callbackId = CurrentCommandCallbackId; try { optionStrings = JSON.JsonHelper.Deserialize <string[]>(options); srcFilePath = optionStrings[0]; destPath = optionStrings[1]; callbackId = optionStrings[2]; } catch (Exception) { DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION), callbackId); return; } using (IsolatedStorageFile appStorage = IsolatedStorageFile.GetUserStoreForApplication()) { // DEBUG here to copy file from dll to isostore ... // this is only really needed if you want to test with a file in your package/project StreamResourceInfo fileResourceStreamInfo = Application.GetResourceStream(new Uri(srcFilePath, UriKind.Relative)); if (fileResourceStreamInfo != null) { using (BinaryReader br = new BinaryReader(fileResourceStreamInfo.Stream)) { byte[] data = br.ReadBytes((int)fileResourceStreamInfo.Stream.Length); // This will truncate/overwrite an existing file, or using (IsolatedStorageFileStream outFile = appStorage.OpenFile(srcFilePath, FileMode.Create)) { using (var writer = new BinaryWriter(outFile)) { writer.Write(data); } } } } IsolatedStorageFileStream zipStream = null; ZipArchive zipArch = null; try { zipStream = new IsolatedStorageFileStream(srcFilePath, FileMode.Open, FileAccess.Read, appStorage); } catch (Exception) { Debug.WriteLine("File not found :: " + srcFilePath); DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR), callbackId); return; } if (zipStream != null) { zipArch = new ZipArchive(zipStream); } if (zipArch != null) { int totalFiles = zipArch.FileNames.Count(); int current = 0; try { foreach (string filename in zipArch.FileNames) { string destFilePath = destPath + "/" + filename; string directoryName = getDirectoryName(destFilePath); //Debug.WriteLine("upacking file : " + filename + " to : " + destFilePath); if (!appStorage.DirectoryExists(directoryName)) { appStorage.CreateDirectory(directoryName); } using (Stream readStream = zipArch.GetFileStream(filename)) { if (readStream != null) { using (FileStream outStream = new IsolatedStorageFileStream(destFilePath, FileMode.OpenOrCreate, FileAccess.Write, appStorage)) { WriteStreamToPath(readStream, outStream); FileUnzipProgress progEvt = new FileUnzipProgress(totalFiles, current++); PluginResult plugRes = new PluginResult(PluginResult.Status.OK, progEvt); plugRes.KeepCallback = true; plugRes.CallbackId = callbackId; DispatchCommandResult(plugRes, callbackId); } } } } DispatchCommandResult(new PluginResult(PluginResult.Status.OK), callbackId); } catch (Exception) { Debug.WriteLine("File not found :: " + srcFilePath); DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR), callbackId); } } } }
/// <summary> /// Report Media status to JS /// </summary> public void ReportStatus(MediaStatus status) { PluginResult result = new PluginResult(PluginResult.Status.OK, new MediaChannelStatusAction() { Status = status }); result.KeepCallback = true; DispatchCommandResult(result, messageChannelCallbackId); }
void DataReceived(ClaimedBarcodeScanner sender, BarcodeScannerDataReceivedEventArgs args) { PluginResult result = new PluginResult(PluginResult.Status.OK, this.GetDataString(args.Report.ScanData)); result.KeepCallback = true; DispatchCommandResult(result); }
private void Battery_RemainingChargePercentChanged(object sender, object e) { PluginResult result = new PluginResult(PluginResult.Status.OK, GetCurrentBatteryStateFormatted()); result.KeepCallback = true; DispatchCommandResult(result); }
void compass_CurrentValueChanged(object sender, Microsoft.Devices.Sensors.SensorReadingEventArgs<CompassReading> e) { this.SetStatus(Running); if (compass.IsDataValid) { // trueHeading :: The heading in degrees from 0 - 359.99 at a single moment in time. // magneticHeading:: The heading relative to the geographic North Pole in degrees 0 - 359.99 at a single moment in time. // A negative value indicates that the true heading could not be determined. // headingAccuracy :: The deviation in degrees between the reported heading and the true heading. //rawMagnetometerReading = e.SensorReading.MagnetometerReading; //Debug.WriteLine("Compass Result :: " + GetHeadingFormatted(e.SensorReading)); PluginResult result = new PluginResult(PluginResult.Status.OK, GetHeadingFormatted(e.SensorReading)); result.KeepCallback = true; DispatchCommandResult(result); } }
public async Task <PluginResult> Handle(BotMessage message, CommandItems commandItems, CancellationToken token) { var text = message.Text; var chatId = message.ChatId; StringBuilder result = new(); var cost = commandItems.GetDecimal("cost"); var user = await _userService.GetUserAsync(chatId, token); if (user == null) { var sourceAdapter = _sourceAdapterFactory.GetAdapter(message.SourceId); var name = await sourceAdapter.GetName(message.ChatId, token); user = await _userService.AddUserAsync(new AddUserRequest { ChatId = chatId, Name = name }, token); result.AppendLine(AccountantText.WelcomeUser(name)); } var comment = commandItems.GetString("comment"); var categoryName = commandItems.GetString("category"); var categoryExpense = await _accountantService.GetExpenseCategory(user.Id, categoryName, token); var categoryIncome = await _accountantService.GetIncomeCategory(user.Id, categoryName, token); var from = GetCurrentMonthDate(10); var to = from.AddMonths(1); if (categoryExpense == null && categoryIncome == null) { categoryExpense = await _accountantService.AddCategory(new Inbound.AddExpenseCategoryRequest { UserId = user.Id, Name = categoryName }, token); result.AppendLine(AccountantText.AddedNewCategory(categoryName)); } if (categoryExpense != null) { var expense = new Inbound.AddTransactionRequest { Cost = cost, Comment = comment, CategoryId = categoryExpense.Id, UserId = user.Id }; await _accountantService.AddTransaction(expense, token); var categoryBalance = await _accountantService.GetBalance(user.Id, categoryExpense.Id, from, to, token); result.AppendLine( AccountantText.AddedNewExpenseTransaction(categoryName, from, to, categoryBalance)); } else if (categoryIncome != null) { var income = new Inbound.AddTransactionRequest() { Cost = cost, Comment = comment, CategoryId = categoryIncome.Id, UserId = user.Id }; await _accountantService.AddTransaction(income, token); var categoryBalance = await _accountantService.GetBalance(user.Id, categoryIncome.Id, from, to, token); result.AppendLine( AccountantText.AddedNewIncomeTransaction(categoryName, from, to, categoryBalance)); } var balance = await _accountantService.GetBalance(user.Id, token); result.AppendLine(); result.AppendLine(AccountantText.RemainingBalance(balance)); return(PluginResult.Success(result.ToString())); }
void browser_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e) { #if WP8 if (browser != null) { backButton.IsEnabled = browser.CanGoBack; fwdButton.IsEnabled = browser.CanGoForward; } #endif string message = "{\"type\":\"loadstop\", \"url\":\"" + e.Uri.OriginalString + "\"}"; PluginResult result = new PluginResult(PluginResult.Status.OK, message); result.KeepCallback = true; this.DispatchCommandResult(result, NavigationCallbackId); }
/// <summary> /// Initializes a new instance of the <see cref="PluginExecutionResult" /> class. /// </summary> /// <param name="result">The <see cref="PluginResult" /> representing the execution outcome.</param> /// <param name="message">The message describing the result of the execution.</param> /// <param name="category">The category used for grouping similar messages together.</param> public PluginExecutionResult(PluginResult result, string message, string category) : this(result, message) { Category = category; }
void browser_Navigating(object sender, NavigatingEventArgs e) { string message = "{\"type\":\"loadstart\",\"url\":\"" + e.Uri.OriginalString + "\"}"; PluginResult result = new PluginResult(PluginResult.Status.OK, message); result.KeepCallback = true; this.DispatchCommandResult(result, NavigationCallbackId); }
void cam_PreviewFrameAvailable(ICameraCaptureDevice device, object sender) { if (closeScanner) { closeScanner = false; Deployment.Current.Dispatcher.BeginInvoke(delegate() { string resultString = "{\"type\":" + JsonHelper.Serialize("Cancel") + "}"; PluginResult pResult = new PluginResult(PluginResult.Status.OK, resultString); pResult.KeepCallback = true; MWBarcodeScanner.mwbScanner.DispatchCommandResult(pResult, MWBarcodeScanner.kallbackID); if (this.NavigationService.CanGoBack) { this.NavigationService.GoBack(); } return; }); } if (activeThreads >= param_maxThreads || resultDisplayed) { return; } if (isClosing) { return; } activeThreads++; // System.Diagnostics.Debug.WriteLine("ActiveThreads: " + activeThreads.ToString()); isProcessing = true; int len = (int)device.PreviewResolution.Width * (int)device.PreviewResolution.Height; if (pixels == null) { pixels = new byte[len]; } device.GetPreviewBufferY(pixels); // Byte[] result = new Byte[10000]; int width = (int)device.PreviewResolution.Width; int height = (int)device.PreviewResolution.Height; ThreadArguments ta = new ThreadArguments(); ta.height = height; ta.width = width; ta.pixels = pixels; BackgroundWorker bw1 = new BackgroundWorker(); bw1.WorkerReportsProgress = false; bw1.WorkerSupportsCancellation = false; bw1.DoWork += new DoWorkEventHandler(bw_DoWork); bw1.RunWorkerAsync(ta); }
/// <summary> /// Initializes a new instance of the <see cref="PluginExecutionResult" /> class. /// </summary> /// <param name="result">The <see cref="PluginResult" /> representing the execution outcome.</param> public PluginExecutionResult(PluginResult result) { Result = result; }
private void DispatchNonFinalResult(PluginResult.Status status, object message = null) { string callbackId = CurrentCommandCallbackId ?? this.callbackId; if (callbackId == null) { throw new InvalidOperationException("No callback id is available"); } PluginResult result = message != null ? new PluginResult(status, message) : new PluginResult(status); result.KeepCallback = true; this.DispatchCommandResult(result, callbackId); }
private void contacts_SearchCompleted(object sender, ContactsSearchEventArgs e) { ContactSearchParams searchParams = (ContactSearchParams)e.State; List<Contact> foundContacts = null; // used for comparing strings, "" instantiates with InvariantCulture CultureInfo culture = new CultureInfo(""); // make the search comparisons case insensitive. CompareOptions compare_option = CompareOptions.IgnoreCase; // if we have multiple search fields if (!String.IsNullOrEmpty(searchParams.options.filter) && searchParams.fields.Count() > 1) { foundContacts = new List<Contact>(); if (searchParams.fields.Contains("emails")) { foundContacts.AddRange(from Contact con in e.Results from ContactEmailAddress a in con.EmailAddresses where culture.CompareInfo.IndexOf(a.EmailAddress, searchParams.options.filter, compare_option) >= 0 select con); } if (searchParams.fields.Contains("displayName")) { foundContacts.AddRange(from Contact con in e.Results where culture.CompareInfo.IndexOf(con.DisplayName, searchParams.options.filter, compare_option) >= 0 select con); } if (searchParams.fields.Contains("name")) { foundContacts.AddRange( from Contact con in e.Results where con.CompleteName != null && ( (con.CompleteName.FirstName != null && culture.CompareInfo.IndexOf(con.CompleteName.FirstName, searchParams.options.filter, compare_option) >= 0) || (con.CompleteName.LastName != null && culture.CompareInfo.IndexOf(con.CompleteName.LastName, searchParams.options.filter, compare_option) >= 0) || (con.CompleteName.MiddleName != null && culture.CompareInfo.IndexOf(con.CompleteName.MiddleName, searchParams.options.filter, compare_option) >= 0) || (con.CompleteName.Nickname != null && culture.CompareInfo.IndexOf(con.CompleteName.Nickname, searchParams.options.filter, compare_option) >= 0) || (con.CompleteName.Suffix != null && culture.CompareInfo.IndexOf(con.CompleteName.Suffix, searchParams.options.filter, compare_option) >= 0) || (con.CompleteName.Title != null && culture.CompareInfo.IndexOf(con.CompleteName.Title, searchParams.options.filter, compare_option) >= 0) || (con.CompleteName.YomiFirstName != null && culture.CompareInfo.IndexOf(con.CompleteName.YomiFirstName, searchParams.options.filter, compare_option) >= 0) || (con.CompleteName.YomiLastName != null && culture.CompareInfo.IndexOf(con.CompleteName.YomiLastName, searchParams.options.filter, compare_option) >= 0)) select con); } if (searchParams.fields.Contains("phoneNumbers")) { foundContacts.AddRange(from Contact con in e.Results from ContactPhoneNumber a in con.PhoneNumbers where culture.CompareInfo.IndexOf(a.PhoneNumber, searchParams.options.filter, compare_option) >= 0 select con); } if (searchParams.fields.Contains("urls")) { foundContacts.AddRange(from Contact con in e.Results from string a in con.Websites where culture.CompareInfo.IndexOf(a, searchParams.options.filter, compare_option) >= 0 select con); } } else { foundContacts = new List<Contact>(e.Results); } //List<string> contactList = new List<string>(); string strResult = ""; IEnumerable<Contact> distinctContacts = foundContacts.Distinct(); foreach (Contact contact in distinctContacts) { strResult += FormatJSONContact(contact, null) + ","; //contactList.Add(FormatJSONContact(contact, null)); if (!searchParams.options.multiple) { break; // just return the first item } } PluginResult result = new PluginResult(PluginResult.Status.OK); result.Message = "[" + strResult.TrimEnd(',') + "]"; DispatchCommandResult(result); }
public void registerForPush(string options) { PushOptions pushOptions; if (!TryDeserializeOptions(options, out pushOptions)) { DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION)); return; } #if DEBUG Debug.WriteLine("Registering for push on channel " + pushOptions.ChannelName); #endif HttpNotificationChannel pushChannel = HttpNotificationChannel.Find(pushOptions.ChannelName); ChannelListener channelListener = null; if (!channelListeners.TryGetValue(pushOptions.ChannelName, out channelListener)) { channelListener = new ChannelListener(pushOptions.ChannelName, this, this.CurrentCommandCallbackId); channelListeners[pushOptions.ChannelName] = channelListener; } if (pushChannel == null) { pushChannel = new HttpNotificationChannel(pushOptions.ChannelName); channelListener.Subscribe(pushChannel); try { for (int tries = 0; tries < 3 && pushChannel.ChannelUri == null; ++tries) { pushChannel.Open(); } } catch (InvalidOperationException) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, InvalidRegistrationError)); return; } pushChannel.BindToShellToast(); pushChannel.BindToShellTile(); } else { channelListener.Subscribe(pushChannel); } if (pushChannel.ChannelUri != null) { #if DEBUG Debug.WriteLine("Already registered for push on channel " + pushChannel.ChannelName + " with URI " + pushChannel.ChannelUri); #endif PluginResult result = new PluginResult(PluginResult.Status.OK, pushChannel.ChannelUri.ToString()); result.KeepCallback = true; DispatchCommandResult(result); } FireAllPendingEvents(); }