Issue I need to know if a Date is between a DateRange. I have three dates: // The date range DateTime startDate; DateTime endDate; DateTime dateToCheck; The easy solution is doing a comparison, but is there a smarter way to
Continue readingTag: c#
Date and time between a date range in dotnet
Issue I am facing the problem to know if DateTime is between a date range in the dotnet. For example if the x.SchedulerStart value is 2022-11-02 06:46:30 and x.SchedulerEnd value is 2022-11-02 23:26:30. I want check this DateTime.Today value is
Continue readingHow to get all weekends within a date range in C#
Issue Is there a simple way or framework to get all weekends within a date range in C#? Is it possible to do with LINQ as well? Solution I found how to do it. http://www.dotnetjalps.com/2011/06/finding-saturdaysunday-between-date.html namespace DatimeApplication { class Program
Continue readingCalculating Distance between two Latitude and Longitude GeoCoordinates
Issue I’m calculating the distance between two GeoCoordinates. I’m testing my app against 3-4 other apps. When I’m calculating distance, I tend to get an average of 3.3 miles for my calculation whereas other apps are getting 3.5 miles. It’s
Continue readingReverse geocoding using Nominatim API doesn't work
Issue I need to find out the name of the city given a pair of lat,lon coordinates I’m using Nominatim API https://wiki.openstreetmap.org/wiki/Nominatim This is an example query: https://nominatim.openstreetmap.org/reverse?format=xml&lat=40&lon=30&zoom=18&addressdetails=1 And it works from the Browser, however it fails from this C#
Continue readingHow to determine the current Windows timer resolution?
Issue It might be obvious, but I can’t find/google the correct method to get the current system value of the timer resolution, which a program can set by timeBeginPeriod(n)/timeEndPeriod(n). I want to find out what’s the current resolution… The Windows 7
Continue readingIf an Exception happens within a using statement does the object still get disposed?
Issue If an Exception happens within a using statement does the object still get disposed? The reason why I’m asking is because I’m trying to decide on whether to put a try caught around the whole code block or within
Continue readingWhat is the best workaround for the WCF client `using` block issue?
Issue I like instantiating my WCF service clients within a using block as it’s pretty much the standard way to use resources that implement IDisposable: using (var client = new SomeWCFServiceClient()) { //Do something with the client } But, as
Continue readingHow to dispose HttpClient after it's finished?
Issue I want to use HttpClient to get content for my web page. public async Task<IActionResult> OnGet() { NetworkCredential credentials = new NetworkCredential(Settings.Username, Settings.Password); using (HttpClientHandler handler = new HttpClientHandler { Credentials = credentials }) using (HttpClient httpClient = new
Continue readingProblem with identical namespace and class name in C#
Issue namespace LedgerCommander.A { class B { static public int a = 7; } } namespace LedgerCommander { using LedgerCommander.A; public class MyClass { private int myProperty; public int MyProperty { get { return LedgerCommander.A.B.a; } } } } this
Continue readingC# Nested Type Aliases – Cannot Resolve Symbol
Issue Why doesn’t this compile in Unity 2018 C#? namespace MyNS { using FooTable = Dictionary<int, float[]>; using BarTable = Dictionary<int, FooTable>; } Likewise, if I omit the namespace: using FooTable = System.Collections.Generic.Dictionary<int, float[]>; using BarTable = System.Collections.Generic.Dictionary<int, FooTable>; I
Continue readingNew `using` syntax interaction with long lived references
Issue Here’s some example code; public sealed class HoldingClass : IDisposable { private BinaryReader _binaryReaderField; public string GetStringFromReader(int count) { var data = _binaryReaderField.ReadBytes(count); // … Process data … // return newString; } public void Dispose() { _binaryReaderField?.Close(); _binaryReaderField?.Dispose(); }
Continue readingCreate using blocks for multiple objects in collection
Issue Given the following code: using (payment.GetModifyLock()) { foreach (var paymentItem in paymentItems) { using (paymentItem.GetModifyLock()) { } } DoAction(); } I’m looking to modify this code so that DoAction is done inside all the using blocks (not just one).
Continue readingnameof won´t reflect using
Issue I have an alias within my source-code file like this: MyClass.cs using System; using SomeClass = NewClass; public class Program { public static void Main() { Console.WriteLine(nameof(SomeClass)); } } public class NewClass { } I need this because the
Continue readingUsing System.Runtime.Serialization but IgnoreDataMemberAttribute and DataMemberAttribute not found
Issue I am trying to get this small JSONParser to work. Basicaly you just copy the code into your project. The only thing i changed is the namespace but i get errors in the following part: T member = members[i];
Continue readingWhy remove unused using directives in C#?
Issue I’m wondering if there are any reasons (apart from tidying up source code) why developers use the “Remove Unused Usings” feature in Visual Studio 2008? Solution There are a few reasons you’d want to take them out. It’s pointless.
Continue readingWhy disposing NetworkStream disconnects client
Issue When the following bare bones code is sending or receiving data, the client becomes disconnected. It was my understanding that a using block disposes the object it creates, ie the NetworkStream object, but why does the TcpClient Socket disconnect?
Continue readingWhy using HttpClient in a using block IS WRONG in WebApi context?
Issue So, the question is why the usage of HttpClient in using block is WRONG, BUT in WebApi context? I’ve been reading this article Don’t Block on Async Code. In it we have the following example: public static async Task<JObject>
Continue readingWhy using HttpClient in a using block IS WRONG in WebApi context?
Issue So, the question is why the usage of HttpClient in using block is WRONG, BUT in WebApi context? I’ve been reading this article Don’t Block on Async Code. In it we have the following example: public static async Task<JObject>
Continue readingWhy using HttpClient in a using block IS WRONG in WebApi context?
Issue So, the question is why the usage of HttpClient in using block is WRONG, BUT in WebApi context? I’ve been reading this article Don’t Block on Async Code. In it we have the following example: public static async Task<JObject>
Continue readingWhy using HttpClient in a using block IS WRONG in WebApi context?
Issue So, the question is why the usage of HttpClient in using block is WRONG, BUT in WebApi context? I’ve been reading this article Don’t Block on Async Code. In it we have the following example: public static async Task<JObject>
Continue readingWhy using HttpClient in a using block IS WRONG in WebApi context?
Issue So, the question is why the usage of HttpClient in using block is WRONG, BUT in WebApi context? I’ve been reading this article Don’t Block on Async Code. In it we have the following example: public static async Task<JObject>
Continue readingWhy using HttpClient in a using block IS WRONG in WebApi context?
Issue So, the question is why the usage of HttpClient in using block is WRONG, BUT in WebApi context? I’ve been reading this article Don’t Block on Async Code. In it we have the following example: public static async Task<JObject>
Continue readingIs this the right usage of using?
Issue I am not sure how to use using statement correct. I try like this: [HttpDelete("{ClubId}", Name = "DeleteOpenings_Club")] public async Task<IActionResult> DeleteClub_IsOpening([FromRoute] string ClubId) { using (_db_ClubIsOpen) { var result = _db_ClubIsOpen.ClubIsOpen_TBL.Where(x => x.FK_Club == ClubId); foreach (var item
Continue readingIs this the right usage of using?
Issue I am not sure how to use using statement correct. I try like this: [HttpDelete("{ClubId}", Name = "DeleteOpenings_Club")] public async Task<IActionResult> DeleteClub_IsOpening([FromRoute] string ClubId) { using (_db_ClubIsOpen) { var result = _db_ClubIsOpen.ClubIsOpen_TBL.Where(x => x.FK_Club == ClubId); foreach (var item
Continue readingIs this the right usage of using?
Issue I am not sure how to use using statement correct. I try like this: [HttpDelete("{ClubId}", Name = "DeleteOpenings_Club")] public async Task<IActionResult> DeleteClub_IsOpening([FromRoute] string ClubId) { using (_db_ClubIsOpen) { var result = _db_ClubIsOpen.ClubIsOpen_TBL.Where(x => x.FK_Club == ClubId); foreach (var item
Continue readingIs this the right usage of using?
Issue I am not sure how to use using statement correct. I try like this: [HttpDelete("{ClubId}", Name = "DeleteOpenings_Club")] public async Task<IActionResult> DeleteClub_IsOpening([FromRoute] string ClubId) { using (_db_ClubIsOpen) { var result = _db_ClubIsOpen.ClubIsOpen_TBL.Where(x => x.FK_Club == ClubId); foreach (var item
Continue readingIs this the right usage of using?
Issue I am not sure how to use using statement correct. I try like this: [HttpDelete("{ClubId}", Name = "DeleteOpenings_Club")] public async Task<IActionResult> DeleteClub_IsOpening([FromRoute] string ClubId) { using (_db_ClubIsOpen) { var result = _db_ClubIsOpen.ClubIsOpen_TBL.Where(x => x.FK_Club == ClubId); foreach (var item
Continue readingIs this the right usage of using?
Issue I am not sure how to use using statement correct. I try like this: [HttpDelete("{ClubId}", Name = "DeleteOpenings_Club")] public async Task<IActionResult> DeleteClub_IsOpening([FromRoute] string ClubId) { using (_db_ClubIsOpen) { var result = _db_ClubIsOpen.ClubIsOpen_TBL.Where(x => x.FK_Club == ClubId); foreach (var item
Continue readingNested using statements in C#
Issue I am working on a project. I have to compare the contents of two files and see if they match each other precisely. Before a lot of error-checking and validation, my first draft is: DirectoryInfo di = new DirectoryInfo(Environment.CurrentDirectory
Continue readingUnable to apply the new syntax of `using` for StreamWriter
Issue On MSDN about using, there’s the new syntax presented. I like it and started to apply it. Instead of using (MemoryStream memory = new MemoryStream()) { using (CryptoStream crypto = new CryptoStream(memory, transform, CryptoStreamMode.Write)) { using (StreamWriter writer =
Continue readingHow to return a Stream from a method, knowing it should be disposed?
Issue I have a method that takes FileStream as input. This method is running inside a for loop. private void UploadFile(FileStream fileStream) { var stream = GetFileStream(); // do things with stream } I have another method which creates and
Continue readingIs Close() same as Using statement
Issue Is Close() same as Dispose() or using statement. Is it necessary to call using statement even if Close is called?. I know before disposing of an object, close should be called, so we close the resource and may it
Continue readingWhat are the uses of "using" in C#?
Issue User kokos answered the wonderful Hidden Features of C# question by mentioning the using keyword. Can you elaborate on that? What are the uses of using? Solution The reason for the using statement is to ensure that the object
Continue readingWhat is the C# Using block and why should I use it?
Issue What is the purpose of the Using block in C#? How is it different from a local variable? Solution If the type implements IDisposable, it automatically disposes that type. Given: public class SomeDisposableType : IDisposable { …implmentation details… }
Continue readingStreamReader with using statement difference?
Issue I am using StreamReader as shown below in my code: string json = await new StreamReader(context.Request.Body).ReadToEndAsync(); // … use json variable here in some other code And I stumbled upon using statement. Is there any difference between my first
Continue readingUsing a returned instance?
Issue I have a hierarchy of classes that perform API requests. In the base class, I build the request object, and in some subclasses, this method is overridden. Base class: protected virtual HttpRequestMessage BuildRequest(HttpMethod method, Uri uri, HttpContent content =
Continue readingXamlParseException: Could not load file or assembly 'ResourceLibrary, …' or one of its dependencies. The system cannot find the file specified
Issue System.Windows.Markup.XamlParseExceptionoccurred A first chance exception of type ‘System.Windows.Markup.XamlParseException’ occurred in PresentationFramework.dll Additional information: ‘Set property ‘System.Windows.ResourceDictionary.Source’ threw an exception.’ Line number ’21’ and line position ‘6’. “Could not load file or assembly ‘ResourceLibrary, Culture=neutral’ or one of its dependencies.
Continue readingTry/Finally block vs calling dispose?
Issue Is there any difference between these two code samples and if not, why does using exist? StreamWriter writer; try { writer = new StreamWriter(…) writer.blahblah(); } finally { writer.Dispose(); } vs: using (Streamwriter writer = new Streamwriter(…)) { writer.blahblah
Continue readingC# FirstOrDefault() not working even with using System.Linq
Issue Beginner to C# here: I want to only see the facilities where there is an employee with the same age as the current user. For some reason FirstOrDefault() has a red line under it saying: ‘Facility’ does not contain
Continue readingC# 8 understanding await using syntax
Issue I have next method: public async Task<IEnumerable<Quote>> GetQuotesAsync() { using var connection = new SqlConnection(_connectionString); var allQuotes = await connection.QueryAsync<Quote>(@”SELECT [Symbol], [Bid], [Ask], [Digits] FROM [QuoteEngine].[RealtimeData]”); return allQuotes; } Everything fine and clear, connection will be disposed at the
Continue readinghow to convert text readed from barcode to arabic text
Issue I have barcode image with type “pdf417”,it content a arabic text , When read it using barcode it through a text like this “ÃÍãÏ#” how can I convert this text to its original text (arabic) Solution If your method
Continue readingExplain using statement in C# code in middle of code… (not in header as loading libraries)
Issue Please, can anyone explain to me statement in c# “using”. I know that I use it at header of program to load basic libraries such as using System.Text;. But is not clear to me, What is the difference between:
Continue reading'ExecuteNonQuery requires an open and available Connection. The connection's current state is closed.' – C#
Issue The code: private void btnSave_Click(object sender, EventArgs e) { using (con = new SqlConnection(connectionString)) { SqlCommand cmd; switch (action) { case ‘a’: cmd = new SqlCommand("INSERT INTO tbl_User (userName, userPass) Values (@username, @userpass)", con); cmd.CommandType = CommandType.Text; cmd.Parameters.AddWithValue("@username", txtUN.Text.Trim());
Continue readingDo HttpClient and HttpClientHandler have to be disposed between requests?
Issue System.Net.Http.HttpClient and System.Net.Http.HttpClientHandler in .NET Framework 4.5 implement IDisposable (via System.Net.Http.HttpMessageInvoker). The using statement documentation says: As a rule, when you use an IDisposable object, you should declare and instantiate it in a using statement. This answer uses this
Continue readingWhat does "using System" mean in C#?
Issue What does using System; namespace HelloWorld { class Program { static void Main(string[] args) { Console.WriteLine("Hello World!"); } } } ["using System"] mean? Why can’t you start your code without these lines? Solution The using System line means that
Continue readingC# .Net Framework Disposing of Tasks
Issue I was wondering if there are any benefits to implementing the dispose feature for Tasks. Will this operate any different? Will this force the memory to clean up any faster? Task updateTask = UpdateRemoteAsync() await updateTask; VS using (Task
Continue readingHow to naming namespaces for product that have sub-products/modules?
Issue I read that carefully. And yes very helpful! https://learn.microsoft.com/en-us/dotnet/standard/design-guidelines/names-of-namespaces Assuming you have following products and namespaces Microsoft.Dynamics.Inventory is a DLL Microsoft.Dynamics.Bank is a DLL Each of above have (Views, Reports, Utils, etc) Microsoft.Dynamics.Inventory.DLL Should I go for that? Microsoft.Dynamics.Inventory.Sales.Reports
Continue readingWhen is an object disposed if it uses 'using' and it is being used in a few methods
Issue Look at this particular line of code: using var ws = new ClientWebSocket() in the class below. When is that object disposed taking into account that it uses using and it is being used in a few methods more
Continue readingIs there a using/Dispose syntax that will be more eager to dispose but just as safe as chaining?
Issue If I’m doing the following: using (var foo = bar.GetFoo()) using (var blat = new Blat(foo)) using (var bonk = Bonk.FromBlat(blat)) using (var bork = Bob.FromBip(bonk)) { var target = bork.ToArray(); // I GOT THE TARGET } It’s very
Continue readingDeclaring and initialising a variable in a using block
Issue After a bit of advice here, regarding best practice coding – I am still a beginner with regards to C#. I have been reading on how using blocks are essential for disposing objects and attempting to implement these. My
Continue readingNot able to get Costura.Fody to work, keeps asking for the DLL
Issue I have installed costura.fody into my project using nuget package. I have updated the FodyWeavers.xml file with: <Costura Unmanaged32Assemblies=’dllname’ Unmanaged64Assemblies=’dllname’ /> when I rebuild it and try to run the exe on seperate PC without the dll it doesnt
Continue readingNot able to get Costura.Fody to work, keeps asking for the DLL
Issue I have installed costura.fody into my project using nuget package. I have updated the FodyWeavers.xml file with: <Costura Unmanaged32Assemblies=’dllname’ Unmanaged64Assemblies=’dllname’ /> when I rebuild it and try to run the exe on seperate PC without the dll it doesnt
Continue readingNot able to get Costura.Fody to work, keeps asking for the DLL
Issue I have installed costura.fody into my project using nuget package. I have updated the FodyWeavers.xml file with: <Costura Unmanaged32Assemblies=’dllname’ Unmanaged64Assemblies=’dllname’ /> when I rebuild it and try to run the exe on seperate PC without the dll it doesnt
Continue readingNot able to get Costura.Fody to work, keeps asking for the DLL
Issue I have installed costura.fody into my project using nuget package. I have updated the FodyWeavers.xml file with: <Costura Unmanaged32Assemblies=’dllname’ Unmanaged64Assemblies=’dllname’ /> when I rebuild it and try to run the exe on seperate PC without the dll it doesnt
Continue readingIncluding other files in Unity without the "using" statement
Issue I have to integrate someone’s code from a Unity project. They created a file with the definition of a class that’s an array of points, and another file that uses the first file’s class. Problem: I don’t see any
Continue readingHow to connect "using" keyword with Deconstruct method
Issue im wondering if we can join using statement and deconstruct operation. To be more visual look at below sample: using System; public class Foo : IDisposable { public IDisposable Bar { get; set; } public IDisposable Baz { get;
Continue readingWhat does Using(…..){…} mean
Issue Possible Duplicates: Using the using statment in c# What is the C# Using block and why should I use it? Just wondering what this means? I’ve seen lots of tutorials online that have the syntax: using (SqlCeCommand cmd2 =
Continue readingWhat is the best way to return from a function that use using block?
Issue What is the best way between those two implementations of using statement: I wonder if the 2nd code prevent using from releasing the resource/ calling ondispose because of the return command? 1st code: public byte[] DeriveSharedKey() { byte[] returnValue
Continue readingEF Core transaction lifetime
Issue We are using our select statement inside transaction scope because of concurrency concerns. The question is, if I put my transaction in using statement, do I still have to call Commit() method explicitly to be sure that the transaction
Continue readingEF Core transaction lifetime
Issue We are using our select statement inside transaction scope because of concurrency concerns. The question is, if I put my transaction in using statement, do I still have to call Commit() method explicitly to be sure that the transaction
Continue readingEF Core transaction lifetime
Issue We are using our select statement inside transaction scope because of concurrency concerns. The question is, if I put my transaction in using statement, do I still have to call Commit() method explicitly to be sure that the transaction
Continue readingEF Core transaction lifetime
Issue We are using our select statement inside transaction scope because of concurrency concerns. The question is, if I put my transaction in using statement, do I still have to call Commit() method explicitly to be sure that the transaction
Continue readingCreate a temporary file from stream object in c#
Issue Given a stream object which contains an xlsx file, I want to save it as a temporary file and delete it when not using the file anymore. I thought of creating a class that implementing IDisposable and using it
Continue readingCreate a temporary file from stream object in c#
Issue Given a stream object which contains an xlsx file, I want to save it as a temporary file and delete it when not using the file anymore. I thought of creating a class that implementing IDisposable and using it
Continue readingReading, modifying and writing a CSV with CSVHelper (variable scope with 'using' )
Issue This is a general coding question of how I can share the same list of data between the stages of reading, modifying and writing. I’m a novice and new to C# too, so I’m struggling. I was expecting to
Continue readingDoes a C# using statement perform try/finally?
Issue Suppose that I have the following code: private void UpdateDB(QuoteDataSet dataSet, Strint tableName) { using(SQLiteConnection conn = new SQLiteConnection(_connectionString)) { conn.Open(); using (SQLiteTransaction transaction = conn.BeginTransaction()) { using (SQLiteCommand cmd = new SQLiteCommand(“SELECT * FROM ” + tableName, conn))
Continue readingOptional context parameter in using statement
Issue I have this method public static List<_Account> Get(_User user, string name = null, SearchType sName = SearchType.Equals) { using (Context context = new Context()) { IQueryable<_Account> query = context.Accounts; if (!string.IsNullOrEmpty(name) && sName == SearchType.Equals) query = query.Where(r =>
Continue readingC# – getting out of using with return doesnt work
Issue This method works: HttpResponseMessage responseMessage = await GetResponseMessage(pathWithParams: $"https://api.webasd.com/crm/v3565/objects/contacts?&limit=100&after={afterValue}&archived=false"); private Task<HttpResponseMessage> GetResponseMessage(string pathWithParams = null, HttpRequestMessage requestMessage = null) { var httpClient = new HttpClient(); var bearerToken = _configuration["BEARER_TOKEN"]; httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", bearerToken); if (pathWithParams != null) {
Continue readingDoes .dll ignore import errors, clr
Issue I got a question for you guys who are a little more knowledgeable about c# and the using keyword. Say I got the following classes: using Project.BuildB.B namespace Project.BuildA public class A { } and namespace Project.BuildB public class
Continue readingSet all properties to null is a valid way to dispose an object?
Issue Using statement requires the object type to directly implement IDisposable. Looking for the easiest to do so, came up with this snippet. public class Foo : IDisposable { public string? exampleProperty { get; set; } public virtual void Dispose()
Continue readingC# ValueTuple with disposable members
Issue Let’s say I have a method foo which returns a ValueTuple where one of it’s members is disposable, for example (IDisposable, int). What is the best way to make sure the returned disposable object is correctly disposed on the
Continue readingCombining foreach and using
Issue I’m iterating over a ManageObjectCollection.( which is part of WMI interface). However the important thing is, the following line of code. : foreach (ManagementObject result in results) { //code here } The point is that ManageObject also implements IDisposable,
Continue readingElmah: How to get JSON HTTP request body from error report
Issue I’m using Elmah to log exceptions. Elmah is great at logging request bodies if the request is a Form-based request (i.e. Content-Type: application/x-www-form-urlencoded), but with JSON based requests where the content type is application/json, the request body is nowhere
Continue readingStacktrace for angularjs ?
Issue Need some expert advice for client side error handling…. I have a angularjs web application using C# at the backend. I am using Nlog to log backend errors to the database. I want to find out which tool can
Continue readinglog4Net RollingFileAppender Does Not "Roll"
Issue I am using log4Net to capture transaction data from an application, to help with debugging issues/errors basically. Lately, it hasn’t been creating new files after the file size hits 10MB, it just stops recording data. I looked online and
Continue readingHow to get real error messages in Nancy on Mono?
Issue I can’t figure out how to get actual 500 errors to be written into the response body. All I get is the Nancy 500 error page with JavaScript button to show the error. Since this is all happening behind
Continue readingUsing log4net with asp.net web forms
Issue I am trying to incorporate log4net into my web application. I have already done so with the newer portion based on .net mvc, but am having trouble incorporating it into the web forms based portion of my app. I
Continue readingSeparating Logging Code from C# Objects
Issue Currently I have a custom built static logging class in C# that can be called with the following code: EventLogger.Log(EventLogger.EventType.Application, string.Format(“AddData request from {0}”, ipAddress)); When this is called it simply writes to a defined log file specified in
Continue readingWhere does Prism DebugLogger save the log file
Issue I am using the Prism DebugLogger in my catch block as follows: catch (Exception e) { new DebugLogger().Log(e.Message, Category.Exception, Priority.High); } I am not sure if this is the complete implementation and if it is, does the logger save
Continue readingSentry is not logging 404 errors for ASP.NET MVC site
Issue I’ve managed to hook up SharpRaven to log and capture errors successfully from both MVC and Web API controllers, but have been unable to log and capture 404 errors. I’m attempting to do this through Application_Error like so: public
Continue readingWhich log utility is good for .NET application in C# (ASP.NET, WinForms)?
Issue I am trying to evaluate some of the best log utilities available for .NET framework, such as Microsoft Enterprise Library, Log4Net, elmah. Can someone who has already gone through this exercise would come to my help in listing pros
Continue readingWhat are the best practices for error logging in ASP.NET?
Issue When I worked with Java, I used log4j and slf4j in my web projects. I used next scheme:base class for objects, where I can use inheritance, and static class for other situations. Now I have project on C#(MVC3). What
Continue readingError Logging in a ASP.NET WebApplication
Issue If an exception occurs, it should be logged to a text file. And that the user should be redirected to a page that explains the error to the user. Where do I start? Solution I’d recommend using log4net. It’s
Continue readingError logging in C#
Issue I am making my switch from coding in C++ to C#. I need to replace my C++ error logging/reporting macro system with something similar in C#. In my C++ source I can write LOGERR(“Some error”); or LOGERR(“Error with inputs
Continue readingThe Enterprise Library Logging Application Block – System.InvalidOperationException: The LogWriter is already set
Issue I’m trying to use the the Logging Exception Handler from The Enterprise Library, but once in a while when I refresh the page (obviously), I get this error: Description: An unhandled exception occurred during the execution of the current
Continue readingHow should you diagnose the error SEHException – External component has thrown an exception
Issue Whenever a user reports an error such as System.Runtime.InteropServices.SEHException – External component has thrown an exception? is there anything that I as a programmer can do to determine the cause? Scenario : One user (using a program my company
Continue readingHow to use ELMAH to manually log errors
Issue Is it possible to do the following using ELMAH? logger.Log(” something”); I’m doing something like this: try { // Code that might throw an exception } catch(Exception ex) { // I need to log error here… } This exception
Continue readingLog4Net: Writing a C# object (apart from Exception) to the log?
Issue I have seen in Log4Net you can write a message and pass as the second parameter the Exception Object. Is it possible to send another type of object to log4net so I can see the values in my log
Continue readingPulling specific information from C# WinForms error messages
Issue I have a logging system set up in my C# WinForms project that writes to a log txt file. A typical error message looks like this: Error : 8:34:48 AM Tuesday, April 21, 2020 : :System.ArgumentOutOfRangeException: Index was out
Continue readingAzure functions V3 logging exceptions in startup file
Issue Currently we are preapring a set of azure functions to trigger a blob storage. The function app V3 should do some kind of checks on startup. So I added the Startup.cs file in the VS solution. The problem what
Continue readingNLog seems to be writing incorrect value in database
Issue I’m using NLog for logging into database. It seems to me its misplacing value in columns. For instance, it writes StackTrace in Message column and Exception information in StackTrace column Configuration: <nlog xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" throwConfigExceptions="true" throwExceptions="true"> <targets> <target name="database" type="Database"
Continue readingHow to log the request url when an error occurs in asp net core?
Issue Why does this code only gets executed when no error has occurred? app.Use(async (context, next) => { Console.WriteLine(context.RequestAborted.IsCancellationRequested); if(context.Response.StatusCode < 200 || context.Response.StatusCode > 299) { Console.WriteLine(); Console.WriteLine(context.Request.Method); Console.WriteLine(context.Request.Path); } await next.Invoke(); }); Is there an easy way to
Continue readingSerilog – logging specific properties from request body on error
Issue I tried the following answer: https://stackoverflow.com/a/68493795/897326 Namely this: options.EnrichDiagnosticContext = (diagnosticContext, httpContext) => { // string body = your logic to get body from httpContext.Request.Body diagnosticContext.Set("Body", body); }; But in my case body is an empty string. My code
Continue readingDesign pattern for including errors with return values
Issue I’m writing an add-in for another piece of software through its API. The classes returned by the API can only be access through the native software and the API. So I am writing my own stand alone POCO/DTO objects
Continue readingSeparating concerns with Linq To SQL and DTO's
Issue I recently started a new webforms project and decided to separate the business classes from any DBML references. My business layer classes instead access discrete Data layer methods and are returned collections of DTO’s. So the data layer might
Continue readingAutoMapper: Convert Type for one Property
Issue I use the following two classes for Entity and DTO: public class VehicleEntity { public int Id { get; set; } public string AddressNumber { get; set; } public string VehicleNumber { get; set; } public string Brand {
Continue readingWindows Phone 8 (C#) — Buttons not responding to long press on initial load
Issue I’m testing a simple Windows Phone 8 app with the emulator. I discovered that on the initial load of an app, a Button object will not respond correctly to a long press — if that button is the first
Continue readingWPF, ScrollViewer consuming touch before longpress
Issue I’m kinda new to this WPF world. And I’m kinda confused on why my scrollview is consuming my touch event. My current situation is this: I have this ScrollViewer with an ItemsControl. In this ItemsControl I’m using a Wrappanel
Continue readingHow to fix routing failure with ApiController?
Issue I have a small ASP.NET Core web app project named "OdeToFood". The dev environment includes: IDE: Visual Studio 2019 on Windows 10 PC ASP.NET Core 3.1 Use Dapper for data access from SQL DB Not using MVC In one
Continue reading