public static void Info(string message) { if (IsDebuggerAttached) { Dbg.WriteLine(message); } }
public async Task <ObservableCollection <Item> > GetFilterResults(ObservableCollection <Tag> tags) { string query = tags.First().ToString(); foreach (Tag tag in tags.Skip(1)) { query += '&' + tag.ToString(); } Uri uri = new Uri(Constants.RestUrl + "items/filter/tags=" + query); ObservableCollection <Item> results = null; try { HttpResponseMessage response = await client.GetAsync(uri); if (response.IsSuccessStatusCode) { string content = await response.Content.ReadAsStringAsync(); results = JsonConvert.DeserializeObject <ObservableCollection <Item> >(content); } } catch (Exception ex) { Debug.WriteLine(@"\tERROR {0}", ex.Message); throw ex; } return(results); }
private void Test() { ControlSettings s = ControlSettings.Constructor(); for (byte i = 0; i < 32; i++) { s.TimeIntervals[i].Active = true; s.TimeIntervals[i].From.Hour = i; s.TimeIntervals[i].From.Minute = i; s.TimeIntervals[i].To.Hour = i; s.TimeIntervals[i].To.Minute = i; } communicator.SendCommandData("setsettings", s.ToByteArray()); var r = communicator.SendCommand("getsettings"); ControlSettings s2 = ControlSettings.FromByteArray(r); string str = ""; for (byte i = 0; i < 32; i++) { str += s2.TimeIntervals[i].From.Hour + "\n"; str += s2.TimeIntervals[i].From.Minute + "\n"; str += s2.TimeIntervals[i].To.Hour + "\n"; str += s2.TimeIntervals[i].To.Minute + "\n"; } Debug.WriteLine(str); Debug.Assert(s.Mode == s2.Mode); Debug.Assert(Enumerable.SequenceEqual(s.TimeIntervals, s2.TimeIntervals)); Debug.WriteLine(s2.TimeIntervals[5].To.Hour); }
/// <summary> /// Generates a PublicKey instance from a string containing the Base64-encoded public key. /// </summary> /// <param name="encodedPublicKey"> /// Base64-encoded public key /// </param> /// <returns> /// An IPublicKey that is used to verify the server data. /// </returns> /// <exception cref="System.ArgumentException"> /// if encodedPublicKey is invalid /// </exception> private static IPublicKey GeneratePublicKey(string encodedPublicKey) { try { byte[] decodedKey = Convert.FromBase64String(encodedPublicKey); KeyFactory keyFactory = KeyFactory.GetInstance(KeyFactoryAlgorithm); return(keyFactory.GeneratePublic(new X509EncodedKeySpec(decodedKey))); } catch (NoSuchAlgorithmException ex) { // This won't happen in an Android-compatible environment. throw new Exception(ex.Message); } catch (FormatException) { Debug.WriteLine("Could not decode public key from Base64."); throw; } catch (InvalidKeySpecException exx) { Debug.WriteLine("Invalid public key specification."); throw new ArgumentException(exx.Message); } }
public Func <Task> WaitDelayAndCheckForRegionExited(CancellationToken regionExitedCancellationToken) { return(async() => { try { // if > 30 seconds since last beacon, send beacon exited await Task.Delay(BeaconExitedTimeoutMs, _cancellationToken); } catch (TaskCanceledException) { SystemDebug.WriteLine("Region exit delay task cancelled", LogTag); return; } lock (_lock) { if (!regionExitedCancellationToken.IsCancellationRequested) { _wasRegionExitTriggered = true; SystemDebug.WriteLine("Region exited", LogTag); BeaconRegionExited?.Invoke(this, new BeaconPacketArgs(new BeaconPacket(_beaconRegion))); } } }); }
/// <summary> /// Retrieves the list of specified class types from the specified assembly. /// </summary> /// <param name="className">string class name</param> /// <param name="assembly">Assembly to search for a class from</param> /// <returns>ArrayList: List of types. Most likely just one item</returns> public static Type[] GetClassTypeByNameFromAssembly(string className, Assembly assembly) { List <Type> typeList = new List <Type>(); Type[] types = null; try { types = GetTypesFromAssembly(assembly); } catch (Exception e) { Trace.WriteLine("Exception getting types for assembly '" + assembly.FullName + "': " + e.Message); } if (types != null) { foreach (Type ctype in types) { if ((ctype != null) && ctype.IsClass && !ctype.IsAbstract) { if (ctype.Name == className) { typeList.Add(ctype); } } } } return(typeList.ToArray()); }
/// <summary> /// Use underline socket to send protocol message async. /// </summary> /// <param name="vMessage">The protocol message to be sended.</param> public void SendMessage(System.Object vMsg) { Log.Info("一个消息需要发送"); if (State != ConnectionState.Established) { Log.Info("一个消息需要发送 1"); Debug.WriteLine(String.Format("SendMessage Error:in State {0}", State)); return; } if (vMsg == null) { Log.Info("一个消息需要发送 2"); Debug.WriteLine(String.Format("SendMessage Error:vMsg is null")); return; } ArraySegment <Byte> sndBuf = ProtoHelper.EncodeMessage(vMsg, vMsg is IResponse); SocketAsyncEventArgs sendEventArgs = new SocketAsyncEventArgs(); sendEventArgs.Completed += new EventHandler <SocketAsyncEventArgs>(OnCompletedForSend); sendEventArgs.SetBuffer(sndBuf.Array, sndBuf.Offset, sndBuf.Count); Debug.WriteLine(string.Format("SendMessage Send {0}", vMsg.GetType().Name)); Log.Info(string.Format("SendMessage Send {0}", vMsg.GetType().Name)); if (!ConnSocket.SendAsync(sendEventArgs)) { OnCompletedForSendImpl(sendEventArgs); sendEventArgs.Dispose(); } }
public async Task <bool> SubmitOrder(Order order, Session sess) { Uri uri = new Uri(Constants.RestUrl + "orders/new"); bool result = false; try { var jsonData = new { order, sessId = sess.SessId }; StringContent data = new StringContent(JsonConvert.SerializeObject(jsonData), Encoding.UTF8, "application/json"); HttpResponseMessage response = await client.PostAsync(uri, data); // Could check body here but not necessary with current implementation. if (response.IsSuccessStatusCode) { result = true; } } catch (Exception ex) { Debug.WriteLine(@"\tERROR {0}", ex.Message); throw ex; } return(result); }
public void UnhandledException(Exception ex, string message, [CallerFilePath] string filePath = "", [CallerMemberName] string memberName = "", [CallerLineNumber] int lineNumber = 0) { Console.WriteLine("=== FATAL EXCEPTION ==="); Log(message, filePath, memberName, lineNumber); Console.WriteLine(ex.ToString()); Console.WriteLine("=== =============== ==="); }
public override Result DoWork() { try { SetForegroundAsync(CreateForegroundInfo()); Task.Run(DoAsyncWork).GetAwaiter().GetResult(); return(Result.InvokeSuccess()); } catch (Exception ex) { Debug.WriteLine(ex); if (_runAttemptCount < 3) { LogUtils.LogException(LogSeverity.WARNING, ex, $"{nameof(BackgroundFetchScheduler)}.{nameof(BackgroundFetchWorker)}.{nameof(DoWork)}: Failed to perform key background fetch. Retrying now."); ++_runAttemptCount; return(Result.InvokeRetry()); } LogUtils.LogException(LogSeverity.WARNING, ex, $"{nameof(BackgroundFetchScheduler)}.{nameof(BackgroundFetchWorker)}.{nameof(DoWork)}: Failed to perform key background fetch. Pull aborted. BG Task is rescheduled"); _runAttemptCount = 0; return(Result.InvokeFailure()); } }
public void Sort(IList <T> collection, IComparer <T> comparer = null) { Diagnostics.WriteLine( $"{nameof(SorterBase<T>)}, collection: " + GetString(collection)); Implementation(collection, comparer); Diagnostics.WriteLine("Result: " + GetString(collection)); }
protected override void writeError(string message) { if (!shouldWrite(LogLevel.Error)) { return; } lock (gate) { DiagDbg.WriteLine("ERROR: " + message); } }
protected override void writeInfo(string message) { if (!shouldWrite(LogLevel.Info)) { return; } lock (gate) { DiagDbg.WriteLine("Info: " + message); } }
protected override void writeWarn(string message) { if (!shouldWrite(LogLevel.Warn)) { return; } lock (gate) { DiagDbg.WriteLine("Warn: " + message); } }
protected override void writeDebug(string message) { if (!shouldWrite(LogLevel.Debug)) { return; } lock (gate) { DiagDbg.WriteLine("Debug: " + message); } }
public AndroidBeaconProvider(Context context, BeaconRegion beaconRegion) { SystemDebug.WriteLine(LogTag, LogTag); var manager = (BluetoothManager)context.GetSystemService("bluetooth"); _beaconRegion = beaconRegion; _adapter = manager.Adapter; }
protected void DisposeSwapChain() { try { DisposeHelper.Dispose(ref _swapChain); Debug.WriteLine("SWAPCHAIN DISPOSED"); } catch (ObjectDisposedException) { Debug.WriteLine("SWAPCHAIN ALREADY DISPOSED?"); } }
public void MakeLightWaveScene() { Reset(); LWScene scene = LWSceneParser.Load("res/Scenes/boxi3.lws"); Debug.WriteLine(scene.Objects.Count + " objects"); Debug.WriteLine(scene.Lights.Count + " lights"); Debug.WriteLine(scene.Cameras.Count + " cameras"); Material wood = materialManager["wood"]; var loadedModels = new Dictionary <string, RenderStack.LightWave.LWModel>(); foreach (var @object in scene.Objects) { try { string name = "res/Objects/" + @object.Name.Split('/').Last(); LWModel lwModel = null; if (loadedModels.ContainsKey(name)) { lwModel = loadedModels[name]; } else { loadedModels[name] = lwModel = RenderStack.LightWave.LWModelParser.Load(name); } foreach (var layer in lwModel.Layers.Values) { var mesh = new GeometryMesh(layer.Geometry, NormalStyle.CornerNormals); var model = new Model(layer.Name, mesh, wood, Motion(@object, 0.0f)); AddModel(model); } Debug.WriteLine("\tObject '" + @object.Name + "' " + @object.Bones.Count + " bones @ "); } catch (System.Exception) { } } foreach (var item in scene.Cameras) { Debug.WriteLine("\tCamera '" + item.Name + "'"); } foreach (var item in scene.Lights) { Debug.WriteLine("\tLight '" + item.Name + "'"); } AddCameras(); camera.Frame.LocalToParent.Set( Motion(scene.Cameras.First(), 0.0f) ); AddCameraUserControls(); }
private Type FindIModuleType(Assembly assembly) { Type imodule; // see if we have an explicitly defined entry #if NETSTANDARD1_3 var attrib = assembly.GetCustomAttributes <IoCModuleEntryAttribute>().FirstOrDefault(); #else var attrib = (from a in assembly.GetCustomAttributes(true) where a is IoCModuleEntryAttribute select a as IoCModuleEntryAttribute).FirstOrDefault(); #endif if (attrib != null) { if (!(attrib.EntryType is IModule)) { throw new Exception( string.Format("IoCModuleEntry.EntryType in assembly '{0}' doesn't derive from IModule", assembly.FullName)); } imodule = attrib.EntryType; } else { // default to old behavior - loading will be *much* slower under Mono as we have to call GetTypes() // under CF and FFX this appears negligible try { #if NETSTANDARD1_3 imodule = assembly.ExportedTypes.First(t => t.Equals(typeof(IModule))); #else imodule = (from t in assembly.GetTypes() where t.GetInterfaces().Count(i => i.Equals(typeof(IModule))) > 0 select t).FirstOrDefault(m => !m.IsAbstract); #endif } #if !WindowsCE catch (ReflectionTypeLoadException ex) { Debug.WriteLine(string.Format("IoC: Exception loading assembly '{0}': {1}", assembly.FullName, ex.Message), Constants.TraceCategoryName); throw; } #else catch (Exception ex) { Trace.WriteLine(string.Format("IoC: Exception loading assembly '{0}': {1}", assembly.FullName, ex.Message), Constants.TraceCategoryName); throw; } #endif } return(imodule); }
/// <inheritdoc cref="IAmLogger.Debug" /> public void Debug ( string text ) { if (!string.IsNullOrEmpty(text)) { SysDebug.WriteLine(text, "Debug"); } }
public void readCommand(IByteBuffer bytes) { Debug.WriteLine("Reading command"); var parser = new ByteParser(bytes); playerId = parser.readInt(); Debug.WriteLine("PlayerID: " + playerId); sessionId = parser.readUTF(); Debug.WriteLine("SessionID: " + sessionId); }
/// <inheritdoc cref="IAmLogger.Warn" /> public void Warn ( string text ) { if (!string.IsNullOrEmpty(text)) { SysDebug.WriteLine(text, "Warn"); } }
/// <inheritdoc cref="IAmLogger.Fatal" /> public void Fatal ( string text ) { if (!string.IsNullOrEmpty(text)) { SysDebug.WriteLine(text, "Fatal"); } }
/// <inheritdoc cref="IAmLogger.Info" /> public void Info ( string text ) { if (!string.IsNullOrEmpty(text)) { SysDebug.WriteLine(text, "Info"); } }
/// <inheritdoc cref="IAmLogger.Trace" /> public void Trace ( string text ) { if (!string.IsNullOrEmpty(text)) { SysDebug.WriteLine(text, "Trace"); } }
/// <inheritdoc cref="IAmLogger.Error" /> public void Error ( string text ) { if (!string.IsNullOrEmpty(text)) { SysDebug.WriteLine(text, "Error"); } }
private IEnumerator PostFormEncodedStringNoAuth <T>(string urlPath, string data, Action <T> OnCompleted, Action <Exception> OnError) { using (UnityWebRequest req = new UnityWebRequest(new Uri(Config.RootApiUri, urlPath))) { req.uploadHandler = new UploadHandlerRaw(Encoding.UTF8.GetBytes(data)) { contentType = "application/x-www-form-urlencoded" }; req.method = "POST"; req.downloadHandler = new DownloadHandlerBuffer(); yield return(req.SendWebRequest()); if (req.isNetworkError) { OnError(new SqApiNetworkException($"Unity Network Error: {req.error}")); yield break; } else if (req.isHttpError) { if (req.responseCode == 401 || req.responseCode == 403) { OnError(new SqApiAuthException((int)req.responseCode, $"Unity Http Error: {req.error}")); yield break; } else { OnError(new SqApiAuthException((int)req.responseCode, $"Unity Http Error: {req.error}")); yield break; } } var resStr = req.downloadHandler.text; if (string.IsNullOrWhiteSpace(resStr)) { OnCompleted?.Invoke(default(T)); yield break; } else { try { OnCompleted?.Invoke(JsonConvert.DeserializeObject <T>(resStr)); yield break; } catch (Exception ex) { Debug.WriteLine("Failed deserializing response from API", ex); OnError?.Invoke(ex); yield break; } } } }
/// <summary> /// The on service disconnected. /// </summary> /// <param name="name"> /// The name. /// </param> public void OnServiceDisconnected(ComponentName name) { lock (this.locker) { // Called when the connection with the service has been // unexpectedly disconnected. That is, Market crashed. // If there are any checks in progress, the timeouts will handle them. Debug.WriteLine("Service unexpectedly disconnected."); this.licensingService = null; } }
public override void Start(IModuleInfoStore store) { #if DESKTOP if (IsSingletonApp) { if (HandleSingleton()) { return; } } #endif // add a generic "control" to the Items list. var invoker = new Control(); // force handle creation var handle = invoker.Handle; RootWorkItem.Items.Add(invoker, Constants.EventInvokerName); ModuleInfoStoreService storeService = RootWorkItem.Services.AddNew <ModuleInfoStoreService>(); AddServices(); if (store != null) { storeService.ModuleLoaded += new EventHandler <GenericEventArgs <IModuleInfo> >(OnModuleLoaded); storeService.LoadModulesFromStore(store); } BeforeShellCreated(); // create the shell form after all modules are loaded // see if there's a registered shell replacement. ShellReplacement replacement = null; if (EnableShellReplacement) { replacement = RootWorkItem.Services.Get <ShellReplacement>(); } if ((replacement == null) || (!replacement.ShellReplacementEnabled)) { ShellForm = RootWorkItem.Items.AddNew <TShell>(); } else { ShellForm = replacement as Form; Trace.WriteLine("Replacement shell found.", Constants.TraceCategoryName); } AfterShellCreated(); OnApplicationRun(ShellForm); OnApplicationClose(); }
///// <summary> ///// shutdown the socket ///// </summary> //public void Shutdown() //{ // try // { // lock (_lockSocket) // { // ////Console.WriteLine("Shutdown::lock (_lockPeer)"); // ConnSocket.Shutdown(SocketShutdown.Both); // } // } // catch (Exception) // { // //String msg = String.Format("{0}:{1}", ex.GetType().ToString(), ex.Message); // //Debug.WriteLine(msg); // //Console.WriteLine(msg); // //throw ex; // } // //Console.WriteLine("Client SHUTDOWN!"); //} /// <summary> /// 断开soket /// </summary> private void SocketDisconnect() { try { if (ConnSocket != null) { lock (_lockSocket) { // 启动断开连接的timer if (m_disconnectTimer == null) { m_disconnectTimer = new Timer((c) => { if (ConnSocket.Connected) { return; } if (State != ConnectionState.Disconnecting) { return; } // 记录日志 Debug.WriteLine(string.Format("SocketDisconnect Disconnected timer start...")); FireEventOnLogPrint("Disconnect.Timer" + "state=" + State); // 设置状态 State = ConnectionState.Closed; // 发送连接断开的消息 var vMsg = new CCMSGConnectionBreak(); RecvQueue.Enqueue(new KeyValuePair <int, object>(vMsg.MessageId, vMsg)); // 清理timer if (m_disconnectTimer != null) { m_disconnectTimer.Dispose(); m_disconnectTimer = null; } }, null, 500, 1000); // 500毫秒后启动, 1000毫秒检查一次 } ConnSocket.Shutdown(SocketShutdown.Both); //ConnSocket.Disconnect(false); } } } catch (Exception ex) { String msg = String.Format("{0}:{1}", ex.GetType().ToString(), ex.Message); Debug.WriteLine(msg); //throw ex; } }