private void ValidateRanges(BLECommandSetDataModel data, Action onSuccess, OnErr onError) { ErrReport report; WrapErr.ToErrReport(out report, 9999, () => { string error = string.Empty; foreach (ScriptItem item in data.Items) { this.ValidateBLECmdItem(data.DataType, item, () => { }, (err) => { if (error == string.Empty) { error = err; } }); } if (error == string.Empty) { onSuccess(); } else { onError(error); } }); if (report.Code != 0) { WrapErr.SafeAction(() => onError(report.Msg)); } }
public void GetMenuItemDataModel( MenuCode menuCode, MsgCode msgCode, UIIcon iconCode, string padding, Action <MenuItemDataModel> onSuccess, Action <MenuItemDataModel> onError) { WrapErr.ToErrReport(9999, () => { ErrReport report; WrapErr.ToErrReport(out report, 9999, () => { onSuccess(new MenuItemDataModel() { Code = menuCode, Display = this.GetText(msgCode), IconSource = this.IconSource(iconCode), Padding = padding, }); }); if (report.Code != 0) { WrapErr.SafeAction(() => { onError.Invoke(new MenuItemDataModel() { Code = menuCode, Display = "**NA**", IconSource = "", Padding = padding, }); }); } }); }
private async Task <WifiErrorCode> ConnectToNetwork(WiFiAdapter adapter, string ssid, string password) { try { // Should already be scanned WiFiNetworkReport report = adapter.NetworkReport; WifiErrorCode returnValue = WifiErrorCode.NetworkNotAvailable; foreach (var net in report.AvailableNetworks) { if (net.Ssid == ssid) { // TODO Will need to have multiple types of authentication PasswordCredential cred = new PasswordCredential() { Password = password }; returnValue = (await adapter.ConnectAsync(net, WiFiReconnectionKind.Automatic, cred)).ConnectionStatus.Convert(); break; } } if (returnValue != WifiErrorCode.Success) { this.OnError?.Invoke(this, new WifiError(returnValue)); } return(returnValue); } catch (Exception e) { WrapErr.SafeAction(() => { this.OnError?.Invoke(this, new WifiError(WifiErrorCode.Unknown)); }); return(WifiErrorCode.Unknown); } }
public void RetrieveCodeFile(CodeSelectDisplayDataModel dataModel, Action <string> onSuccess, OnErr onError) { WrapErr.ToErrReport(9999, () => { ErrReport report; WrapErr.ToErrReport(out report, 9999, () => { if (dataModel == null) { onError(this.GetText(MsgCode.NothingSelected)); } else { string filename = this.CodeFileName(dataModel.Code); if (File.Exists(filename)) { onSuccess.Invoke(File.ReadAllText(filename)); } else { onError.Invoke(this.GetText(MsgCode.NotFound)); } } }); if (report.Code != 0) { WrapErr.SafeAction(() => onError(report.Msg)); } }); }
//https://stackoverflow.com/questions/45191412/deviceinformation-pairasync-not-working-in-wpf private async Task DoUnPairing(BTDeviceInfo info) { try { using (BluetoothDevice device = await BluetoothDevice.FromIdAsync(info.Address)) { this.log.Info("DoUnPairing", () => string.Format("'{0}'", info.Name)); DeviceUnpairingResult result = await device.DeviceInformation.Pairing.UnpairAsync(); this.log.Info("DoUnPairing", () => string.Format("'{0}' Unpair status {1}", info.Name, result.Status.ToString())); this.BT_UnPairStatus?.Invoke(this, new BTUnPairOperationStatus() { Name = info.Name, UnpairStatus = result.Status.ConvertStatus(), IsSuccessful = result.Status.IsSuccessful(), }); } } catch (Exception e) { WrapErr.SafeAction(() => { this.BT_UnPairStatus?.Invoke(this, new BTUnPairOperationStatus() { Name = info.Name, UnpairStatus = BT_UnpairingStatus.Failed, IsSuccessful = false, }); }); } }
public void SaveLanguage(LangCode code, Action onSuccess, Action <string> onError) { WrapErr.ToErrReport(9999, () => { ErrReport report; WrapErr.ToErrReport(out report, 9999, () => { this.languages.SetCurrentLanguage(code); SettingItems items = this.settings.ReadObjectFromDefaultFile(); items.Language = code; items.LanguageName = this.languages.CurrentLanguage.Language.Display; if (this.settings.WriteObjectToDefaultFile(items)) { onSuccess.Invoke(); } else { // TODO Language onError.Invoke("Failed"); } }); if (report.Code != 0) { // TODO - language WrapErr.SafeAction(() => { onError.Invoke("Unhandled Error on saving language"); }); } }); }
public void GetCodeSample(CommMedium helpType, Action <string> onSuccess, OnErrTitle onError) { ErrReport report; WrapErr.ToErrReport(out report, 9999, () => string.Format(""), () => { string filename = this.GetFilename(helpType); if (filename.Length > 0) { // TODO - Move to cross platform access if (File.Exists(filename)) { onSuccess.Invoke(File.ReadAllText(filename)); return; } } onError(this.GetText(MsgCode.Error), "* N/Ax *"); }); if (report.Code != 0) { WrapErr.SafeAction(() => { onError.Invoke(this.GetText(MsgCode.Error), report.Msg); }); } }
public void NoExceptionPropagation() { Assert.DoesNotThrow(() => { WrapErr.SafeAction(() => { Console.WriteLine("Throwing Exception within safe block"); throw new Exception("This should be caught"); }); }); }
/// <summary> /// Push the log message to the log message event subscribers /// </summary> /// <param name="eventData"></param> private static void RaiseEvent(MsgLevel level, ErrReport msg) { if (Log.OnLogMsgEvent != null) { WrapErr.SafeAction(() => Log.OnLogMsgEvent(level, msg)); } else { System.Diagnostics.Debug.WriteLine("No subscribers to log message event"); } }
public void LanguageList(Action <List <LanguageDataModel> > onDone) { WrapErr.ToErrReport(9999, () => { ErrReport report; WrapErr.ToErrReport(out report, 9999, () => { onDone(this.languages.AvailableLanguages); }); if (report.Code != 0) { WrapErr.SafeAction(() => { onDone(new List <LanguageDataModel>()); }); } }); }
public void CurrentLanguage(Action <LangCode> onDone) { WrapErr.ToErrReport(9999, () => { ErrReport report; WrapErr.ToErrReport(out report, 9999, () => { onDone(this.languages.CurrentLanguageCode); }); if (report.Code != 0) { WrapErr.SafeAction(() => { onDone(this.languages.CurrentLanguageCode); }); } }); }
/// <summary> /// Safely dispose of the existing timer /// </summary> private void DisposeTimer() { lock (this.timerLock) { if (this.timer != null) { WrapErr.SafeAction(() => this.timer.Stop()); WrapErr.SafeAction(() => this.timer.Elapsed -= this.onTimerWakeup); WrapErr.SafeAction(() => this.timer.Dispose()); this.timer = null; } } }
public void ReturnsValidObj() { // The safe wrapper should overwrite the valid object with default(obj1) obj1 o1 = null; Assert.DoesNotThrow(() => { o1 = WrapErr.SafeAction(() => { return(new obj1()); }); }); Assert.IsNotNull(o1); }
/// <summary> /// Dispose resources /// </summary> /// <param name="disposeManagedResources"> /// If true it was called by the Dispose method rather than finalizer /// </param> private void Dispose(bool disposeManagedResources) { if (!disposed) { if (disposeManagedResources) { WrapErr.SafeAction(() => this.DisposeManagedResources()); } WrapErr.SafeAction(() => this.DisposeNativeResources()); } this.disposed = true; }
public void BTClassicConnectAsync(BTDeviceInfo device) { this.log.InfoEntry("BTClassicConnectAsync"); ErrReport report; WrapErr.ToErrReport(out report, 20003, "Failure on BTClassicConnectAsync", () => { this.classicBluetooth.ConnectAsync(device); }); if (report.Code != 0) { WrapErr.SafeAction(() => BT_DiscoveryComplete?.Invoke(this, false)); } }
public void DefaultObjectOnThrow() { // The safe wrapper should overwrite the valid object with default(obj1) obj1 o1 = new obj1(); Assert.DoesNotThrow(() => { o1 = WrapErr.SafeAction(() => { string s2 = null; string s3 = s2.Substring(0, 10); return(new obj1()); }); }); Assert.AreEqual(o1, default(obj1)); Assert.IsNull(o1); }
public void BLE_GetShortRangeDisplay(BLE_DataType dataType, Action <string> onSuccess, OnErr onError) { try { DataTypeDisplay display = this.validator.GetRange(dataType); onSuccess( string.Format("{0}, {1}: {2}, {3}: {4}", display.DataType, this.GetText(MsgCode.Min), display.Min, this.GetText(MsgCode.Max), display.Max)); } catch (Exception e) { this.log.Exception(9999, "", e); WrapErr.SafeAction(() => { onError.Invoke(this.GetText(MsgCode.UnhandledError)); }); } }
/// <summary> /// Add the extra info from XmlException /// </summary> /// <param name="e"></param> protected override void AddExtraInfo(Exception e) { if (e.GetType() == typeof(XmlException)) { XmlException ex = (XmlException)e; this.ExtraInfo.Add(new ExceptionExtraInfo("Line Number", ex.LineNumber.ToString())); this.ExtraInfo.Add(new ExceptionExtraInfo("Line Position", ex.LinePosition.ToString())); this.ExtraInfo.Add(new ExceptionExtraInfo("Source URI", ex.SourceUri)); } else { WrapErr.SafeAction(() => Debug.WriteLine("The Exception is a {0} instead of an XmlException", e.GetType().Name)); } }
/// <summary> /// Safely pass a Log message to the logger implementation /// </summary> /// <param name="level">The loging level of the message</param> /// <param name="err">The error report object with the information</param> void Log_OnLogMsgEvent(MsgLevel level, ErrReport err) { if (this.loggerImpl != null) { try { string msg = "NO MSG"; if (err.StackTrace.Length > 0) { msg = String.Format( "{0}\t{1}\t{2}\t{3}.{4} {5}{6}{7}", err.TimeStamp.ToString("h:mm:ss fff"), this.LogLevelShort(level), err.Code, err.AtClass, err.AtMethod, err.Msg, Environment.NewLine, err.StackTrace); } else { msg = String.Format( "{0}\t{1}\t{2}\t{3}.{4} {5}", err.TimeStamp.ToString("h:mm:ss fff"), this.LogLevelShort(level), err.Code, err.AtClass, err.AtMethod, err.Msg); } switch (level) { case MsgLevel.Info: loggerImpl.Info(msg); break; case MsgLevel.Debug: loggerImpl.Debug(msg); break; case MsgLevel.Warning: loggerImpl.Warn(msg); break; case MsgLevel.Error: case MsgLevel.Exception: loggerImpl.Error(msg); break; } #if SEND_LOG_TO_DEBUG Debug.WriteLine(msg); #endif } catch (Exception e) { WrapErr.SafeAction(() => Debug.WriteLine(String.Format("Exception on logging out message:{0}", e.Message))); } } }
private void IconInfo(UIIcon code, Action <IconDataModel> onSuccess, Action <string> onError) { ErrReport report; WrapErr.ToErrReport(out report, 9999, () => string.Format("No icon for {0}", code), () => { onSuccess.Invoke(this.iconFactory.GetIcon(code)); }); if (report.Code != 0) { WrapErr.SafeAction(() => { onError(string.Format("Unhandled error retrieving icon {0}", code)); }); } }
private void LaunchReadTask() { Task.Run(async() => { try { this.log.InfoEntry("DoReadTask +++"); this.readFinishedEvent.Reset(); while (this.continueReading) { try { int count = (int)await this.reader.LoadAsync( this.readBufferMaxSizer).AsTask(this.readCancelationToken.Token); //this.log.Info("Launch Read Task", () => string.Format("Received:{0} bytes", count)); if (count > 0) { byte[] tmpBuff = new byte[count]; this.reader.ReadBytes(tmpBuff); this.HandlerMsgReceived(this, tmpBuff); } } catch (TaskCanceledException) { this.log.Info("DoReadTask", "Cancelation"); break; } catch (Exception e) { this.log.Exception(9999, "", e); WrapErr.SafeAction(() => { this.MsgPumpConnectResultEvent?.Invoke(this, new MsgPumpResults(MsgPumpResultCode.ReadFailure)); }); break; } } this.log.InfoExit("DoReadTask ---"); this.readFinishedEvent.Set(); this.Connected = false; } catch (Exception e) { this.log.Exception(9999, "LaunchReadTask", "", e); this.readFinishedEvent.Set(); this.Connected = false; WrapErr.SafeAction(() => { this.MsgPumpConnectResultEvent?.Invoke(this, new MsgPumpResults(MsgPumpResultCode.ReadFailure)); }); } }); }
public void GetCodeList(Action <List <CodeSelectDisplayDataModel> > onSuccess, OnErr onError) { WrapErr.ToErrReport(9999, () => { ErrReport report; WrapErr.ToErrReport(out report, 9999, () => { List <CodeSelectDisplayDataModel> list = new List <CodeSelectDisplayDataModel>(); foreach (CodeFileCode code in EnumHelpers.GetEnumList <CodeFileCode>()) { list.Add(new CodeSelectDisplayDataModel(code)); } onSuccess.Invoke(list); }); if (report.Code != 0) { WrapErr.SafeAction(() => onError(report.Msg)); } }); }
/// <summary>Dispose the services manualy since the device dispose does not do it</summary> private void DisposeServices() { try { foreach (GattDeviceService service in this.currentServices) { try { service.Dispose(); } catch (Exception e) { this.log.Exception(9998, "DisposeServices", "", e); } } } catch (Exception e) { this.log.Exception(9999, "DisposeServices", "", e); } finally { WrapErr.SafeAction(this.currentServices.Clear); } }
public void HasCodeFile(CodeSelectDisplayDataModel dataModel, Action <bool> onSuccess, OnErr onError) { WrapErr.ToErrReport(9999, () => { ErrReport report; WrapErr.ToErrReport(out report, 9999, () => { if (dataModel == null) { onError(this.GetText(MsgCode.NothingSelected)); } else { onSuccess.Invoke(File.Exists(this.CodeFileName(dataModel.Code))); } }); if (report.Code != 0) { WrapErr.SafeAction(() => onError(report.Msg)); } }); }
public void BLE_GetRangeDisplay(BLE_CharacteristicDataModel dataModel, Action <string, string> onSuccess, OnErr onError) { try { if (dataModel != null) { DataTypeDisplay display = this.validator.GetRange(dataModel.Parser.DataType); onSuccess( dataModel.CharName, string.Format("{0}: {1}, {2}: {3}, {4}: {5}", this.GetText(MsgCode.DataType), display.DataType, this.GetText(MsgCode.Min), display.Min, this.GetText(MsgCode.Max), display.Max)); } } catch (Exception e) { this.log.Exception(9999, "", e); WrapErr.SafeAction(() => { onError.Invoke(this.GetText(MsgCode.UnhandledError)); }); } }
public void GetRange(BinaryMsgDataTypeDisplay dataType, Action <NumericRange> onSuccess, OnErr onError) { try { if (dataType == null) { onError(this.GetText(MsgCode.NothingSelected)); } else if (dataType.DataType == BinaryMsgDataType.tyepUndefined || dataType.DataType == BinaryMsgDataType.typeInvalid) { onError(this.GetText(MsgCode.UnhandledError)); } else { onSuccess(dataType.DataType.Range()); } } catch (Exception ex) { this.log.Exception(9999, "GetRange", "", ex); WrapErr.SafeAction(() => onError(this.GetText(MsgCode.UnknownError))); } }
/// <summary>Tear down all binders including detaching events</summary> public void ClearAll() { try { foreach (BLE_CharacteristicBinder binder in this.binders) { try { binder.DataModel.OnReadValueChanged -= onReadValueChanged; binder.Teardown(); } catch (Exception e) { this.log.Exception(9998, "ClearAll", "", e); } } } catch (Exception e) { this.log.Exception(9999, "ClearAll", "", e); } finally { WrapErr.SafeAction(this.binders.Clear); } }
public void ValidateEditValues(RawConfigValues values, Action <ValidatedConfigValues> onSuccess, OnErr onError) { try { if (string.IsNullOrEmpty(values.Name)) { onError(this.GetText(MsgCode.EmptyName)); } else { this.Validate(BinaryMsgDataType.typeUInt8, values.Id, () => { this.Validate(values.DataType, values.Min, () => { this.Validate(values.DataType, values.Max, () => { this.Validate(values.DataType, values.Step, () => { double step = double.Parse(values.Step); if (step < 1) { step *= -1; } onSuccess(new ValidatedConfigValues() { Id = values.Id.ToUInt8(), IOName = values.Name, Minimum = double.Parse(values.Min), Maximum = double.Parse(values.Max), SendAtStep = step, }); }, onError); }, onError); }, onError); }, onError); } } catch (Exception ex) { this.log.Exception(9999, "GetRange", "", ex); WrapErr.SafeAction(() => onError(this.GetText(MsgCode.UnknownError))); } }
public void BLE_Send(string value, BLE_CharacteristicDataModel dataModel, Action onSuccess, OnErr onError) { try { if (dataModel != null) { RangeValidationResult result = dataModel.Write(value); if (result.Status == BLE_DataValidationStatus.Success) { onSuccess.Invoke(); } else { onError.Invoke(this.Translate(result)); } } } catch (Exception e) { this.log.Exception(9999, "BLE_Send", "", e); WrapErr.SafeAction(() => { onError.Invoke(this.GetText(MsgCode.UnhandledError)); }); } }
public void GetFilteredBLECmdList( BLE_DataType dataType, string characteristic, Action <List <IIndexItem <BLECmdIndexExtraInfo> >, List <IIndexItem <BLECmdIndexExtraInfo> > > onSuccess, OnErr onError) { ErrReport report; WrapErr.ToErrReport(out report, 9999, "Failure on GetFilteredBLECmdList", () => { this.RetrieveIndex( this.bleCmdStorage, (idx) => { List <IIndexItem <BLECmdIndexExtraInfo> > generalResult = new List <IIndexItem <BLECmdIndexExtraInfo> >(); List <IIndexItem <BLECmdIndexExtraInfo> > specificResult = new List <IIndexItem <BLECmdIndexExtraInfo> >(); if (idx.Count > 0) { foreach (var item in idx) { if (item.ExtraInfoObj.DataType == dataType) { generalResult.Add(item); if (!string.IsNullOrWhiteSpace(characteristic) && item.ExtraInfoObj.CharacteristicName == characteristic) { specificResult.Add(item); } } } } onSuccess.Invoke(generalResult, specificResult); }, onError); }); if (report.Code != 0) { WrapErr.SafeAction(() => onError(this.GetText(MsgCode.UnknownError))); } }