/// <summary> /// メッセージをファイルに書き込む /// </summary> /// <param name="message">書き込むメッセージ</param> public void Write(string message) { listener.WriteLine(String.Format("ver{0} ({1})", TwinDll.Version, DateTime.Now)); listener.WriteLine(String.Format("{0} CLR {1}", Environment.OSVersion, Environment.Version)); listener.WriteLine(message); listener.WriteLine(String.Empty); }
public static void Test(TraceListener log) { KDNode root = KDNode.Process(new Tuple <Vector2d, int>[] { new Tuple <Vector2d, int>(new Vector2d(+0, +0), 0), new Tuple <Vector2d, int>(new Vector2d(+1, +1), 1), new Tuple <Vector2d, int>(new Vector2d(-1, +1), 2), new Tuple <Vector2d, int>(new Vector2d(+1, -1), 3), new Tuple <Vector2d, int>(new Vector2d(-1, -1), 4), new Tuple <Vector2d, int>(new Vector2d(-2, -0), 5), }); log?.WriteLine(root); double x = -2.0; double y = 0.1; Vector2d buff = new Vector2d(); for (y = 2.0; y > -2; y -= 0.25) { for (x = -3.0; x < 3; x += 0.25) { buff.X = x; buff.Y = y; var ret = root.GetNearest(ref buff); log?.Write(ret); } log?.WriteLine(""); } }
public IEnumerable <T> GetListings() { var listings = new List <T>(); int numResults; int pageNum = 1; _trace.WriteLine($"Attempting to fetch {typeof(T).Name} listings from {Client.BaseAddress}"); _trace.WriteLine($"Page size is {PageSize}"); do { string requestUri = GetRequestUri(pageNum); HttpResponseMessage response = Client.GetAsync(requestUri).Result; string json = response.Content.ReadAsStringAsync().Result; var listingResponse = JsonConvert.DeserializeObject <ListingContainer <T> >(json, Settings); numResults = listingResponse.TotalCount; listings.AddRange(listingResponse.List); pageNum++; } while (PageSize * (pageNum - 1) < numResults); _trace.WriteLine($"Total count of listings: {numResults}"); _trace.WriteLine($"Successfuly parsed {listings.Count} rental listings."); return(listings); }
public void OutputSearchResult(SearchResultCollection result, TraceListener listener) { int n = 0; foreach (SearchResult sr in result) { listener.WriteLine(string.Format("第{0}行结果开始", n)); listener.IndentLevel++; foreach (string propName in sr.Properties.PropertyNames) { string strValue = string.Empty; for (int i = 0; i < sr.Properties[propName].Count; i++) { if (strValue != string.Empty) { strValue += ", "; } strValue += sr.Properties[propName][i].ToString(); } listener.WriteLine(string.Format("Property Name: {0}\tProperty Value: {1}", propName, strValue)); } listener.IndentLevel--; listener.WriteLine(string.Format("第{0}行结果结束", n)); n++; } }
private static void RetrieveDiagnostics(DiagnosticView diagview, TraceListener traceListener) { // Display diagnostics for diagnostic view object traceListener.WriteLine("Diagnostic View for '" + diagview.ObjectName + "':"); foreach (KeyValuePair <string, object> diagprop in diagview) { traceListener.WriteLine(" " + diagprop.Key + ": " + diagprop.Value); } }
public Task Debug(string message) { Task task = Task.Run(() => { listener.WriteLine("Debug :: " + message); listener.Flush(); }); return(task); }
public void IsSourceLinked(Type exceptionThrower) { var exception = Assert.Throws <Exception>(() => Activator.CreateInstance(exceptionThrower).ToString()); var stackTrace = exception.SourceMappedTrace(); _output.WriteLine("--------------------- Original stack trace: ---------------"); _output.WriteLine(exception.ToString()); Assert.Contains("//example.org/", stackTrace); Assert.Contains("/test1234/", stackTrace); }
private void WriteToLog(string level, string format, params object[] values) { if (_traceSource.Switch.Level == SourceLevels.Off) { return; } for (var i = 0; i < values.Length; i++) { if (values[i] == null) { continue; } if (values[i].GetType() == typeof(EzTextingModel)) { values[i] = _serializer.Serialize(values[i]); } else if (values[i] is ICollection) { values[i] = (((ICollection)values[i]).Cast <object>().ToList().ToPrettyString()); } } // ReSharper disable once UseStringInterpolation _eztextingLogFile.WriteLine(string.Format("{0} - {1} [{2}] {3}", DateTime.Now.ToString(ClientConstants.LogDatetimePattern), _traceSource.Name, level, string.Format(format, values))); }
async Task IPostToBot.PostAsync(IActivity activity, CancellationToken token) { try { await this.inner.PostAsync(activity, token); } catch (SqlException) { await this.botToUser.PostAsync("Ocurrió un problema de conexión a la base de datos. Por favor intente más tarde"); } catch (Exception ex) { try { if (ex.Source == "Google.Api.Gax") { await this.botToUser.PostAsync("Ocurrió un problema de comunicación con el servidor. Por favor intente más tarde"); } else { //await this.botToUser.PostAsync(this.resources.GetString("UnhandledExceptionToUser")); await this.botToUser.PostAsync("Hay un error"); } } catch (Exception inner) { trace.WriteLine(inner); BaseData.LogError(inner); await this.botToUser.PostAsync("Hay un error"); } Console.WriteLine(ex.Message); BaseData.LogError(ex); } }
protected virtual void WriteTraceMessage(TraceLevel traceLevel, string message, Exception exception = null) { try { if (TraceListener == null) { return; } if (TraceLevel < TraceLevel.Off || TraceLevel > TraceLevel.Verbose) { return; } if (TraceLevel >= traceLevel) { var messageToWrite = new StringBuilder(message); if (exception != null) { messageToWrite.Append(DumpException(exception)); } TraceListener.WriteLine($"{FormatTraceMessageHeader()}{messageToWrite}"); TraceListener.Flush(); } } catch { // Intentionally ignored } }
/// <summary> /// Creates a SQLiteCommand given the command text (SQL) with arguments. Place a '?' /// in the command text for each of the arguments and then executes that command. /// Use this method instead of Query when you don't expect rows back. Such cases include /// INSERTs, UPDATEs, and DELETEs. /// You can set the Trace or TimeExecution properties of the connection /// to profile execution. /// </summary> /// <param name="query"> /// The fully escaped SQL. /// </param> /// <param name="args"> /// Arguments to substitute for the occurences of '?' in the query. /// </param> /// <returns> /// The number of rows modified in the database as a result of this execution. /// </returns> public int Execute(string query, params object[] args) { var cmd = CreateCommand(query, args); if (TimeExecution) { if (_sw == null) { _sw = Platform.StopwatchFactory.Create(); } _sw.Reset(); _sw.Start(); } var r = cmd.ExecuteNonQuery(); if (TimeExecution) { _sw.Stop(); _elapsedMilliseconds += _sw.ElapsedMilliseconds; TraceListener.WriteLine("Finished in {0} ms ({1:0.0} s total)", _sw.ElapsedMilliseconds, _elapsedMilliseconds / 1000.0); } return(r); }
public void OutputEntryProperties(DirectoryEntry entry, TraceListener listener) { foreach (string strName in entry.Properties.PropertyNames) { listener.WriteLine(string.Format("Name: {0},\tValue: {1}", strName, entry.Properties[strName].Value.ToString())); } }
async Task IPostToBot.PostAsync(IActivity activity, CancellationToken token) { try { await inner.PostAsync(activity, token); } catch (Exception ex) { trace.WriteLine(ex.Message); var messageActivity = activity.AsMessageActivity(); if (messageActivity != null) { await botToUser.PostAsync(messageProvider.GetMessage("ExceptionMessage"), cancellationToken : token); await botToUser.PostAsync(messageProvider.GetMessage("WhatMoreCanIDo"), cancellationToken : token); using (var scope = DialogModule.BeginLifetimeScope(Conversation.Container, messageActivity)) { var botData = scope.Resolve <IBotData>(); await botData.LoadAsync(default(CancellationToken)); var stack = scope.Resolve <IDialogStack>(); stack.Reset(); botData.ConversationData.Clear(); await botData.FlushAsync(default(CancellationToken)); } } } }
async Task IPostToBot.PostAsync(IActivity activity, CancellationToken token) { try { await _inner.PostAsync(activity, token); } catch (Exception error) { try { if (Debugger.IsAttached) { var message = _botToUser.MakeMessage(); message.Text = $"Exception: { error.Message}"; message.Attachments = new[] { new Attachment(MediaTypeNames.Text.Plain, content: error.StackTrace) }; await _botToUser.PostAsync(message, token); } else { await _botToUser.PostAsync("Ops! I'm still handle the previous message...", cancellationToken : token); } } catch (Exception e) { _trace.WriteLine(e); } throw; } }
private async Task <Tuple <string, FriendlyMesh> > GetComputedChunk(StandardChunkMetadata template, TraceListener log) { string filename = GetShortFilename(template); Tuple <string, FriendlyMesh> ret = new Tuple <string, FriendlyMesh>(GetFullFileName(template, filename), null); try { using (BlobHelper.DeletableFileStream ms = await BlobHelper.TryGetStreamAsync(cachedFileContainer, ret.Item1, log)) { if (ms != null) { ret = new Tuple <string, FriendlyMesh>(ret.Item1, ReadChunk(ms, template)); } } } catch (StorageException stex) { if (stex.RequestInformation.HttpStatusCode == 404) { log?.WriteLine("Blob not found;"); } else { throw; } } return(ret); }
public async Task <byte[]> GetData(StandardChunkMetadata template, TraceListener log) { var computedChunk = await GetComputedChunk(template, log); string fileName = computedChunk.Item1; byte[] imageData = computedChunk.Item2; if (computedChunk.Item2 != null) { log?.WriteLine("Cached " + description + " chunk (" + template.ToString() + ") file exists: " + fileName); return(computedChunk.Item2); } log?.WriteLine("Cached " + description + " chunk (" + template.ToString() + ") file does not exist: " + fileName + ", so starting generation..."); MemoryStream ms = null; try { var pixels = await Images.Current.GetData(template, log); if (pixels != null) { ms = Utils.GetBitmap(pixels, a => a, OutputType.JPEG); } } catch { } if (ms == null) { throw new MountainViewException("Source image not found for chunk " + template.ToString()); } imageData = new byte[ms.Length]; ms.Seek(0, SeekOrigin.Begin); ms.Read(imageData, 0, imageData.Length); await WriteChunk(imageData, fileName, log); log?.WriteLine("Finished generation of " + description + " cached chunk (" + template.ToString() + ") file: " + fileName); return(imageData); }
public static async Task <DeletableFileStream> TryGetStreamAsync(string containerName, string fileName, TraceListener log) { var localFileName = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".tmp"); var cacheFileName = Path.Combine(Path.GetTempPath(), fileName); foreach (DriveInfo d in DriveInfo.GetDrives().Where(p => p.Name.ToLower()[0] == localFileName.ToLower()[0] && p.IsReady)) { log?.WriteLine(string.Format("{0} has {1, 15} bytes available", d.Name, d.AvailableFreeSpace)); } if (!File.Exists(cacheFileName)) { try { CloudBlockBlob blockBlob = (await GetContainerAsync(containerName, log)).GetBlockBlobReference(fileName); await blockBlob.DownloadToFileAsync(localFileName, FileMode.CreateNew); } catch (Exception ex) { log?.WriteLine("Missing blob: " + fileName); log?.WriteLine("Error was:" + ex.ToString()); return(null); } var fi = new FileInfo(localFileName); if (!File.Exists(cacheFileName)) { fi.CopyTo(cacheFileName); } } else { var fi = new FileInfo(cacheFileName); fi.CopyTo(localFileName); } var fs = File.OpenRead(localFileName); fs.Position = 0; var ret = new DeletableFileStream(localFileName, fs); return(ret); }
public void Log(string message) { lock (System.Diagnostics.Trace.Listeners[this.eventStreamName]) { TraceListener item = System.Diagnostics.Trace.Listeners[this.eventStreamName]; object[] now = new object[] { DateTime.Now, this.eventStreamName, AsyncHelper.Trace.ActivityId, message }; item.WriteLine(string.Format("{0} [{1}] [ActivityId={2}] {3}", now)); System.Diagnostics.Trace.Listeners[this.eventStreamName].Flush(); } }
//--------------------------------------------------------------------- protected override void WriteToLog(string loggerName, LoggerLevel level, string message) { var logMessage = CreateLogMessage(loggerName, level, message); if (!string.IsNullOrWhiteSpace(logMessage)) { _listener.WriteLine(logMessage); _listener.Flush(); } }
public async Task <FriendlyMesh> GetData(StandardChunkMetadata template, TraceListener log) { var computedChunk = await GetComputedChunk(template, log); string fileName = computedChunk.Item1; FriendlyMesh ret = computedChunk.Item2; if (computedChunk.Item2 != null) { log?.WriteLine("Cached " + description + " chunk (" + template.ToString() + ") file exists: " + fileName); return(computedChunk.Item2); } log?.WriteLine("Cached " + description + " chunk (" + template.ToString() + ") file does not exist: " + fileName + ", so starting generation..."); ChunkHolder <float> pixels2 = null; try { pixels2 = await Heights.Current.GetData(template, log); } catch { } if (pixels2 == null) { // throw new InvalidOperationException("Source heights not found for chunk " + template.ToString()); return(null); } ret = new FriendlyMesh( template.LatSteps, template.LonSteps, template.LatLo, template.LonLo, template.LatHi, template.LonHi, pixels2.Data, log); await WriteChunk(ret, fileName, log); log?.WriteLine("Finished generation of " + description + " cached chunk (" + template.ToString() + ") file: " + fileName); return(ret); }
public async Task <ChunkHolder <T> > GetData(StandardChunkMetadata template, TraceListener log) { var computedChunk = await GetComputedChunk(template, log); string fileName = computedChunk.Item1; ChunkHolder <T> ret = computedChunk.Item2; if (computedChunk.Item2 != null) { log?.WriteLine("Cached " + description + " chunk file exists: " + fileName); return(computedChunk.Item2); } log?.WriteLine("Cached " + description + " chunk file does not exist: " + fileName); if (template.ZoomLevel <= this.SourceDataZoom) { throw new MountainViewException("Source data is missing for chunk " + template.ToString()); //log?.WriteLine("Starting generation..."); //ret = await GenerateData(template, log); //await WriteChunk(ret, fileName, log); //log?.WriteLine("Finished generation of " + description + " cached chunk file: " + fileName); //return ret; } log?.WriteLine("Need to interpolate from lower zoom data"); var parent = template.GetParentChunk(); var chunks = new ChunkHolder <T>[] { await GetData(parent, log) }; ret = new ChunkHolder <T>( template.LatSteps, template.LonSteps, template.LatLo, template.LonLo, template.LatHi, template.LonHi, null, toDouble, fromDouble); ret.RenderChunksInto(chunks, aggregate, log); await WriteChunk(ret, fileName, log); log?.WriteLine("Finished generation of " + description + " cached chunk file: " + fileName); return(ret); }
public async override void WriteLine(string Message) { if (CurrentLine.Length > 0) { Message = CurrentLine.Append(Message).ToString(); CurrentLine.Clear(); } if (!await Discord.LogMessage(Message)) { BackupTraceListener.WriteLine(Message); } }
public async Task <ChunkHolder <T> > ProcessRawData(StandardChunkMetadata template, TraceListener log) { var computedChunk = await GetComputedChunk(template, log); string fileName = computedChunk.Item1; ChunkHolder <T> ret = computedChunk.Item2; if (computedChunk.Item2 != null) { log?.WriteLine("Cached " + description + " chunk file exists: " + fileName); return(computedChunk.Item2); } log?.WriteLine("Cached " + description + " chunk file does not exist: " + fileName); if (template.ZoomLevel > this.SourceDataZoom) { // Nothing to do for processing return(null); } else if (template.ZoomLevel == this.SourceDataZoom) { log?.WriteLine("Starting generation..."); ret = await GenerateData(template, log); await WriteChunk(ret, fileName, log); log?.WriteLine("Finished generation of " + description + " cached chunk file: " + fileName); return(ret); } log?.WriteLine("Need to aggregate up from higher zoom data"); var children = template.GetChildChunks(); List <ChunkHolder <T> > chunks = new List <ChunkHolder <T> >(); foreach (var child in children) { log?.WriteLine(child); chunks.Add(await ProcessRawData(child, log)); } ret = new ChunkHolder <T>( template.LatSteps, template.LonSteps, template.LatLo, template.LonLo, template.LatHi, template.LonHi, null, toDouble, fromDouble); ret.RenderChunksInto(chunks, aggregate, log); await WriteChunk(ret, fileName, log); log?.WriteLine("Finished generation of " + description + " cached chunk file: " + fileName); return(ret); }
/// <summary> /// Copy the contents of the buffered output to another trace listener /// </summary> /// <param name="Other">The trace listener to receive the buffered output</param> public void CopyTo(TraceListener Other) { int StartIdx = 0; while (StartIdx < Buffer.Length) { int EndIdx = StartIdx; while (EndIdx < Buffer.Length && Buffer[EndIdx] != '\n') { EndIdx++; } Other.WriteLine(Buffer.ToString(StartIdx, EndIdx - StartIdx)); StartIdx = EndIdx + 1; } }
/// <summary> /// Adds a new item to the end of this array. /// </summary> /// <param name="item">The new item.</param> public void Add(T item) { if (Length >= Data.Length) { int length = (int)((Length + 1) * 2); if (verbose) { log?.WriteLine(DateTime.Now + "\tImplicitly resizing array '" + name + "' from " + Data.Length + " to " + length); } Array.Resize(ref Data, length); } Data[Length++] = item; }
public static void Write(string Message, TraceLevel Level) { try { lastError = string.Empty; if (traceSwitch != null && traceSwitch.Level >= Level) { TraceListenerCollection traceListenerCollection = System.Diagnostics.Trace.Listeners; if (traceListenerCollection != null) { int listernersNo = traceListenerCollection.Count; for (int i = 0; i < listernersNo; i++) { TraceListener listener = (TraceListener)traceListenerCollection[i]; if (listener != null) { StringBuilder sb = new StringBuilder(); DateTime date = DateTime.Now; sb.Append(date.ToString("yyyy/MM/dd hh:mm:ss.fff tt")).Append(": ").Append(Message); listener.WriteLine(sb.ToString()); listener.Flush(); } if (traceSwitch.Level >= TraceLevel.Verbose) { TraceListener listenerDef = traceListenerCollection["Default"]; if (listenerDef != null) { listenerDef.WriteLine(Message); listenerDef.Flush(); } } } } } } catch (System.Exception ex) { lastError = ex.Message; } }
public void Execute(string channelName, int fromPostId, int toPostId) { if (string.IsNullOrWhiteSpace(channelName)) { throw new ArgumentException(nameof(channelName)); } _traceListener.WriteLine($"Start getting '{channelName}' posts ({fromPostId} to {toPostId})...\n"); try { for (int postId = fromPostId; postId <= toPostId; postId++) { _traceListener.Write($"\nStart getting post #{postId} "); var telegramPost = _channelTools.GetPost(channelName, postId); if (telegramPost == null) { _traceListener.WriteLine($"\n\tCould not read post #{postId}."); } else { foreach (var postSaver in _postSavers) { SpinAnimation.Start(250); try { postSaver.Save(telegramPost); SpinAnimation.Stop(); _traceListener.Write($"\n\t{postSaver.GetType().Name} has saved post #{postId}."); } catch (Exception ex) { _traceListener.WriteLine($"\n\tError in storing {postId} from '{channelName}'."); _traceListener.WriteLine($"\t\tError:\n\t\t{ex}\n"); } } } } } catch (Exception ex) { _traceListener.WriteLine("\nError:"); _traceListener.WriteLine($"\t{ex.Message}"); } _traceListener.WriteLine($"\nFinished storing posts #{fromPostId} to #{toPostId} from channel '{channelName}'.\n"); }
public static async Task Uploader(string sourcePath, int lat, int lon, TraceListener log) { string folder = "NAIP_n" + lat + "w" + (-lon); foreach (var x in Directory.GetFiles(Path.Combine(sourcePath, folder)).Where(p => p.EndsWith(".csv") || p.EndsWith(".jp2"))) { log?.WriteLine(x); using (var ms = new MemoryStream()) { using (var fs = File.OpenRead(x)) { fs.CopyTo(ms); ms.Position = 0; await BlobHelper.WriteStream("sources", folder + "/" + x.Split(Path.DirectorySeparatorChar).Last(), ms, log); } } } }
public async Task PostAsync(IActivity activity, CancellationToken token) { try { await inner.PostAsync(activity, token); } catch (Exception ex) { try { await botToUser.PostAsync("Sorry that I'm unable to answer you in current context. Please try again later...", cancellationToken : token); } catch (Exception innerex) { trace.WriteLine(inner); } throw; } }
private static async Task <CloudBlobContainer> GetContainerAsync(string containerName, TraceListener log) { if (!singleton.TryGetValue(containerName, out CloudBlobContainer ret)) { if (string.IsNullOrEmpty(connectionString)) { log?.WriteLine("Must set the 'connectionString' property prior to use"); throw new MountainViewException("Must set the 'connectionString' property prior to use"); } CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connectionString); CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient(); ret = blobClient.GetContainerReference(containerName); await ret.CreateIfNotExistsAsync(); singleton.AddOrUpdate(containerName, ret, (a, b) => b); } return(ret); }