{"id":11332,"date":"2017-06-07T16:20:10","date_gmt":"2017-06-07T21:20:10","guid":{"rendered":"https:\/\/stackify.com\/?p=11332"},"modified":"2024-05-24T05:16:04","modified_gmt":"2024-05-24T05:16:04","slug":"top-net-software-errors","status":"publish","type":"post","link":"https:\/\/stackify.com\/top-net-software-errors\/","title":{"rendered":"Top .NET Software Errors: 50 Common Mistakes and How to Fix Them"},"content":{"rendered":"<p>Developing in .NET provides several powerful benefits, including less overall code, improved security, ease of updates\/changes, and language independence.<\/p>\n<p>That said, the system isn\u2019t without errors and problems. From common exceptions to coding mistakes to incorrect assumptions, most of these issues come down to programmer error.<\/p>\n<p>The list below shares the 50 top .NET software errors from around the web. It includes exceptions, broken data bindings, <a href=\"\/java-memory-leaks-solutions\/\">memory leaks<\/a>, LINQ issues, mistyping errors, and dozens more. We also look at ways to fix each one.<\/p>\n<p>When you&#8217;re ready to start coding, download\u00a0our free guide to <a href=\"https:\/\/info.stackify.com\/guide-to-dotnet-profilers-from-stackify\">.NET Profilers<\/a> for some insider knowledge and everything you need to know about code profiling for .NET. And while you&#8217;re at it, be sure to check out <a href=\"https:\/\/stackify.com\/prefix\/\">Prefix<\/a>, our own lightweight profiler for .NET and Java developers. (And, if you&#8217;re thinking about .NET Core, read our opinion on why it&#8217;s the next big thing <a href=\"https:\/\/stackify.com\/net-core-csharp-next-programming-language\/\">here<\/a>.)<\/p>\n<h2>1. NullReferenceException<\/h2>\n<p>This .NET exception gets thrown whenever we try to use a class <a href=\"https:\/\/stackify.com\/csharp-random-numbers\/\">reference<\/a> that\u2019s set to null\/Nothing, when the code expects otherwise. In the very simple example below, the string \u201cfoo\u201d is set to <em>null<\/em>.<\/p>\n<pre class=\"prettyprint\">string foo = null;\nfoo.ToUpper();\n<\/pre>\n<p>The second line above will throw a NullReferenceException because we can\u2019t call the method on a string that points to <em>null.<\/em><\/p>\n<p>To fix\/avoid this error:<\/p>\n<ul>\n<li>Build <em>null<\/em> checking into the code and set default values.<\/li>\n<li>Use Debug.Assert to catch the problem before the exception occurs.<\/li>\n<li>See examples for <a href=\"http:\/\/stackoverflow.com\/questions\/4660142\/what-is-a-nullreferenceexception-and-how-do-i-fix-it\" target=\"_blank\" rel=\"noopener noreferrer\">avoiding the NullReferenceException .NET error here<\/a>. (<a href=\"https:\/\/twitter.com\/StackOverflow\" target=\"_blank\" rel=\"noopener noreferrer\">@StackOverflow<\/a>)<\/li>\n<\/ul>\n<h2>2. DivideByZeroException<\/h2>\n<p>The DivideByZeroException error gets thrown whenever a program tries to divide by zero. To handle it gracefully, protect any code that does arithmetic division within try-catch blocks that look for that specific exception. Here\u2019s an example:<\/p>\n<pre class=\"prettyprint\">try\n{\nint x = SomeService.Calculate();\nint y = 10 \/ x;\n}\ncatch (DivideByZeroException ex)\n{\n\/\/TODO: Write code that should run when x is 0\n}\n<\/pre>\n<p>Ways to fix\/prevent DivideByZeroException:<\/p>\n<ul>\n<li>Use Try\/Catch blocks to catch the exception.<\/li>\n<li>Set <em>guards<\/em> on functions that throw errors in the event of a zero value.<\/li>\n<li>Use validation on critical user inputs to prevent zero values.<\/li>\n<li>For more detail on how to handle this .NET error, see this article from <a href=\"https:\/\/www.dotnetperls.com\/dividebyzeroexception\" target=\"_blank\" rel=\"noopener noreferrer\">Dot Net Perls<\/a>.<\/li>\n<\/ul>\n<h2>3. Broken Data Bindings in WPF<\/h2>\n<p>Data bindings in WPF can be a huge time saver \u2013 when they work well. When they break, they\u2019re one of the more frustrating .NET errors out there. In the example below, there\u2019s a TextBlock with a missing data context. Frustratingly, it won\u2019t show errors in Visual Studio\u2019s output window.<\/p>\n<pre class=\"prettyprint\">    \n&lt;Window x:Class=\"WpfApplication1.MainWindow\"\n xmlns=\"http:\/\/schemas.microsoft.com\/winfx\/2006\/xaml\/presentation\"\n xmlns:x=\"http:\/\/schemas.microsoft.com\/winfx\/2006\/xaml\"\n Title=\"MainWindow\" Height=\"350\" Width=\"525\"&gt;\n &lt;Grid&gt;\n &lt;TextBlock Text=\"{Binding ThereIsNoDataContext}\"\/&gt;\n &lt;\/Grid&gt;\n&lt;\/Window&gt;\n\n<span style=\"font-family: Georgia, 'Times New Roman', 'Bitstream Charter', Times, serif;\">We can fix this by enabling tracing to the output window to reveal any problems:<\/span>\n<\/pre>\n<pre class=\"prettyprint\">    \n &lt;Window x:Class=\"WpfApplication1.MainWindow\"\n xmlns=\"http:\/\/schemas.microsoft.com\/winfx\/2006\/xaml\/presentation\"\n xmlns:x=\"http:\/\/schemas.microsoft.com\/winfx\/2006\/xaml\"\nxmlns:diag=\"clr-namespace:System.Diagnostics;assembly=WindowsBase\"\n Title=\"MainWindow\" Height=\"350\" Width=\"525\"&gt;\n &lt;Grid&gt;\n &lt;TextBlock Text=\"{Binding ThereIsNoDataContext,\ndiag:PresentationTraceSources.TraceLevel=High}\" \/&gt;\n &lt;\/Grid&gt;\n&lt;\/Window&gt;\n<\/pre>\n<p>Here are a couple of other fixes for the broken data bindings error:<\/p>\n<ul>\n<li>Add a Value Converter that Breaks into the Debugger.<\/li>\n<li>Add a TraceListener so you know right away when a data binding breaks.<\/li>\n<li>There\u2019s a great tutorial that gives more detail on fixing this issue\u00a0<a href=\"https:\/\/spin.atomicobject.com\/2013\/12\/11\/wpf-data-binding-debug\/\" target=\"_blank\" rel=\"noopener noreferrer\">here<\/a>. (<a href=\"https:\/\/twitter.com\/atomicobject\" target=\"_blank\" rel=\"noopener noreferrer\">@atomicobject<\/a>)<\/li>\n<\/ul>\n<p><a href=\"https:\/\/github.com\/paologutierrez\/.net50\/blob\/master\/brokendatabindingswpf.md\" target=\"_blank\" rel=\"noopener noreferrer\">https:\/\/github.com\/paologutierrez\/.net50\/blob\/master\/brokendatabindingswpf.md<\/a><\/p>\n<h2>4. Using a Reference Like a Value or Vice Versa<\/h2>\n<p>This problem is specific to C#. In C#, the programmer who writes the object decides whether the value assigned to it is a value or a reference to another object. The example below shows a couple of unwanted surprises.<\/p>\n<pre class=\"prettyprint\">Point point1 = new Point(20, 30);\nPoint point2 = point1;\npoint2.X = 50;\nConsole.WriteLine(point1.X);       \/\/ 20 (does this surprise you?)\nConsole.WriteLine(point2.X);       \/\/ 50\n  \nPen pen1 = new Pen(Color.Black);\nPen pen2 = pen1;\npen2.Color = Color.Blue;\nConsole.WriteLine(pen1.Color);     \/\/ Blue (or does this surprise you?)\nConsole.WriteLine(pen2.Color);     \/\/ Blue\n\n<\/pre>\n<p>To fix the problem, look at definitions of the object types. In Visual Studio, do this by putting your cursor over the object\u2019s name and pressing F12.<\/p>\n<p>For a more in-depth explanation of the reference\/value error, see <a href=\"https:\/\/helpcontentsblog.wordpress.com\/2017\/01\/23\/using-a-reference-like-a-value-or-vice-versa\/\" target=\"_blank\" rel=\"noopener noreferrer\">this tutorial<\/a>.<\/p>\n<p><a href=\"https:\/\/github.com\/paologutierrez\/.net50\/blob\/master\/using-reference-like-value-vice-versa.md\" target=\"_blank\" rel=\"noopener noreferrer\">https:\/\/github.com\/paologutierrez\/.net50\/blob\/master\/using-reference-like-value-vice-versa.md<\/a><\/p>\n<h2>5. Letting Compiler Warnings Accumulate<\/h2>\n<p>This very common issue erodes the strict type checking provided by the C# compiler. The temptation to hide warnings in Visual Studio\u2019s \u201cError List\u201d window can lead to a buildup of hidden or ignored warnings. Unheeded warnings can cause eventual code problems like this:<\/p>\n<pre class=\"prettyprint\">class Account {\n  \n      int myId;\n      int Id;   \/\/ compiler warned you about this, but you didn\u2019t listen!\n  \n      \/\/ Constructor\n      Account(int id) {\n          this.myId = Id;     \/\/ OOPS!\n      }\n  \n  }\n\n<\/pre>\n<p>Of course, the easy fix for the buildup of compiler warnings is to set aside regular time blocks to address them. Spending a few seconds on each warning now can save hours down the road. See <a href=\"https:\/\/helpcontentsblog.wordpress.com\/2017\/01\/23\/allowing-compiler-warnings-to-accumulate-2\/\" target=\"_blank\" rel=\"noopener noreferrer\">this article<\/a> for more.<\/p>\n<p><a href=\"https:\/\/github.com\/paologutierrez\/.net50\/blob\/master\/allowing-compiler-warnings-accumulate.md\" target=\"_blank\" rel=\"noopener noreferrer\">https:\/\/github.com\/paologutierrez\/.net50\/blob\/master\/allowing-compiler-warnings-accumulate.md<\/a><\/p>\n<h2>6. Losing Scope Before Disposing an Object<\/h2>\n<p>Disposing objects before all references to them are out of scope is a housekeeping issue. We might assume the garbage collector will take care of it when it runs the object\u2019s finalizer, but that isn\u2019t always the case.<\/p>\n<p>To fix this error, make sure all .NET objects are explicitly disposed.<\/p>\n<ul>\n<li>Use the <em>using<\/em> statement to wrap all IDisposable objects. Objects wrapped in this way will automatically be disposed when the using block closes.<\/li>\n<li><a href=\"https:\/\/msdn.microsoft.com\/en-us\/library\/ms182289.aspx?cs-save-lang=1&amp;cs-lang=csharp#code-snippet-2\">In some cases, the <\/a><a href=\"https:\/\/msdn.microsoft.com\/en-us\/library\/ms182289.aspx?cs-save-lang=1&amp;cs-lang=csharp#code-snippet-2\"><em>using<\/em><\/a><a href=\"https:\/\/msdn.microsoft.com\/en-us\/library\/ms182289.aspx?cs-save-lang=1&amp;cs-lang=csharp#code-snippet-2\" target=\"_blank\" rel=\"noopener noreferrer\"> statement isn\u2019t enough<\/a>. (<a href=\"https:\/\/twitter.com\/msdev\" target=\"_blank\" rel=\"noopener noreferrer\">@msdev<\/a>)<span class=\"username u-dir\" dir=\"ltr\">\u00a0One example is when nesting constructors are protected by only one exception handler.<\/span><\/li>\n<li>For additional protection, add specific code to check and dispose variables when needed. The <em>finally<\/em> block below does this with the <em>tempPort\u00a0<\/em>variable.<\/li>\n<\/ul>\n<pre class=\"prettyprint\">public SerialPort OpenPort1(string portName)\n{\n   SerialPort port = new SerialPort(portName);\n   port.Open();  \/\/CA2000 fires because this might throw\n   SomeMethod(); \/\/Other method operations can fail\n   return port;\n}\n\npublic SerialPort OpenPort2(string portName)\n{\n   SerialPort tempPort = null;\n   SerialPort port = null;\n   try\n   {\n      tempPort = new SerialPort(portName);\n      tempPort.Open();\n      SomeMethod();\n      \/\/Add any other methods above this line\n      port = tempPort;\n      tempPort = null;\n      \n   }\n   finally\n   {\n      if (tempPort != null)\n      {\n         tempPort.Close();\n      }\n   }\n   return port;\n}\n\n<\/pre>\n<h3>7. Redundant Nested Exception Handling<\/h3>\n<p>While not exactly a .NET error, using too much exception handling with nested methods is definitely a mistake. This one creates a lot of redundant code and a real performance drain. The best practice here is using nested exception handling, which performs the exception handling only once:<\/p>\n<pre class=\"prettyprint\"> public class NestedExceptionHandling\n  {\n      public void MainMethod()\n      {\n          try\n          {\n              \/\/some implementation\n              ChildMethod1();\n          }\n          catch (Exception exception)\n          {\n              \/\/Handle exception\n          }\n      }\n  \n      private void ChildMethod1()\n      {\n          try\n          {\n              \/\/some implementation\n              ChildMethod2();\n          }\n          catch (Exception exception)\n          {\n              \/\/Handle exception\n  \t     throw;\n  \n          }\n      }\n  \n      private void ChildMethod2()\n      {\n          try\n          {\n              \/\/some implementation\n          }\n          catch (Exception exception)\n          {\n              \/\/Handle exception\n              throw;\n          }\n      }\n  }\n\n<\/pre>\n<p>For a deeper look at this mistake, see <a href=\"http:\/\/www.codeguru.com\/csharp\/article.php\/c17911\/7-Common-Mistakes-Made-By-C-Programmers.htm\" target=\"_blank\" rel=\"noopener noreferrer\">this article<\/a>. (<a href=\"https:\/\/twitter.com\/Codeguru\">@Codeguru<\/a>)<\/p>\n<p><a href=\"https:\/\/github.com\/paologutierrez\/.net50\/blob\/master\/nested-exception-handling.mdown\" target=\"_blank\" rel=\"noopener noreferrer\">https:\/\/github.com\/paologutierrez\/.net50\/blob\/master\/nested-exception-handling.mdown<\/a><\/p>\n<h3>8. Deferred Execution in LINQ<\/h3>\n<p>LINQ makes it a lot easier to query data than if we use for\/each loops with conditional logic like nested if blocks. But consider the code below, which uses LINQ-to-SQL to get a customer list:<\/p>\n<pre class=\"prettyprint\">public IEnumerable GetCustomers()\n\t{\n\t\tusing(var context = new DBContext())\n\t\t{\n\t\t\treturn from c in context.Customers\n\t\t\t       where c.Balance &gt; 2000\n\t\t\t       select c;\n\t\t}\n\t}\n\n<\/pre>\n<p>The code seems fine until we try to enumerate the collection. At that point, we\u2019ll get an \u201cObjectDisposedException.\u201d That\u2019s because link won\u2019t actually perform the query until we attempt to enumerate the results.<\/p>\n<p>To fix this, first convert your LINQ queries to a List using ToList(), or to an array using ToArray(). This step will ensure all LINQ queries get evaluated right away. See more on this <a href=\"https:\/\/visualstudiomagazine.com\/articles\/2010\/08\/31\/5-traps-to-avoid-in-csharp.aspx\" target=\"_blank\" rel=\"noopener noreferrer\">here<\/a>. (<a href=\"https:\/\/twitter.com\/VSMdev\" target=\"_blank\" rel=\"noopener noreferrer\">@VSMdev<\/a>)<\/p>\n<p><a href=\"https:\/\/github.com\/paologutierrez\/.net50\/blob\/master\/deferred-execution-in-linq.md\" target=\"_blank\" rel=\"noopener noreferrer\">https:\/\/github.com\/paologutierrez\/.net50\/blob\/master\/deferred-execution-in-linq.md<\/a><\/p>\n<h3>9. Iterating with Values Instead of with LINQ<\/h3>\n<p>Here\u2019s another \u201cnot quite a .NET error\u201d that\u2019s nonetheless a big mistake. Iterating through long lists of records is far from efficient. Rather than rely on a foreach loop or a for loop, use LINQ. LINQ or Language-Integrated Query is a feature of .NET that makes it easier to query objects like long lists or collections.<\/p>\n<pre class=\"prettyprint\">foreach (Customer customer in CustomerList) {\n   if (customer.State == \"FL\") {\n     tax += customer.Balance;\n   }\n }\n\n<\/pre>\n<p>The code above returns 1,000 customers. That\u2019s much more efficient than getting 100,000 customers with a foreach loop. For more, see <a href=\"https:\/\/www.upwork.com\/hiring\/development\/common-mistakes-in-c-sharp-programming\/\">this post<\/a>. (<a href=\"https:\/\/twitter.com\/Upwork\" target=\"_blank\" rel=\"noopener noreferrer\">@Upwork<\/a>)<\/p>\n<p><a href=\"https:\/\/github.com\/paologutierrez\/.net50\/blob\/master\/iterating-through-values-instead-of-using-linq.md\" target=\"_blank\" rel=\"noopener noreferrer\">https:\/\/github.com\/paologutierrez\/.net50\/blob\/master\/iterating-through-values-instead-of-using-linq.md<\/a><\/p>\n<h3>10. Accessing Virtual Members within a Constructor<\/h3>\n<p>This C# error comes from executing code before its time. This can happen when we call an overridden method straight from the constructor of a base class.<\/p>\n<p>In the example below, the virtual method call is made on a class before the class\u2019 constructor has been run.<\/p>\n<pre class=\"prettyprint\">public class Parent\n{\n  public Parent()\n  {\n    Console.WriteLine(\"Parent Ctor\");\n    Method();\n  }\n\n  public virtual void Method()\n  {\n    Console.WriteLine(\"Parent method\");\n  }\n}\n\npublic class Child : Parent\n{\n  public Child()\n  {\n    Console.WriteLine(\"Child Ctor\");\n  }\n\n  public override void Method()\n  {\n    Console.WriteLine(\"Child method\");\n  }\n}\n\n<\/pre>\n<p>To fix the problem, first mark your class as sealed. This ensures that it\u2019s the most derived type within the inheritance hierarchy. That way, when we call the virtual method, we don\u2019t get a warning.<\/p>\n<ul>\n<li>For more information, <a href=\"https:\/\/codeaddiction.net\/articles\/38\/10-common-traps-and-mistakes-in-c\" target=\"_blank\" rel=\"noopener noreferrer\">see this tutorial<\/a>. (<a href=\"https:\/\/twitter.com\/code_addiction\" target=\"_blank\" rel=\"noopener noreferrer\">@code_addiction<\/a>)<\/li>\n<li>Also, <a href=\"http:\/\/stackoverflow.com\/questions\/119506\/virtual-member-call-in-a-constructor\" target=\"_blank\" rel=\"noopener noreferrer\">see this discussion<\/a> about the virtual method call error. (<a href=\"https:\/\/twitter.com\/StackOverflow\" target=\"_blank\" rel=\"noopener noreferrer\">@StackOverflow<\/a>)<\/li>\n<\/ul>\n<p><a href=\"https:\/\/github.com\/paologutierrez\/.net50\/blob\/master\/accessing-virtual-member-in-a-constructor.md\" target=\"_blank\" rel=\"noopener noreferrer\">https:\/\/github.com\/paologutierrez\/.net50\/blob\/master\/accessing-virtual-member-in-a-constructor.md<\/a><\/p>\n<h3>11. Logic Errors<\/h3>\n<p>Logic errors happen when we don\u2019t get the result we expected. They don\u2019t always result in error messages because they\u2019re not technically \u201cbugs.\u201d Instead, they\u2019re problems with programming logic. Take a look at the code below. It tries to add up the numbers from one to ten.<\/p>\n<pre class=\"prettyprint\">private void button1_Click(object, sender, EventArgs e)\n{\n    int startLoop = 11;\n    int endLoop = 1;\n    int answer = 0;\n    \n    for (int i = startLoop; i &lt; endLoop; i++)\n    {\n        answer = answer + i;\n    }\n    \n    MessageBox.Show(\"answer =\" + answer.ToString());\n}\n\n<\/pre>\n<p>Can you see the error? The answer is zero! The program didn\u2019t run into any code errors, but it gave us the wrong answer. That\u2019s a logic error. We should have set the startLoop variable as 1, and endLoop as 11. To nip logic errors in the bud:<\/p>\n<ul>\n<li>Use C# .NET Breakpoints. This is where we tell C# to stop the code, so we can assess what\u2019s in the variables.<\/li>\n<li>Use the C# .NET Locals Window. This keeps track of what\u2019s in local variables.<\/li>\n<li>Use Try &#8230; Catch blocks.<\/li>\n<li>For a full tutorial on how to implement the above fixes, <a href=\"http:\/\/www.homeandlearn.co.uk\/csharp\/csharp_s5p3.html\" target=\"_blank\" rel=\"noopener noreferrer\">click here<\/a>.<\/li>\n<\/ul>\n<p><a href=\"https:\/\/github.com\/paologutierrez\/.net50\/blob\/master\/logic-error.md\" target=\"_blank\" rel=\"noopener noreferrer\">https:\/\/github.com\/paologutierrez\/.net50\/blob\/master\/logic-error.md<\/a><\/p>\n<h3>12. Mixing Strings and Numbers with +<\/h3>\n<p>Most languages use the + sign for both concatenation and arithmetic addition. That means 2 + 2 is 4 and \u201chello \u201d + \u201cworld\u201d is \u201chello world.\u201d But what about \u201chello \u201c + 2? This would result in \u201chello 2\u201d. This would be better expressed as \u201chello \u201d + \u201c2\u201d.<\/p>\n<p>Here\u2019s a less obvious example:<\/p>\n<pre class=\"prettyprint\">static void Main(string[] args) {\n\n    int x = 4;\n    string y = \"12\";\n\n    Console.WriteLine(string.Format(\"{0}\", x + y)); \/\/ 412\n\n    Console.ReadKey();\n}\n\n<\/pre>\n<p>In this case, x + y is 412, where 4 is a number and \u201c12\u201d is a string.<\/p>\n<p>To head this mistake off:<\/p>\n<ul>\n<li>Make sure all values you intend to add are actually numbers.<\/li>\n<li>Use string.Format() instead of concatenating with +.<\/li>\n<li>Perform arithmetic as distinct statements before outputting concatenated results or strings.<\/li>\n<li>For an in-depth tutorial, <a href=\"http:\/\/www.dreamincode.net\/forums\/topic\/384373-10-common-programming-mistakes\/\" target=\"_blank\" rel=\"noopener noreferrer\">click here<\/a>. (<a href=\"https:\/\/twitter.com\/DreamInCode\" target=\"_blank\" rel=\"noopener noreferrer\">@DreamInCode<\/a>)<\/li>\n<\/ul>\n<p><a href=\"https:\/\/github.com\/paologutierrez\/.net50\/blob\/master\/concatenating-rather-than-adding.md\" target=\"_blank\" rel=\"noopener noreferrer\">https:\/\/github.com\/paologutierrez\/.net50\/blob\/master\/concatenating-rather-than-adding.md<\/a><\/p>\n<h3>13. Forgetting Strings Are Immutable<\/h3>\n<p>Strings are immutable in .NET. That means once we create a string, we can\u2019t change its value. It may <em>look<\/em> like we\u2019re changing a string\u2019s value, but what we\u2019re really doing is creating a new object with a new value.<\/p>\n<p>The example below shows how forgetting that strings are immutable can lead us into a problem. (<a href=\"https:\/\/twitter.com\/amazedsaint\" target=\"_blank\" rel=\"noopener noreferrer\">@amazedsaint<\/a>)<\/p>\n<pre class=\"prettyprint\">string = \"Take this out\";\ns.Replace(\"this\", \"that\"); \/\/wrong\n\ns = s.Replace(\"this\", \"that\"); \/\/correct\n\n<\/pre>\n<p>There\u2019s another great example of an immutable string error <a href=\"https:\/\/www.codeproject.com\/Articles\/406046\/Why-strings-are-immutable-and-what-are-the-implica\" target=\"_blank\" rel=\"noopener noreferrer\">here<\/a> that results in the creation of 10,000 unwanted string variables. (<a href=\"https:\/\/twitter.com\/codeproject\" target=\"_blank\" rel=\"noopener noreferrer\">@codeproject<\/a>)\u00a0The article presents an elegant solution: using the StringBuilder class to change the text without making thousands of new String class instances.<\/p>\n<p><a href=\"https:\/\/github.com\/paologutierrez\/.net50\/blob\/master\/forgetting-that-strings-are-immutable.md\" target=\"_blank\" rel=\"noopener noreferrer\">https:\/\/github.com\/paologutierrez\/.net50\/blob\/master\/forgetting-that-strings-are-immutable.md<\/a><\/p>\n<h3>14. Incorrect Granularity<\/h3>\n<p>Here\u2019s a common C# error that results from a multithreading mistake. This happens when we use <em>lock<\/em> with poor code synchronization.<\/p>\n<p>The example below checks for curse words in a string, printing a warning if it finds one. It also performs several other operations. The code isn\u2019t synchronized, however, so it\u2019s not thread safe. For instance, two threads might try to update the same counter at the same time, causing an exception.<\/p>\n<pre class=\"prettyprint\">private static List wordList;\nprivate static List curseWords;\nprivate static int currentWordIndex;\nprivate static Dictionary&lt;string, int&gt; wordCountDict;\n\npublic static void CalculateWordCounts() {\n\twordList = GetWordList();\n\tcurseWords = GetCurseWords();\n\tcurrentWordIndex = 0;\n\twordCountDict = new Dictionary&lt;string, int&gt;();\n\n\tThread threadA = new Thread(ThreadDoWork);\n\tThread threadB = new Thread(ThreadDoWork);\n\tThread threadC = new Thread(ThreadDoWork);\n\tThread threadD = new Thread(ThreadDoWork);\n\tthreadA.Start();\n\tthreadB.Start();\n\tthreadC.Start();\n\tthreadD.Start();\n\tthreadA.Join();\n\tthreadB.Join();\n\tthreadC.Join();\n\tthreadD.Join();\n}\n\nprivate static void ThreadDoWork() {\n\tbool atLeastOneWordRemaining;\n\tint thisWordIndex = currentWordIndex;\n\tcurrentWordIndex = currentWordIndex + 1;\n\tif (thisWordIndex &gt;= wordList.Count) atLeastOneWordRemaining = false;\n\telse atLeastOneWordRemaining = true;\n\n\twhile (atLeastOneWordRemaining) {\n\t\tstring thisWord = wordList[thisWordIndex];\n\t\tbool firstOccurrenceOfWord = !wordCountDict.ContainsKey(thisWord);\n\n\t\tif (curseWords.Contains(thisWord)) Console.WriteLine(\"Curse word detected!\");\n\t\tif (firstOccurrenceOfWord) wordCountDict.Add(thisWord, 1);\n\t\telse wordCountDict[thisWord] = wordCountDict[thisWord] + 1;\n\n\t\tthisWordIndex = currentWordIndex;\n\t\tcurrentWordIndex = currentWordIndex + 1;\n\t\tif (thisWordIndex &gt;= wordList.Count) atLeastOneWordRemaining = false;\n\t}\n}\n\n<\/pre>\n<p>To repair this:<\/p>\n<ul>\n<li>Make sure only one thread can read\/update a counter at a time.<\/li>\n<li>Lock over checking\/updating routines.<\/li>\n<li>For a full tutorial on the incorrect granularity error, <a href=\"http:\/\/benbowen.blog\/post\/cmmics_i\/\" target=\"_blank\" rel=\"noopener noreferrer\">click here<\/a>. (<a href=\"https:\/\/twitter.com\/Xenoprimate\" target=\"_blank\" rel=\"noopener noreferrer\">@Xenoprimate<\/a>)<\/li>\n<\/ul>\n<p><a href=\"https:\/\/github.com\/paologutierrez\/.net50\/blob\/master\/incorrect-granularity.md\" target=\"_blank\" rel=\"noopener noreferrer\">https:\/\/github.com\/paologutierrez\/.net50\/blob\/master\/incorrect-granularity.md<\/a><\/p>\n<h3>15. Unhandled Exogenous Exceptions<\/h3>\n<p>This may sound like the lost Dali painting, but it\u2019s just a fancy way of saying, \u201cunhandled, handleable exceptions.\u201d Since the definition of <em>exogenous<\/em> is \u201coriginating externally,\u201d these exceptions are beyond our control and must be anticipated and handled.<\/p>\n<p>The code below shows a good example.<\/p>\n<pre class=\"prettyprint\">try \n{   \n  using ( File f = OpenFile(filename, ForReading) )   \n  {\n    \/\/ Blah blah blah   \n  } \n} \ncatch (FileNotFoundException) \n{   \n  \/\/ Handle file not found \n}\n\n<\/pre>\n<p>We have to use the try-catch block because something might have happened to our file. Use try-catch blocks to avoid an error arising from these exceptions.<\/p>\n<p>See <a href=\"https:\/\/ericlippert.com\/2008\/09\/10\/vexing-exceptions\/\" target=\"_blank\" rel=\"noopener noreferrer\">this tutorial<\/a> for a good explanation of the different kinds of exceptions, plus whether and how to handle them. (<a href=\"https:\/\/twitter.com\/ericlippert\" target=\"_blank\" rel=\"noopener noreferrer\">@ericlippert<\/a>)<\/p>\n<p><a href=\"https:\/\/github.com\/paologutierrez\/.net50\/blob\/master\/failure-to-handle-exogenous-exceptions.md\" target=\"_blank\" rel=\"noopener noreferrer\">https:\/\/github.com\/paologutierrez\/.net50\/blob\/master\/failure-to-handle-exogenous-exceptions.md<\/a><\/p>\n<h3>16. Protection Level Conflicts<\/h3>\n<p>For any class, the default protection level is \u201cinternal.\u201d For any member in that class, the default level is \u201cprivate.\u201d We can run into an\u00a0issue\u00a0when we forget those facts.<\/p>\n<pre class=\"prettyprint\">class MyFirstClass \/\/default protection = internal\n{\n    public void NameFunction() {\n        MySecondClass sc = new MySecondClass();\n        sc.strFirstName = \"Harry\";\n        sc.strLastName = \"Potter\";\n        Console.WriteLine(\"Name: \" + sc.FirstName + \" \" + sc.strLastName);\n    }\n}\n\npublic class MySecondClass\n{\n    string strFirstName = \"Roy\";\n    string strLastName = \"Weasley\"; \/\/default protection = private\n}\n\n<\/pre>\n<p>When we declare \u201cMySecondClass\u201d public, its variables don\u2019t also become public. If we want MyFirstClass to be able to access the variables in MySecondClass, we\u2019ll need to set MyFirstClass and the MySecondClass variables to \u201cpublic.\u201d See <a href=\"http:\/\/www.developerdrive.com\/2011\/12\/common-c-build-time-errors-part-i\/\" target=\"_blank\" rel=\"noopener noreferrer\">this post <\/a>for more details. (<a href=\"https:\/\/twitter.com\/DeveloperDrive\" target=\"_blank\" rel=\"noopener noreferrer\">@DeveloperDrive<\/a>)<\/p>\n<p><a href=\"https:\/\/github.com\/paologutierrez\/.net50\/blob\/master\/protection-level-conflicts.md\" target=\"_blank\" rel=\"noopener noreferrer\">https:\/\/github.com\/paologutierrez\/.net50\/blob\/master\/protection-level-conflicts.md<\/a><\/p>\n<h3>17. StackOverflowException<\/h3>\n<p>Apart from being a popular developer forum, this is also a common error. This one is something like an OutOfMemoryException because it means your code has exceeded a memory boundary. The stack is finite, which means if we have too many memory allocations in it, we\u2019ll get an overflow exception.<\/p>\n<p>The simple C# example below shows an infinite recursion that will trigger a StackOverflowException.<\/p>\n<pre class=\"prettyprint\">class Program\n{\n    private static int hitCount;\n\n    static void Main(string[] args)\n    {\n        hitCount = 0;\n        MyRecursiveExample(null);\n    }\n\n    static void MyRecursiveExample(string value)\n    {\n        hitCount++;\n\n        if (value == null)\n        {\n            MyRecursiveExample(value);\n        }\n        else\n        {\n            System.Console.WriteLine(value);\n        }\n    }\n}\n<\/pre>\n<p>To avoid the StackOverflowException error, try not to have objects mutually reference each other whenever possible. See <a href=\"http:\/\/stackoverflow.com\/questions\/14019239\/how-can-i-avoid-a-stackoverflowexception-in-c\" target=\"_blank\" rel=\"noopener noreferrer\">this discussion<\/a> and <a href=\"https:\/\/www.experts-exchange.com\/articles\/5389\/5-Common-Exceptions-in-NET-and-How-to-Resolve-Them.html\">this article<\/a> for more insight. (<a href=\"https:\/\/twitter.com\/StackOverflow\" target=\"_blank\" rel=\"noopener noreferrer\">@StackOverflow<\/a> and\u00a0<a href=\"https:\/\/twitter.com\/ExpertsExchange\" target=\"_blank\" rel=\"noopener noreferrer\">@ExpertsExchange<\/a>)<\/p>\n<p><a href=\"https:\/\/github.com\/paologutierrez\/.net50\/blob\/master\/stack-overflow-exception.md\">https:\/\/github.com\/paologutierrez\/.net50\/blob\/master\/stack-overflow-exception.md<\/a><\/p>\n<h3>18. Busy-Wait and Thread.Sleep<\/h3>\n<p>Using busy-wait instead of correct thread synchronization can deliver a troublesome error. The code below will suck up 100% of the CPU core while the thread in Example() processes the <em>while<\/em> loop.<\/p>\n<pre class=\"prettyprint\">private static string userInput;\n\nprivate static void Example() {\n\tuserInput = null;\n\tGetUserInput(); \/\/ tells the UI to request user input on the UI thread\n\t\n\twhile (userInput == null) ; \/\/ wait for user input\n\t\n\tProcessUserInput(userInput); \/\/ now use that input\n}\n<\/pre>\n<p>Some developers will try to use something like <em>Thread.Sleep(100) <\/em>to interrupt an infinite loop. While this works, it\u2019s sloppy coding, since what we really need is an in-built synchronization construct. In general, we should only use Thread.Sleep:<\/p>\n<ul>\n<li>To make some kind of timer functionality<\/li>\n<li>For testing, but not for production<\/li>\n<li>For a more in-depth look at how to dodge the busy-wait and thread.sleep error, <a href=\"http:\/\/benbowen.blog\/post\/cmmics_iv\/\" target=\"_blank\" rel=\"noopener noreferrer\">click here<\/a>. (<a href=\"https:\/\/twitter.com\/Xenoprimate\" target=\"_blank\" rel=\"noopener noreferrer\">@Xenoprimate<\/a>)<\/li>\n<\/ul>\n<p><a href=\"https:\/\/github.com\/paologutierrez\/.net50\/blob\/master\/busy-waiting-and-thread-sleep.md\">https:\/\/github.com\/paologutierrez\/.net50\/blob\/master\/busy-waiting-and-thread-sleep.md<\/a><\/p>\n<h3>19. Handling Non-Exogenous Exceptions<\/h3>\n<p>Certain .NET errors in the form of exceptions that can\u2019t be foreseen and that originate from outside our control must be handled. For example, let\u2019s say our program does a check for File.Exists. The file does exist, but between the check and the next operation, the file gets deleted. That said, most exceptions should be avoided whenever possible by writing code that renders them unnecessary. Consider the following three exceptions:<\/p>\n<pre class=\"prettyprint\">string val = null;\n  int value = int.Parse(str); \/\/Will throw ArgumentNullException\n\n  string val = \"100.11\";\n  int value = int.Parse(val); \/\/Will throw FormatException\n\n  string val = \"999999999999999999999999999999999999999999\";\n  int value = int.Parse(val); \/\/Will throw OverflowException\u203a\u203a\n\n<\/pre>\n<p>If we use the int.TryParse() method instead of an exception, we get a 0 response. That means this method avoids the need for complex and potentially buggy exception handling.<\/p>\n<ul>\n<li>For a full breakdown of the above example, <a href=\"http:\/\/dailydotnettips.com\/2016\/01\/16\/back-to-basic-difference-between-int-parse-and-int-tryparse\/\" target=\"_blank\" rel=\"noopener noreferrer\">see this article<\/a>. (<a href=\"https:\/\/twitter.com\/DailyDotNetTips\" target=\"_blank\" rel=\"noopener noreferrer\">@DailyDotNetTips<\/a>)<\/li>\n<li>For a robust discussion about avoiding exceptions, <a href=\"http:\/\/wiki.c2.com\/?AvoidExceptionsWheneverPossible\" target=\"_blank\" rel=\"noopener noreferrer\">click here<\/a>. (<a href=\"https:\/\/twitter.com\/WardCunningham\" target=\"_blank\" rel=\"noopener noreferrer\">@WardCunningham<\/a>)<\/li>\n<li>See <a href=\"https:\/\/www.quora.com\/Why-do-people-usually-avoid-exceptions-when-writing-code\" target=\"_blank\" rel=\"noopener noreferrer\">this post <\/a>for a good explanation of the reasons to avoid exceptions. (<a href=\"https:\/\/twitter.com\/Quora\" target=\"_blank\" rel=\"noopener noreferrer\">@Quora<\/a>)<\/li>\n<\/ul>\n<p><a href=\"https:\/\/github.com\/paologutierrez\/.net50\/blob\/master\/avoiding-exceptions-instead-of-working-with-them.mdown\" target=\"_blank\" rel=\"noopener noreferrer\">https:\/\/github.com\/paologutierrez\/.net50\/blob\/master\/avoiding-exceptions-instead-of-working-with-them.mdown<\/a><\/p>\n<h3>20. Unsafe Assumptions in Multithreading<\/h3>\n<p>Certain assumptions about how multithreading works can lead us to unexpected problems. These are especially likely when working with shared state. Often, the mistakes arise when we think multithreaded code works in the same way as single-threaded code.<\/p>\n<p>One example is a torn read from non-atomic access to a variable<em>.<\/em> The following code will return unwanted values:<\/p>\n<pre class=\"prettyprint\">private const int NUM_ITERATIONS = 20000;\nprivate const decimal DENOMINATOR = 200m;\nprivate const decimal MAX_POSSIBLE_VALUE = NUM_ITERATIONS \/ DENOMINATOR;\n\nprivate static decimal sharedState;\npublic static decimal SharedState {\n\tget {\n\t\treturn sharedState;\n\t}\n\tset {\n\t\tsharedState = value;\n\t}\n}\n\nstatic void Main(string[] args) {\n\tThread writerThread = new Thread(WriterThreadEntry);\n\tThread readerThread = new Thread(ReaderThreadEntry);\n\n\twriterThread.Start();\n\treaderThread.Start();\n\n\twriterThread.Join();\n\treaderThread.Join();\n\n\tConsole.ReadKey();\n}\n\nprivate static void WriterThreadEntry() {\n\tfor (int i = 0; i &lt; NUM_ITERATIONS; ++i) {\n\t\tSharedState = i \/ DENOMINATOR;\n\t}\n}\n\nprivate static void ReaderThreadEntry() {\n\tfor (int i = 0; i &lt; NUM_ITERATIONS; ++i) { var sharedStateLocal = SharedState; if (sharedStateLocal &gt; MAX_POSSIBLE_VALUE) Console.WriteLine(\"Impossible value detected: \" + sharedStateLocal);\n\t}\n}\n\n<\/pre>\n<p>The problem\u00a0occurs because one thread can read the value of sharedState halfway through a write by another thread. This forces the variable into values we hadn\u2019t anticipated (or wanted).<\/p>\n<p>To fix the problem, make access to the variable <em>atomic.<\/em> To do this:<\/p>\n<ul>\n<li>Use the <em>lock<\/em> statement<\/li>\n<li>Use the <em>Interlocked<\/em><\/li>\n<\/ul>\n<p>For a detailed breakdown of incorrect multithreading assumptions in .NET and how to fix them, see <a href=\"http:\/\/benbowen.blog\/post\/cmmics_iii\/\" target=\"_blank\" rel=\"noopener noreferrer\">this in-depth tutorial<\/a>. (<a href=\"https:\/\/twitter.com\/Xenoprimate\" target=\"_blank\" rel=\"noopener noreferrer\">@Xenoprimate<\/a>)<\/p>\n<p><a href=\"https:\/\/github.com\/paologutierrez\/.net50\/blob\/master\/unsafe-assumptions-on-multithreading.md\" target=\"_blank\" rel=\"noopener noreferrer\">https:\/\/github.com\/paologutierrez\/.net50\/blob\/master\/unsafe-assumptions-on-multithreading.md<\/a><\/p>\n<h3>21. The Nullable Paradox<\/h3>\n<p>A nullable value passed to the stack will create garbage. Paradoxically, a similar variable that\u2019s actually set to null won\u2019t create any garbage.<\/p>\n<pre class=\"prettyprint\">private static void DoTestA() {\n    int? maybeInt = null;\n    for (int i = 0; i &lt; 100000; ++i) {\n        DoSomething(maybeInt);\n    }\n}\n \nprivate static void DoTestB() {\n    int? maybeInt = 3;\n    for (int i = 0; i &lt; 100000; ++i) {\n        DoSomething(maybeInt);\n    }\n}\n \nprivate static void DoSomething(object o) {\n    \/\/ Do something...\n}\n\n<\/pre>\n<p>In the example above, DoTestA() creates zero garbage, while DoTestB() quickly racks up a large amount.<\/p>\n<p>The best way to fix this is to generify our DoSomething method:<\/p>\n<pre class=\"prettyprint\">Private static void DoSomething&lt;T&gt;(T o) {\n\n\/\/ Do something...\n\n}\n\n<\/pre>\n<p>For a more detailed explanation of this paradox and how to fix it, see <a href=\"http:\/\/benbowen.blog\/post\/three_garbage_examples\/\" target=\"_blank\" rel=\"noopener noreferrer\">this post<\/a>. (<a href=\"https:\/\/twitter.com\/Xenoprimate\">@Xenoprimate<\/a>)<\/p>\n<p><a href=\"https:\/\/github.com\/paologutierrez\/.net50\/blob\/master\/nullable-paradox.md\" target=\"_blank\" rel=\"noopener noreferrer\">https:\/\/github.com\/paologutierrez\/.net50\/blob\/master\/nullable-paradox.md<\/a><\/p>\n<h3>22. Failure to Log Exceptions<\/h3>\n<p>This common mistake is really one of omission. It can result in user problems with no indication of what went wrong. Consider the case of a user registration functionality with unlogged exceptions. In this case, if registration fails, our log stays empty.<\/p>\n<pre class=\"prettyprint\">public class UserService\n{\n    private readonly IMessagingService _messagingService;\n    public UserService(IMessagingService messagingService)\n    {\n        _messagingService = messagingService;\n    }\n\n    public bool RegisterUser(string login, string emailAddress, string password)\n    {\n        \/\/ insert user to the database\n\n        \/\/ generate an activation code to send via email\n\n        \/\/ save activation code to the database\n\n        \/\/ create an email message object\n        try\n        {\n            _messagingService.SendRegistrationEmailMessage(message);\n        }\n        catch (Exception)\n        {\n            \/\/ boom!\n        }\n        return true;\n\n    }\n}\n\n<\/pre>\n<p>Of course, the fix for this error is to add logging to the try-catch block. To see the full tutorial, <a href=\"https:\/\/www.codeproject.com\/Articles\/1173928\/Csharp-BAD-PRACTICES-Learn-how-to-make-a-good-co\" target=\"_blank\" rel=\"noopener noreferrer\">click here<\/a>. (<a href=\"https:\/\/twitter.com\/codeproject\" target=\"_blank\" rel=\"noopener noreferrer\">@codeproject<\/a>)<\/p>\n<p><a href=\"https:\/\/github.com\/paologutierrez\/.net50\/blob\/master\/eating-exceptions.md\" target=\"_blank\" rel=\"noopener noreferrer\">https:\/\/github.com\/paologutierrez\/.net50\/blob\/master\/eating-exceptions.md<\/a><\/p>\n<h3>23. Unnecessary Contention in Multithreading<\/h3>\n<p>Contention happens when two or more threads try to access the same resource at the same time. They <em>contend<\/em> for the resource. This situation causes several\u00a0issues.<\/p>\n<p>Even when we use thread-safe coding, contention can still add overhead. For example, when we use the <em>lock<\/em> keyword, we force some threads to wait while one thread accesses a scope.<\/p>\n<p>The following multi-threaded code actually works worse than a single-threaded version would, because it creates a lot more overhead while some threads wait.<\/p>\n<pre class=\"prettyprint\">private static List wordList;\nprivate static List curseWords;\nprivate static int currentWordIndex;\nprivate static Dictionary&lt;string, int&gt; wordCountDict;\nprivate static readonly object wordCountCalculatorSyncObj = new object();\n\npublic static void CalculateWordCounts() {\n\twordList = GetWordList();\n\tcurseWords = GetCurseWords();\n\tcurrentWordIndex = 0;\n\twordCountDict = new Dictionary&lt;string, int&gt;();\n\n\tThread threadA = new Thread(ThreadDoWork);\n\tThread threadB = new Thread(ThreadDoWork);\n\tThread threadC = new Thread(ThreadDoWork);\n\tThread threadD = new Thread(ThreadDoWork);\n\tthreadA.Start();\n\tthreadB.Start();\n\tthreadC.Start();\n\tthreadD.Start();\n\tthreadA.Join();\n\tthreadB.Join();\n\tthreadC.Join();\n\tthreadD.Join();\n}\n\nprivate static void ThreadDoWork() {\n\tbool atLeastOneWordRemaining;\n\tint thisWordIndex;\n\tlock (wordCountCalculatorSyncObj) {\n\t\tthisWordIndex = currentWordIndex;\n\t\tcurrentWordIndex = currentWordIndex + 1;\n\t}\n\tif (thisWordIndex &gt;= wordList.Count) atLeastOneWordRemaining = false;\n\telse atLeastOneWordRemaining = true;\n\n\twhile (atLeastOneWordRemaining) {\n\t\tstring thisWord = wordList[thisWordIndex]\n\t\t\t.ToUpper()\n\t\t\t.Replace(\"-\", String.Empty)\n\t\t\t.Replace(\"'\", String.Empty)\n\t\t\t.Trim();\n\n\t\tif (curseWords.Contains(thisWord)) Console.WriteLine(\"Curse word detected!\");\n\n\t\tlock (wordCountCalculatorSyncObj) {\n\t\t\tbool firstOccurrenceOfWord = !wordCountDict.ContainsKey(thisWord);\n\t\t\n\t\t\tif (firstOccurrenceOfWord) wordCountDict.Add(thisWord, 1);\n\t\t\telse wordCountDict[thisWord] = wordCountDict[thisWord] + 1;\n\t\t\tthisWordIndex = currentWordIndex;\n\t\t\tcurrentWordIndex = currentWordIndex + 1;\n\t\t}\n\t\tif (thisWordIndex &gt;= wordList.Count) atLeastOneWordRemaining = false;\n\t}\n}\n\n<\/pre>\n<p>The solution to this is to split the work into equal chunks before it\u2019s processed. Then, let each thread perform a local count before it updates the global one. To see how that works, take a look at <a href=\"http:\/\/benbowen.blog\/post\/cmmics_ii\/\" target=\"_blank\" rel=\"noopener noreferrer\">this article<\/a>. (<a href=\"https:\/\/twitter.com\/Xenoprimate\" target=\"_blank\" rel=\"noopener noreferrer\">@Xenoprimate<\/a>)<\/p>\n<p><a href=\"https:\/\/github.com\/paologutierrez\/.net50\/blob\/master\/unnecessary-contention-in-multithreading.md\" target=\"_blank\" rel=\"noopener noreferrer\">https:\/\/github.com\/paologutierrez\/.net50\/blob\/master\/unnecessary-contention-in-multithreading.md<\/a><\/p>\n<h3>24. Using Weak Cryptographic Algorithms<\/h3>\n<p>Using old, outdated cryptographic algorithms is one of the most easily avoided errors. Algorithms like TripleDES, SHA1, and RIPEMD160 can\u2019t deliver the level of security that their more modern counterparts can.<\/p>\n<pre class=\"prettyprint\">using System.Security.Cryptography;   \n...   \nvar hashAlg = SHA1.Create();  \n\n<\/pre>\n<p>To avoid the CA5350 CheckID, use stronger algorithms.<\/p>\n<ul>\n<li>Instead of TripleDES, use Aes encryption.<\/li>\n<li>Instead of SHA1 or RIPEMD160, use SHA512, SHA384, or SHA256.<\/li>\n<li>See this <a href=\"https:\/\/msdn.microsoft.com\/en-us\/library\/mt612872.aspx\" target=\"_blank\" rel=\"noopener noreferrer\">page<\/a> from Microsoft for full documentation. (<a href=\"https:\/\/twitter.com\/msdev\" target=\"_blank\" rel=\"noopener noreferrer\">@msdev<\/a>)<\/li>\n<\/ul>\n<p><a href=\"https:\/\/github.com\/paologutierrez\/.net50\/blob\/master\/using-weak-cryptography.md\" target=\"_blank\" rel=\"noopener noreferrer\">https:\/\/github.com\/paologutierrez\/.net50\/blob\/master\/using-weak-cryptography.md<\/a><\/p>\n<h3>25. Using the Wrong Collection Type<\/h3>\n<p>In .NET, using the right collection type can save time and avoid errors. Below is a list of the most commonly used C# collections.<\/p>\n<pre class=\"prettyprint\">var list = new List();\n\n  var dictionary = new Dictionary&lt;int, Customer&gt;();\n\n  var hashSet = new HashSet();\n\n  var stack = new Stack();\n\n  var queue = new Queue();\n\n<\/pre>\n<ul>\n<li>The <em>List<\/em> collection type can grow in size to accommodate growing data sets.<\/li>\n<li>The <em>Dictionary<\/em> collection type is useful for fast lookups by keys.<\/li>\n<li>The HashSet collection type works best for very fast lookups in a list of unique items.<\/li>\n<li>The Stack collection type comes in handy for providing users with ways to go back.<\/li>\n<li>This great tutorial gives a great explanation of how to avoid errors by using the right collection type for the job. (<a href=\"https:\/\/twitter.com\/moshhamedani\" target=\"_blank\" rel=\"noopener noreferrer\">@moshhamedani<\/a>)<\/li>\n<\/ul>\n<p><a href=\"https:\/\/github.com\/paologutierrez\/.net50\/blob\/master\/Not-using-the-correct-collection-type-depending-on-the-situation.mdown\" target=\"_blank\" rel=\"noopener noreferrer\">https:\/\/github.com\/paologutierrez\/.net50\/blob\/master\/Not-using-the-correct-collection-type-depending-on-the-situation.mdown<\/a><\/p>\n<h3>26. Unregistered Events<\/h3>\n<p>This common mistake\u00a0happens when we create an event handler that handles events occurring in an object, but we don\u2019t clear the link when we\u2019ve finished. This oversight can leave behind an unwanted strong reference.<\/p>\n<p>In the code below, we subscribe to an <em>OnPlaced<\/em> event in our <em>Order<\/em> class, and the following code executes on a button click:<\/p>\n<pre class=\"prettyprint\">Order newOrder=new Order\n(\u201cEURUSD\u201d, DealType.Buy, Price ,PriceTolerance, TakeProfit, StopLoss);\n\nnewOrder.OnPlaced+=OrderPlaced;\nm_PendingDeals.Add(newOrder);\n\n<\/pre>\n<p>When the <em>OrderPlaced<\/em> method is called, the following code executes:<\/p>\n<pre class=\"prettyprint\">Void OrderPlace(Order pladedOrder)\n\n{\n\nm_PendingDeals.Remove(placedOrder);\n\n}\n\n<\/pre>\n<p>However, a reference to the <em>Order<\/em> object is still held by the <em>OrderPlaced<\/em> event handler. The <em>Order<\/em> object is therefore kept alive, even though we removed it from the collection. For more information on this, see:<\/p>\n<ul>\n<li>This <a href=\"http:\/\/www.red-gate.com\/products\/dotnet-development\/ants-memory-profiler\/learning-memory-management\/WPF-silverlight-pitfalls\" target=\"_blank\" rel=\"noopener noreferrer\">article<\/a> on unregistered events (<a href=\"https:\/\/twitter.com\/redgate\" target=\"_blank\" rel=\"noopener noreferrer\">@redgate<\/a>)<\/li>\n<li>This <a href=\"http:\/\/stackoverflow.com\/questions\/292820\/how-to-correctly-unregister-an-event-handler\" target=\"_blank\" rel=\"noopener noreferrer\">discussion<\/a> on unregistered events (<a href=\"https:\/\/twitter.com\/StackOverflow\" target=\"_blank\" rel=\"noopener noreferrer\">@StackOverflow<\/a>)<\/li>\n<li>This Microsoft library <a href=\"https:\/\/msdn.microsoft.com\/en-us\/library\/ff621447.aspx\" target=\"_blank\" rel=\"noopener noreferrer\">page<\/a>. (<a href=\"https:\/\/twitter.com\/msdev\" target=\"_blank\" rel=\"noopener noreferrer\">@msdev<\/a>)<\/li>\n<\/ul>\n<p><a href=\"https:\/\/github.com\/paologutierrez\/.net50\/blob\/master\/unregistered-events.md\" target=\"_blank\" rel=\"noopener noreferrer\">https:\/\/github.com\/paologutierrez\/.net50\/blob\/master\/unregistered-events.md<\/a><\/p>\n<h3>27. Readonly Shorthand Property Declaration<\/h3>\n<p>This WCF error happens when we fail to keep both <em>getter<\/em> and <em>setter<\/em> in our code when using the ReadOnly shorthand property declaration with the <em>DataMember<\/em> attribute. Without the <em>setter<\/em> part, we\u2019ll get an error.<\/p>\n<pre class=\"prettyprint\">\/\/Data Contract attribute applied to class to make it available to client.\n\n\/\/Data Member attribute applied to the 'MyVar' readonly property.\n\n    [DataContract]\n    public class MyValueObject\n    {\n        [DataMember]\n        public int MyVar\n        {\n            get;\n        \/\/This will not work, as WCF needs both getter and setter to access property.\n\n        }\n    }  \n\n    \/\/Correct version with both getters and setter defined.\n\n    [DataContract]\n    public class MyValueObject\n    {\n        [DataMember]\n        public int MyVar\n        {\n            get; \n            set {}\n            \/\/Empty setter block is supplied for readonly property. \n\n        }\n    }\n\n<\/pre>\n<p>We can circumvent this problem by setting a block with empty brackets, as shown in this <a href=\"https:\/\/www.codeproject.com\/Articles\/763271\/Common-issues-in-WCF\" target=\"_blank\" rel=\"noopener noreferrer\">article<\/a>. (<a href=\"https:\/\/twitter.com\/codeproject\" target=\"_blank\" rel=\"noopener noreferrer\">@codeproject<\/a>)<\/p>\n<p><a href=\"https:\/\/github.com\/paologutierrez\/.net50\/blob\/master\/readonly-shorthand-property-declaration-in-wcf.md\" target=\"_blank\" rel=\"noopener noreferrer\">https:\/\/github.com\/paologutierrez\/.net50\/blob\/master\/readonly-shorthand-property-declaration-in-wcf.md<\/a><\/p>\n<h3>28. Mistyping the WF\/WCF Service Configuration Name<\/h3>\n<p>When we use WCF with Visual Studio, we can run into\u00a0a problem that comes from default configurations.<\/p>\n<pre class=\"prettyprint\">&lt;?xml version=\"1.0\" encoding=\"utf-8\" ?&gt;\n&lt;configuration&gt;\n&lt;system.serviceModel&gt;\n&lt;behaviors&gt;\n&lt;serviceBehaviors&gt;\n&lt;behavior&gt;\n&lt;serviceMetadata httpGetEnabled=\"true\"\/&gt;\n&lt;serviceDebug includeExceptionDetailInFaults=\"false\"\/&gt;\n&lt;\/behavior&gt;\n&lt;\/serviceBehaviors&gt;\n&lt;\/behaviors&gt;\n&lt;\/system.serviceModel&gt;\n&lt;\/configuration&gt;\n<\/pre>\n<p>The code above doesn\u2019t specify a &lt;services&gt; section. It therefore adds a set of default endpoints to your service. This can result in the use of an incorrect service name. To fix this situation, we\u2019ll need to manually change the name of our service in the configuration file. See this <a href=\"https:\/\/blogs.msdn.microsoft.com\/endpoint\/2009\/11\/09\/common-user-mistake-in-net-4-mistyping-the-wfwcf-service-configuration-name\/\" target=\"_blank\" rel=\"noopener noreferrer\">tutorial<\/a> for more. (<a href=\"https:\/\/twitter.com\/msdev\" target=\"_blank\" rel=\"noopener noreferrer\">@msdev<\/a>)<\/p>\n<p><a href=\"https:\/\/github.com\/paologutierrez\/.net50\/blob\/master\/mistyping-the-wf-wcf-service-configuration-name.md\" target=\"_blank\" rel=\"noopener noreferrer\">https:\/\/github.com\/paologutierrez\/.net50\/blob\/master\/mistyping-the-wf-wcf-service-configuration-name.md<\/a><\/p>\n<h3>29. Modifying SMSvcHost.exe.config for WCF<\/h3>\n<p>We can run into several WCF errors when we modify the SMSvcHost.exe.config file improperly. The sample settings for the file are shown below:<\/p>\n<pre class=\"prettyprint\">&lt;net.tcp listenBacklog=\u201d10? maxPendingConnections=\u201d100? maxPendingAccepts=\u201d2? receiveTimeout=\u201d00:00:10? teredoEnabled=\u201dfalse\u201d&gt;\n&lt;allowAccounts&gt;\n\/\/ LocalSystem account\n&lt;add securityIdentifier=\u201dS-1-5-18?\/&gt;\n\n\/\/ LocalService account\n&lt;add securityIdentifier=\u201dS-1-5-19?\/&gt;\n\n\/\/ Administrators account\n&lt;add securityIdentifier=\u201dS-1-5-20?\/&gt;\n\n\/\/ Network Service account\n&lt;add securityIdentifier=\u201dS-1-5-32-544? \/&gt;\n\n\/\/ IIS_IUSRS account (Vista only)\n&lt;add securityIdentifier=\u201dS-1-5-32-568?\/&gt;\n&lt;\/allowAccounts&gt;\n&lt;\/net.tcp&gt;\n<\/pre>\n<p>Some common problems that arise from modifying the file include:<\/p>\n<ul>\n<li>Modifying the wrong SMSvcHost.exe.config file.<\/li>\n<li>Changing dummy settings in a comment within the file.<\/li>\n<li>Failing to restart Net.Tcp Port Sharing service after making changes to the file.<\/li>\n<\/ul>\n<p>For steps to avoid making these common mistakes, see this <a href=\"https:\/\/blogs.msdn.microsoft.com\/asiatech\/2012\/07\/16\/modifying-smsvchost-exe-config-for-wcf-some-common-mistakes\/\" target=\"_blank\" rel=\"noopener noreferrer\">blog post<\/a> from Microsoft. (<a href=\"https:\/\/twitter.com\/msdev\" target=\"_blank\" rel=\"noopener noreferrer\">@msdev<\/a>)<\/p>\n<p><a href=\"https:\/\/github.com\/paologutierrez\/.net50\/blob\/master\/modifying-smsvchost-exe-config.md\" target=\"_blank\" rel=\"noopener noreferrer\">https:\/\/github.com\/paologutierrez\/.net50\/blob\/master\/modifying-smsvchost-exe-config.md<\/a><\/p>\n<h3>30. Leaving Tracing Enabled in Web-Based Applications<\/h3>\n<p>Tracing is a very useful .NET debugging tool. It\u2019s also an excellent way for a hacker to access your system if it\u2019s left in place in a production environment. Don\u2019t fall into the trap shown below:<\/p>\n<pre class=\"prettyprint\">&lt;configuration&gt;\n\n&lt;system.web&gt;\n\n&lt;trace enabled=\"true\" localOnly=\"false\"&gt;\n<\/pre>\n<p>In the configuration above, any user can access a detailed list of all recent requests to the app. How? By browsing the page \u201ctrace.axd.\u201d The trace log provides a plethora of useful information to the hacker.<\/p>\n<p>The best way to prevent hacks through tracing data is to disable tracing. Do this by setting \u201cenabled\u201d to \u201cfalse\u201d for the &lt;trace&gt; element. For more info, see this <a href=\"https:\/\/weblogs.asp.net\/dotnetstories\/five-common-mistakes-in-the-web-config-file\" target=\"_blank\" rel=\"noopener noreferrer\">tutorial<\/a>. (<a href=\"https:\/\/twitter.com\/dotnetstories\" target=\"_blank\" rel=\"noopener noreferrer\">@dotnetstories<\/a>)<\/p>\n<p><a href=\"https:\/\/github.com\/paologutierrez\/.net50\/blob\/master\/leaving-tracing-enabled-in-web-Based-applications.md\" target=\"_blank\" rel=\"noopener noreferrer\">https:\/\/github.com\/paologutierrez\/.net50\/blob\/master\/leaving-tracing-enabled-in-web-Based-applications.md<\/a><\/p>\n<h3>31. Custom Errors Disabled<\/h3>\n<p>Disabling custom errors in .NET gives clients detailed error messages by default.<\/p>\n<pre class=\"prettyprint\">&lt;configuration&gt;\n&lt;system.web&gt;\n&lt;customErrors mode=\u201dOff\u201c&gt;\n<\/pre>\n<p>With the above configuration, hackers get good information about the source of errors that can help them learn to pick our coding locks. Default ASP.NET error messages show our ASP.NET version and framework, plus the exception type.<\/p>\n<p>To fix the problem:<\/p>\n<ul>\n<li>Set <em>customErrors<\/em> mode to <em>RemoteOnly <\/em>or Doing this displays more generic, nondescript error messages.<\/li>\n<li>Set the\u00a0<em>defaultRedirect <\/em>attribute of the &lt;customErrors&gt; element to redirect the user to a new page.<\/li>\n<li>See this <a href=\"https:\/\/dotnetstories.wordpress.com\/2007\/10\/13\/the-worst-5-mistakes-in-the-webconfig-file\/\" target=\"_blank\" rel=\"noopener noreferrer\">post<\/a> for a more detailed walk-through of fixing this issue. (<a href=\"https:\/\/twitter.com\/dotnetstories\" target=\"_blank\" rel=\"noopener noreferrer\">@dotnetstories<\/a>)<\/li>\n<\/ul>\n<p><a href=\"https:\/\/github.com\/paologutierrez\/.net50\/blob\/master\/custom-errors-disabled.md\" target=\"_blank\" rel=\"noopener noreferrer\">https:\/\/github.com\/paologutierrez\/.net50\/blob\/master\/custom-errors-disabled.md<\/a><\/p>\n<h3>32. Binding Leak<\/h3>\n<p>WPF has several data binding options. If we break them, they can cause memory leaks within our applications. For example, look at the class shown below:<\/p>\n<pre class=\"prettyprint\">class Person\n{\n    public Person(string name)\n    {\n        Name = name\n    }\n    \n    public string Name {get; set;}\n}\n\n<\/pre>\n<p>With the example above, in certain cases, WPF will create a runtime leak by creating a reference to the System.Component.Model.PropertyDescriptor class. When this happens, runtime doesn\u2019t know when to deallocate the reference. Therefore, our source object remains in memory.<\/p>\n<ul>\n<li>Detect this error by checking the dotMemory automatic inspections snapshot overview page for WPF binding leaks.<\/li>\n<li>Fix the problem by making the object a DependencyProperty. For complete instructions, see this <a href=\"https:\/\/blog.jetbrains.com\/dotnet\/2014\/09\/04\/fighting-common-wpf-memory-leaks-with-dotmemory\/\" target=\"_blank\" rel=\"noopener noreferrer\">tutorial<\/a>. (<a href=\"https:\/\/twitter.com\/jetbrains\" target=\"_blank\" rel=\"noopener noreferrer\">@jetbrains<\/a>)<\/li>\n<\/ul>\n<p><a href=\"https:\/\/github.com\/paologutierrez\/.net50\/blob\/master\/binding-leak.md\" target=\"_blank\" rel=\"noopener noreferrer\">https:\/\/github.com\/paologutierrez\/.net50\/blob\/master\/binding-leak.md<\/a><\/p>\n<h3>33. Forgetting to an XSRF Token to the Client<\/h3>\n<p>XRSF tokens protect against cross-site request forgeries. We need to use them any time the browser can authenticate the user implicitly. That includes automatic authentication with cookies, or apps using Windows authentication.<\/p>\n<p>The code below passes an XSRF token to the client, avoiding this egregious mistake.<\/p>\n<pre class=\"prettyprint\">[Route(\"api\/[controller]\")]\npublic class XsrfTokenController : Controller\n{\n    private readonly IAntiforgery _antiforgery;\n \n    public XsrfTokenController(IAntiforgery antiforgery)\n    {\n        _antiforgery = antiforgery;\n    }\n \n    [HttpGet]\n    public IActionResult Get()\n    {\n        var tokens = _antiforgery.GetAndStoreTokens(HttpContext);\n \n        return new ObjectResult(new {\n            token = tokens.RequestToken,\n            tokenName = tokens.HeaderName\n        });\n    }\n}\n\n<\/pre>\n<p>Read the full tutorial on this <a href=\"http:\/\/odetocode.com\/blogs\/scott\/archive\/2017\/02\/06\/anti-forgery-tokens-and-asp-net-core-apis.aspx\" target=\"_blank\" rel=\"noopener noreferrer\">here<\/a>. (<a href=\"https:\/\/twitter.com\/OdeToCode\" target=\"_blank\" rel=\"noopener noreferrer\">@OdeToCode<\/a>)<\/p>\n<p><a href=\"https:\/\/github.com\/paologutierrez\/.net50\/blob\/master\/not-protecting-clients-with-xsrf-tokens.md\" target=\"_blank\" rel=\"noopener noreferrer\">https:\/\/github.com\/paologutierrez\/.net50\/blob\/master\/not-protecting-clients-with-xsrf-tokens.md<\/a><\/p>\n<h3>34. DispatcherTimer Leak<\/h3>\n<p>A DispatcherTimer leak is an error where improper use of the DispatcherTimer causes a memory leak.<\/p>\n<p>In the example below, the <em>count<\/em> variable gets updated once per second by the DispatcherTimer. The reference is held by the Dispatcher, which keeps each UserControl alive, causing a memory leak.<\/p>\n<pre class=\"prettyprint\">public byte[] myMemory = new byte[50 * 1024 * 1024];\n\nSystem.Windows.Threading.DispatcherTimer _timer = new System.Windows.Threading.DispatcherTimer();\nint count = 0;\n\n\nprivate void MyLabel_Loaded(object sender, RoutedEventArgs e)\n{\n\n    _timer.Interval = TimeSpan.FromMilliseconds(1000);\n\n    _timer.Tick += new EventHandler(delegate(object s, EventArgs ev)\n\n    {\n        count++;\n        textBox1.Text = count.ToString();\n    });\n\n    _timer.Start();\n}\n\n<\/pre>\n<p>Fixing this is easy. Just <a href=\"https:\/\/www.simple-talk.com\/dotnet\/net-performance\/the-top-5-wpf-and-silverlight-gotchas\/\" target=\"_blank\" rel=\"noopener noreferrer\">stop the timer<\/a> and set it to null. (<a href=\"https:\/\/twitter.com\/Simple_Talk\" target=\"_blank\" rel=\"noopener noreferrer\">@Simple_Talk<\/a>)<\/p>\n<pre class=\"prettyprint\">_timer.Stop();\n\n_timer=null;\n\n<\/pre>\n<p><a href=\"https:\/\/github.com\/paologutierrez\/.net50\/blob\/master\/dispatcher-timer-leak.md\" target=\"_blank\" rel=\"noopener noreferrer\">https:\/\/github.com\/paologutierrez\/.net50\/blob\/master\/dispatcher-timer-leak.md<\/a><\/p>\n<h3>35. x:Name leak<\/h3>\n<p>Building UIs in software lets us add convenient functionality, such as removing certain controls from the UI after the user performs a given action. However, if we don\u2019t build the UI correctly, we can introduce a memory leak.<\/p>\n<p>Every time we declare a UI element in XAML using the x:Name directive, WPF will create a strong global reference.<\/p>\n<p>We may think we can dynamically remove the element, but the control will stay in memory, even after we remove it from the <em>Children<\/em> collection of the parent control:<\/p>\n<pre class=\"prettyprint\">private void DeleteData_OnClick(object sender, RouteEventArgs e)\n{\n    if (personEditor != null)\n    {\n        _grid.Children.Remove(personEditor);\n        personEditor = null;\n    }\n}\n\n<\/pre>\n<p>Here\u2019s how to fix this common issue:<\/p>\n<ul>\n<li>To detect the problem, click the button to remove the control, then take a snapshot in dotMemory. The snapshot will show that the control stayed in memory.<\/li>\n<li>Fix it by calling the parent control\u2019s UnregisterName method.<\/li>\n<li>For a full brief on this error and its fix, see <a href=\"https:\/\/blog.jetbrains.com\/dotnet\/2014\/09\/04\/fighting-common-wpf-memory-leaks-with-dotmemory\/\" target=\"_blank\" rel=\"noopener noreferrer\">here<\/a>. (<a href=\"https:\/\/twitter.com\/jetbrains\" target=\"_blank\" rel=\"noopener noreferrer\">@jetbrains<\/a>)<\/li>\n<\/ul>\n<p><a href=\"https:\/\/github.com\/paologutierrez\/.net50\/blob\/master\/x-name-leak.md\" target=\"_blank\" rel=\"noopener noreferrer\">https:\/\/github.com\/paologutierrez\/.net50\/blob\/master\/x-name-leak.md<\/a><\/p>\n<h3>36. TextBox Undo Leak<\/h3>\n<p>This isn\u2019t actually a leak, but rather an intended behavior. When an app updates large strings to text boxes over several iterations, we can see a buildup of data on their undo stacks.<\/p>\n<p>The default settings will create this problem by enabling undo and\/or by setting the UndoLimit at -1, which means the number of actions will be limited only by the amount of available memory.<\/p>\n<pre class=\"prettyprint\">textBox1.IsUndoEnabled=true;\ntextBox1.UndoLimit=-1\n\n<\/pre>\n<p>To rectify\u00a0this, either set IsUndoEnabled to false, or set an UndoLimit other than -1 (such as 100).<\/p>\n<p>To see this problem and solution explained in more detail, see this <a href=\"https:\/\/www.simple-talk.com\/dotnet\/net-performance\/the-top-5-wpf-and-silverlight-gotchas\/\" target=\"_blank\" rel=\"noopener noreferrer\">article<\/a>. (<a href=\"https:\/\/twitter.com\/Simple_Talk\" target=\"_blank\" rel=\"noopener noreferrer\">@Simple_Talk<\/a>)<\/p>\n<p><a href=\"https:\/\/github.com\/paologutierrez\/.net50\/blob\/master\/textbox-undo-leak.md\" target=\"_blank\" rel=\"noopener noreferrer\">https:\/\/github.com\/paologutierrez\/.net50\/blob\/master\/textbox-undo-leak.md<\/a><\/p>\n<h3>37. Event Handler Leak<\/h3>\n<p>Yet another memory leak error\u00a0is the event handler leak. In C#, we don\u2019t always get a leak when we subscribe to an event and then forget to unsubscribe. In most cases, the events don\u2019t stay in memory.<\/p>\n<p>However, when an event publisher is long lived, then all its subscribers will be kept alive too, as in the following example:<\/p>\n<pre class=\"prettyprint\">public class ShortLivedEventSubscriber\n{\n    public static int Count;\n\n    public string LatestText { get; private set; }\n\n    public ShortLivedEventSubscriber(Control c)\n    {\n        Interlocked.Increment(ref Count);\n        c.TextChanged += OnTextChanged;\n    }\n\n    private void OnTextChanged(object sender, EventArgs eventArgs)\n    {\n        LatestText = ((Control) sender).Text;\n    }\n\n    ~ShortLivedEventSubscriber()\n    {\n        Interlocked.Decrement(ref Count);\n    }\n}\n\n<\/pre>\n<p>Here\u2019s the code that creates the instances:<\/p>\n<pre class=\"prettyprint\">private void OnShortLivedEventSubscribersClick(object sender, EventArgs eventArgs e)\n    {\nintcount = 10000;\nfor (int n = 0; n &lt; count; n++        \n{ \nvar shortlived2 = new ShortLivedEventSubscriber(this);\n}\nshortlivedEventSubscriberCreated += count;\n}\n\n<\/pre>\n<p>The solution here is simple. Any time you subscribe to an event, if it\u2019s raised by a service that has a long life, you must <a href=\"http:\/\/mark-dot-net.blogspot.com\/2012\/10\/understanding-and-avoiding-memory-leaks.html\" target=\"_blank\" rel=\"noopener noreferrer\">unsubscribe<\/a> from it.<\/p>\n<p><a href=\"https:\/\/github.com\/paologutierrez\/.net50\/blob\/master\/event-handler-leak.md\" target=\"_blank\" rel=\"noopener noreferrer\">https:\/\/github.com\/paologutierrez\/.net50\/blob\/master\/event-handler-leak.md<\/a><\/p>\n<h3>38. Potentially Dangerous Request.Form Value<\/h3>\n<p>Here\u2019s a workaround for an error caused when we want to send HTML code to a server. By default, we\u2019ll get an error, since ASP.NET MVC disables sending this type of code to the server in order to avoid Cross Site Scripting (XSS) attacks.<\/p>\n<p>As shown below, we can use the AllowHtml attribute for the model class to disable <a href=\"\/asp-net-razor-pages-vs-mvc\/\">ASP.NET MVC<\/a> validation for that particular property.<\/p>\n<pre class=\"prettyprint\">public class PersonModel\n{\n    [Display(Name = \"Resume:\")]\n    [AllowHtml]\n    public string Resume { get; set; }\n}\n\n<\/pre>\n<p>For the full rundown of using the AllowHtml attribute to avoid this issue, see this <a href=\"https:\/\/www.aspsnippets.com\/Articles\/What-is-AllowHtml-attribute-its-Uses-and-Examples-in-ASPNet-MVC.aspx\" target=\"_blank\" rel=\"noopener noreferrer\">tutorial<\/a>. (<a href=\"https:\/\/twitter.com\/ASPSnippets\" target=\"_blank\" rel=\"noopener noreferrer\">@ASPSnippets<\/a>)<\/p>\n<p><a href=\"https:\/\/github.com\/paologutierrez\/.net50\/blob\/master\/potentially-dangerous.md\" target=\"_blank\" rel=\"noopener noreferrer\">https:\/\/github.com\/paologutierrez\/.net50\/blob\/master\/potentially-dangerous.md<\/a><\/p>\n<h3>39. \u201cThe Remote Name Could Not Be Resolved\u201d (WCF\/Azure Error)<\/h3>\n<p>Sometimes a service that works fine on a local machine doesn\u2019t play well with Azure. In that case, we get a \u201cfailed to invoke the service\u201d notification.<\/p>\n<pre class=\"prettyprint\">Inner Exception: The remote name could not be resolved: \u2018rd00155d3ad8c4'    \nat System.Net.HttpWebRequest.GetRequestStream(TransportContext&amp; context)\nat System.Net.HttpWebRequest.GetRequestStream()\nat System.ServiceModel.Channels.HttpOutput.WebRequestHttpOutput.GetOutputStream()\n\n<\/pre>\n<p>This can be an extremely frustrating problem since there\u2019s no obvious reason for it to happen in the first place and there\u2019s no obvious fix.\u00a0Alter the web.config file as follows:<\/p>\n<pre class=\"prettyprint\">&lt;behavior name=\u201dMexGet\u201d&gt;\n\n&lt;serviceMetadata httpGetEnabled=\u201dtrue\u201d\u00a0 \/&gt;\n\n&lt;useRequestHeadersForMetadataAddress&gt;\n\n&lt;defaultPorts&gt;\n\n&lt;add scheme=\u201dhttp\u201d port=\u201d81? \/&gt;\n\n&lt;\/defaultPorts&gt;\n\n&lt;\/useRequestHeadersForMetadataAddress&gt;\n\n&lt;\/behavior&gt;\n<\/pre>\n<p>This sets up your service to operate in a load-balanced environment like Azure.<\/p>\n<p><a href=\"https:\/\/github.com\/paologutierrez\/.net50\/blob\/master\/error-in-wcf-azure.md\" target=\"_blank\" rel=\"noopener noreferrer\">https:\/\/github.com\/paologutierrez\/.net50\/blob\/master\/error-in-wcf-azure.md<\/a><\/p>\n<h3>40. PRB: \u201cAccess is Denied\u201d<\/h3>\n<p>When remotely debugging an ASP.NET application using Visual Studio, we can get the following error message:<\/p>\n<p>\u201cError while trying to run project: Unable to start debugging on the web server. Access is denied. Check the DCOM configuration settings for the machine debug manager. Would you like to disable future attempts to debug ASP.NET pages for this project?\u201d<\/p>\n<p>This happens because the user doing the remote debugging doesn\u2019t belong to the Debugger Users group for the MS Internet Information Server.<\/p>\n<p>To solve this problem, add the user to the appropriate group by following the steps shown in this Microsoft support page. (<a href=\"https:\/\/twitter.com\/MicrosoftHelps\" target=\"_blank\" rel=\"noopener noreferrer\">@MicrosoftHelps<\/a>)<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter wp-image-11374 size-full\" src=\"https:\/\/stackify.com\/wp-content\/uploads\/2017\/05\/prb-access-denied-11374.jpg\" alt=\"PRB: \u201cAccess is Denied\u201d\" width=\"500\" height=\"222\" \/><\/p>\n<h3>41. <a href=\"https:\/\/stackify.com\/viewbag\/\">ViewBag<\/a> Does Not Exist in the Current Context<\/h3>\n<p>This issue\u00a0can arise after upgrading an application from ASP MVC 4 to ASP MVC 5.<\/p>\n<p>To fix the problem, install the ASP.NET Web Helpers Library, then open the project\u2019s web.config file and update the bindings as follows:<\/p>\n<pre class=\"prettyprint\">&lt;dependentAssembly&gt;\n&lt;assemblyIdentity name=\u201dSystem.Web.Mvc\u201d publicKeyToken=\u201d31bf3856ad364e35? \/&gt;\n&lt;bindingRedirect oldVersion=\u201d0.0.0.0-5.2.2.0? newVersion=\u201d5.2.2.0\u201d \/&gt;\n&lt;\/dependentAssembly&gt;\n<\/pre>\n<p>In the appsettings, find \u201cwebpages:Version\u201d and update to version 3.0.0.0. Then restart Visual Studio. See this <a href=\"https:\/\/lajak.wordpress.com\/2014\/11\/16\/asp-mvc-5-viewbag-does-not-exist-in-the-current-context\/\" target=\"_blank\" rel=\"noopener noreferrer\">blog post<\/a> for more. (<a href=\"https:\/\/twitter.com\/AhmedAlAsaad\" target=\"_blank\" rel=\"noopener noreferrer\">@AhmedAlAsaad<\/a>)<\/p>\n<p><a href=\"https:\/\/github.com\/paologutierrez\/.net50\/blob\/master\/viewbag-does-not-exist.md\" target=\"_blank\" rel=\"noopener noreferrer\">https:\/\/github.com\/paologutierrez\/.net50\/blob\/master\/viewbag-does-not-exist.md<\/a><\/p>\n<h3>42. Error While Trying to Run Project<\/h3>\n<p>This error comes about when debugging an ASP.NET app with Visual Studio. The full error message is:<\/p>\n<p>\u201cError while trying to run project: Unable to start debugging on the web server. The project is not configured to be debugged.\u201d<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter wp-image-11376 size-full\" src=\"https:\/\/stackify.com\/wp-content\/uploads\/2017\/05\/error-running-project-11376.jpg\" alt=\"Error While Trying to Run Project\" width=\"500\" height=\"127\" \/><\/p>\n<p>We can run into this error for two reasons:<\/p>\n<ul>\n<li>The ASP.NET app is missing a web.config file.<\/li>\n<li>The project folder\u2019s <em>Execute Permissions<\/em> property in Internet Services Manager is set to<\/li>\n<\/ul>\n<p>To fix the problem, either add a web.config file (if it\u2019s missing) or set <em>Execute Permissions <\/em>to <em>Scripts only.<\/em> For more info, see this Microsoft help page. (<a href=\"https:\/\/twitter.com\/MicrosoftHelps\" target=\"_blank\" rel=\"noopener noreferrer\">@MicrosoftHelps<\/a>)<\/p>\n<h3>43. Not Taking Advantage of Dependency Injection<\/h3>\n<p>Let\u2019s say our Controller needs a <em>FooService<\/em> that lets it fetch a <em>Foo<\/em> that it can render to the user, like so:<\/p>\n<pre class=\"prettyprint\">public class FooController\n{\n    public IActionResult Index()\n    {\n        var fooService = new FooService(new BarService(), new BazService());\n        return View(fooService.GetFoo());\n    }\n}\n\n<\/pre>\n<p>The trouble is, our Controller needs fine details about how to create a <em>FooService<\/em>. That means we have to replicate that logic everywhere a <em>FooService<\/em> is needed.<\/p>\n<p>ASP.NET 5 MVC 6 gives us a baked-in feature called Dependency Injection. This lets us declare the dependency in the constructor. The ASP.NET 5 framework will then pass it in for us.<\/p>\n<p>To see all the steps to take advantage of this powerful feature, see this <a href=\"http:\/\/dotnetliberty.com\/index.php\/2015\/10\/15\/asp-net-5-mvc6-dependency-injection-in-6-steps\/\" target=\"_blank\" rel=\"noopener noreferrer\">tutorial<\/a>. (<a href=\"https:\/\/twitter.com\/ArmenShimoon\" target=\"_blank\" rel=\"noopener noreferrer\">@ArmenShimoon<\/a>)<\/p>\n<p><a href=\"https:\/\/github.com\/paologutierrez\/.net50\/blob\/master\/not-taking-advantage-of-dependency-injection.md\" target=\"_blank\" rel=\"noopener noreferrer\">https:\/\/github.com\/paologutierrez\/.net50\/blob\/master\/not-taking-advantage-of-dependency-injection.md<\/a><\/p>\n<h3>44. Misuse of the \u2018var\u2019 Keyword<\/h3>\n<p>Misuse and overuse of the <em>var<\/em> keyword is a common and basic error. The real purpose of <em>var<\/em> is to let us declare a local variable when we don\u2019t know the type name. This is usually true with anonymous types when we don\u2019t get the type name until compile time.<\/p>\n<p>Yet some developers use <em>var<\/em> every time they declare a variable. In a local variable declaration, the type name gives us an added layer of description:<\/p>\n<pre class=\"prettyprint\">\/\/ let's say we have a static method called GetContacts()\n\/\/ that returns System.Data.DataTable\nvar individuals = GetContacts(ContactTypes.Individuals);\n\n\/\/ how is it clear to the reader that I can do this?\nreturn individuals.Compute(\"MAX(Age)\", String.Empty);\n\n<\/pre>\n<p>Other reasons to limit the use of <em>var:<\/em><\/p>\n<ul>\n<li>It encourages Hungarian notation.<\/li>\n<li>It destroys the layer of context provided by type names.<\/li>\n<li>It increases reliance on IntelliSense.<\/li>\n<li>It doesn\u2019t provide backward compatibility.<\/li>\n<\/ul>\n<p>For an in-depth argument about <em>var<\/em> as an error, see this <a href=\"http:\/\/www.brad-smith.info\/blog\/archives\/336\" target=\"_blank\" rel=\"noopener noreferrer\">article<\/a>.<\/p>\n<p><a href=\"https:\/\/github.com\/paologutierrez\/.net50\/blob\/master\/misuse-of-var-keyword.md\" target=\"_blank\" rel=\"noopener noreferrer\">https:\/\/github.com\/paologutierrez\/.net50\/blob\/master\/misuse-of-var-keyword.md<\/a><\/p>\n<h3>45. Incorrectly using IoC Containers<\/h3>\n<p>Dependency injection is a powerful .NET tool we can use to avoid redundant code and save time and effort. Without dependency injection, we would have to reproduce the following code within multiple methods:<\/p>\n<pre class=\"prettyprint\">public class HomeController\n{\n  private readonly IExampleService _service;\n\n  public HomeController()\n  {\n    _service = new ExampleService();\n  }\n\n  public ActionResult Index()\n  {\n    return View(_service.GetSomething());\n  }\n}\n\n<\/pre>\n<p>However, when we use dependency injection improperly in the following ways, we run into errors:<\/p>\n<ul>\n<li>Using the container to retrieve dependencies instead of injecting them.<\/li>\n<li>Abstracting the container.<\/li>\n<li>Accessing the container to resolve components dynamically.<\/li>\n<\/ul>\n<p>For an in-depth tutorial on using IoC containers correctly, <a href=\"http:\/\/www.devtrends.co.uk\/blog\/how-not-to-do-dependency-injection-the-static-or-singleton-container\" target=\"_blank\" rel=\"noopener noreferrer\">click here<\/a>. (<a href=\"https:\/\/twitter.com\/DevTrends\" target=\"_blank\" rel=\"noopener noreferrer\">@DevTrends<\/a>)<\/p>\n<p><a href=\"https:\/\/github.com\/paologutierrez\/.net50\/blob\/master\/incorrectly-using-ioc-containers.md\" target=\"_blank\" rel=\"noopener noreferrer\">https:\/\/github.com\/paologutierrez\/.net50\/blob\/master\/incorrectly-using-ioc-containers.md<\/a><\/p>\n<h3>46. .ToLower() Not Working in LINQ Query<\/h3>\n<p>The String.ToLower method returns a copy of a string, converted to lowercase. However, this can cause a confusing error when we try to use it to compare values from different sources. Take the example below:<\/p>\n<pre class=\"prettyprint\">list = (from sr in dbContext.SERVICE_REQUEST\n             join sc in dbContext.SERVICE_CUSTOMER on sr.CUSTOMER_ID equals sc.CUSTOMER_ID)\n              where  (sr.SERVICE_REQUEST_NO.ToLower().Contains(objtobeAdvSearch.ServiceRequestNumber.ToLower()))\n\n<\/pre>\n<p>One <a href=\"https:\/\/www.experts-exchange.com\/questions\/28711309\/Tolower-is-not-working-in-linq-query.html\" target=\"_blank\" rel=\"noopener noreferrer\">solution<\/a>\u00a0(<a href=\"https:\/\/twitter.com\/ExpertsExchange\" target=\"_blank\" rel=\"noopener noreferrer\">@ExpertsExchange<\/a>) is to avoid the use of .ToLower here and instead use IndexOf with the case-insensitive <a href=\"https:\/\/msdn.microsoft.com\/en-us\/library\/system.stringcomparer.ordinalignorecase(v=vs.110).aspx\" target=\"_blank\" rel=\"noopener noreferrer\">OrdinalIgnoreCase<\/a>\u00a0(<a href=\"https:\/\/twitter.com\/msdev\" target=\"_blank\" rel=\"noopener noreferrer\">@msdev<\/a>) property within the request:<\/p>\n<pre class=\"prettyprint\">list = (from sr in dbContext.SERVICE_REQUEST\n\njoin sc in dbContext.SERVICE_CUSTOMER on sr.CUSTOMER_ID equals sc.CUSTOMER_ID)\n\nWhere (sr.SERVICE_REQUEST_NO.IndexOf(objtobeAdvSearch.ServiceRequestNumber, StringComparison.OrdinalIgnoreCase) != -1))\n\n<\/pre>\n<p><a href=\"https:\/\/github.com\/paologutierrez\/.net50\/blob\/master\/tolower-not-working.md\" target=\"_blank\" rel=\"noopener noreferrer\">https:\/\/github.com\/paologutierrez\/.net50\/blob\/master\/tolower-not-working.md<\/a><\/p>\n<h3>47. Be Careful with Optional Parameters<\/h3>\n<p>We can get errors in C# 4.0 when we don\u2019t keep an eye on our use of optional parameters. The following code shows a common misuse:<\/p>\n<pre class=\"prettyprint\">public class Base\n{\n    public virtual void Foo(Int32 x = 1) \n    {}   \n}\n\npublic class Derived\n{\n    public override void Foo(Int32 x = 2)\n    {}\n}\n\n...\n\nBase f0 = new Base();\nf0.Foo();                \/\/ Invokes Foo(1)\n\nBase f1 = new Derived();\nf1.Foo();               \/\/ Also invokes Foo(1)\n\nDerived f2 = new Derived();\nf2.Foo();               \/\/ Invokes Foo(2)\n\n<\/pre>\n<p>Here, the member function takes different arguments for different static types. With this code, we\u2019re violating the principle of least surprise. <a href=\"https:\/\/elegantcode.com\/2008\/11\/09\/be-careful-with-optional-parameters-in-c-40\/\" target=\"_blank\" rel=\"noopener noreferrer\">Avoid<\/a> this construction whenever possible. (<a href=\"https:\/\/twitter.com\/ElegantCode\" target=\"_blank\" rel=\"noopener noreferrer\">@ElegantCode<\/a>)<\/p>\n<p><a href=\"https:\/\/github.com\/paologutierrez\/.net50\/blob\/master\/be-careful-with-optional-parameters.md\" target=\"_blank\" rel=\"noopener noreferrer\">https:\/\/github.com\/paologutierrez\/.net50\/blob\/master\/be-careful-with-optional-parameters.md<\/a><\/p>\n<h3>48. Overloading Methods Defined in Base Classes<\/h3>\n<p>We can cause hard-to-find errors in our C# code when we overload methods defined in base classes. When we do this, we increase the chance of ambiguity and the chance that our interpretation of the spec differs from the compiler\u2019s.<\/p>\n<p>The code below uses overloading improperly.<\/p>\n<pre class=\"prettyprint\">public class B\n{\n    public void Foo2(IEnumerable parm)\n    {\n        Console.WriteLine(\"In B.Foo2\");\n    }\n}\n\npublic class D : B\n{\n    public void Foo2(IEnumerable parm)\n    {\n        Console.WriteLine(\"In D.Foo2\");\n    }\n}\n\nvar sequence = new List { new D2(), new D2() };\nvar obj2 = new D();\n\nobj2.Foo2(sequence);\n\n<\/pre>\n<p>For a deep look at why overloading methods defined in base classes causes trouble, see this <a href=\"http:\/\/www.informit.com\/articles\/article.aspx?p=1570631\" target=\"_blank\" rel=\"noopener noreferrer\">tutorial<\/a>. (<a href=\"https:\/\/twitter.com\/InformIT\" target=\"_blank\" rel=\"noopener noreferrer\">@InformIT<\/a>)<\/p>\n<p><a href=\"https:\/\/github.com\/paologutierrez\/.net50\/blob\/master\/overloading-methods-defined-in-base-class.md\" target=\"_blank\" rel=\"noopener noreferrer\">https:\/\/github.com\/paologutierrez\/.net50\/blob\/master\/overloading-methods-defined-in-base-class.md<\/a><\/p>\n<h3>49. Using \u201c\u201d Instead of String.Empty Instead<\/h3>\n<p>The use of \u201c\u201d when we mean String.Empty can cause a subtle error. The difference between the two is, \u201c\u201d is a constant, while String.Empty isn\u2019t. It\u2019s a read-only field <em>assigned<\/em> to a constant.<\/p>\n<pre class=\"prettyprint\">string s2=\"\";\n\n<\/pre>\n<p>Another reason to use String.Empty instead of quotes is that String.Empty handles memory more efficiently than \u201c\u201d, because it doesn\u2019t create an object. Therefore, operations using \u201cString.Empty happen faster.<\/p>\n<p>See this <a href=\"https:\/\/www.codeproject.com\/Questions\/112466\/Difference-between-String-Empty-and\" target=\"_blank\" rel=\"noopener noreferrer\">discussion<\/a> for more. (<a href=\"https:\/\/twitter.com\/codeproject\" target=\"_blank\" rel=\"noopener noreferrer\">@codeproject<\/a>)<\/p>\n<p><a href=\"https:\/\/github.com\/paologutierrez\/.net50\/blob\/master\/using-quotation-insteadof-string-empty.md\" target=\"_blank\" rel=\"noopener noreferrer\">https:\/\/github.com\/paologutierrez\/.net50\/blob\/master\/using-quotation-insteadof-string-empty.md<\/a><\/p>\n<h3>50. Storing Secrets in Web.config<\/h3>\n<p>This arises\u00a0from a temptation to avoid extra hassle by storing cryptographic secrets in a web.config file. Below is a sample from an ASP.NET 4.6 web config XML file:<\/p>\n<pre class=\"prettyprint\">&lt;appSettings&gt;\n&lt;add key=\"name\" value=\"someValue\" \/&gt;\n&lt;add key=\"name\" value=\"someSECRETValue\" \/&gt;\n&lt;\/appSettings&gt;\n<\/pre>\n<p>We should never store secrets in a web.config file like that. Instead, we need to refer the code to a protected file, like this:<\/p>\n<pre class=\"prettyprint\">&lt;appSettings file=\u201dWeb.SECRETS.config\u201d&gt;\n\n&lt;add key=\u201dname\u201d value=\u201dsomeValue\u201d \/&gt;\n\n&lt;\/appSettings&gt;\n<\/pre>\n<p>For a full breakdown of how this works, see <a href=\"https:\/\/www.hanselman.com\/blog\/BestPracticesForPrivateConfigDataAndConnectionStringsInConfigurationInASPNETAndAzure.aspx\" target=\"_blank\" rel=\"noopener noreferrer\">here<\/a>. (<a href=\"https:\/\/twitter.com\/shanselman\" target=\"_blank\" rel=\"noopener noreferrer\">@shanselman<\/a>)<\/p>\n<p><a href=\"https:\/\/github.com\/paologutierrez\/.net50\/blob\/master\/storing-secrets-in-web-config.md\" target=\"_blank\" rel=\"noopener noreferrer\">https:\/\/github.com\/paologutierrez\/.net50\/blob\/master\/storing-secrets-in-web-config.md<\/a><\/p>\n<h2>Conclusion<\/h2>\n<p>We hope you found this list of 50 .NET software errors helpful. Do you have a better fix for any of the errors and mistakes above? Do you have a software error you think ought to be included in our list? Give us a shout in the comments below.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Developing in .NET provides several powerful benefits, including less overall code, improved security, ease of updates\/changes, and language independence. That said, the system isn\u2019t without errors and problems. From common exceptions to coding mistakes to incorrect assumptions, most of these issues come down to programmer error. The list below shares the 50 top .NET software [&hellip;]<\/p>\n","protected":false},"author":3,"featured_media":38376,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[7],"tags":[27,19,24,26],"class_list":["post-11332","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-developers","tag-net","tag-errors","tag-exceptions","tag-logging"],"acf":[],"yoast_head":"<!-- This site is optimized with the Yoast SEO Premium plugin v25.6 (Yoast SEO v25.6) - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>Common .NET Software Errors and How to Fix Them<\/title>\n<meta name=\"description\" content=\"We&#039;ve aggregated the 50 top .NET software errors. It includes exceptions, broken data bindings, memory leaks, etc. Find solutions on ways to fix each one.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/stackify.com\/top-net-software-errors\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Common .NET Software Errors and How to Fix Them\" \/>\n<meta property=\"og:description\" content=\"We&#039;ve aggregated the 50 top .NET software errors. It includes exceptions, broken data bindings, memory leaks, etc. Find solutions on ways to fix each one.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/stackify.com\/top-net-software-errors\/\" \/>\n<meta property=\"og:site_name\" content=\"Stackify\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/Stackify\/\" \/>\n<meta property=\"article:published_time\" content=\"2017-06-07T21:20:10+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2024-05-24T05:16:04+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/stackify.com\/wp-content\/uploads\/2017\/06\/DotNet-Mistakes-Header-min-881x441-1.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"881\" \/>\n\t<meta property=\"og:image:height\" content=\"441\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\n<meta name=\"author\" content=\"Alexandra Altvater\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@stackify\" \/>\n<meta name=\"twitter:site\" content=\"@stackify\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Alexandra Altvater\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"23 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/stackify.com\/top-net-software-errors\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/stackify.com\/top-net-software-errors\/\"},\"author\":{\"name\":\"Alexandra Altvater\",\"@id\":\"https:\/\/stackify.com\/#\/schema\/person\/3087594560b933be18c662a37d09b51a\"},\"headline\":\"Top .NET Software Errors: 50 Common Mistakes and How to Fix Them\",\"datePublished\":\"2017-06-07T21:20:10+00:00\",\"dateModified\":\"2024-05-24T05:16:04+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/stackify.com\/top-net-software-errors\/\"},\"wordCount\":5434,\"publisher\":{\"@id\":\"https:\/\/stackify.com\/#organization\"},\"image\":{\"@id\":\"https:\/\/stackify.com\/top-net-software-errors\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/stackify.com\/wp-content\/uploads\/2017\/06\/DotNet-Mistakes-Header-min-881x441-1.jpg\",\"keywords\":[\".NET\",\"errors\",\"exceptions\",\"logging\"],\"articleSection\":[\"Developer Tips, Tricks &amp; Resources\"],\"inLanguage\":\"en-US\"},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/stackify.com\/top-net-software-errors\/\",\"url\":\"https:\/\/stackify.com\/top-net-software-errors\/\",\"name\":\"Common .NET Software Errors and How to Fix Them\",\"isPartOf\":{\"@id\":\"https:\/\/stackify.com\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\/\/stackify.com\/top-net-software-errors\/#primaryimage\"},\"image\":{\"@id\":\"https:\/\/stackify.com\/top-net-software-errors\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/stackify.com\/wp-content\/uploads\/2017\/06\/DotNet-Mistakes-Header-min-881x441-1.jpg\",\"datePublished\":\"2017-06-07T21:20:10+00:00\",\"dateModified\":\"2024-05-24T05:16:04+00:00\",\"description\":\"We've aggregated the 50 top .NET software errors. It includes exceptions, broken data bindings, memory leaks, etc. Find solutions on ways to fix each one.\",\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/stackify.com\/top-net-software-errors\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/stackify.com\/top-net-software-errors\/#primaryimage\",\"url\":\"https:\/\/stackify.com\/wp-content\/uploads\/2017\/06\/DotNet-Mistakes-Header-min-881x441-1.jpg\",\"contentUrl\":\"https:\/\/stackify.com\/wp-content\/uploads\/2017\/06\/DotNet-Mistakes-Header-min-881x441-1.jpg\",\"width\":881,\"height\":441},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/stackify.com\/#website\",\"url\":\"https:\/\/stackify.com\/\",\"name\":\"Stackify\",\"description\":\"\",\"publisher\":{\"@id\":\"https:\/\/stackify.com\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/stackify.com\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/stackify.com\/#organization\",\"name\":\"Stackify\",\"url\":\"https:\/\/stackify.com\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/stackify.com\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/stackify.com\/wp-content\/uploads\/2024\/05\/logo-1.png\",\"contentUrl\":\"https:\/\/stackify.com\/wp-content\/uploads\/2024\/05\/logo-1.png\",\"width\":1377,\"height\":430,\"caption\":\"Stackify\"},\"image\":{\"@id\":\"https:\/\/stackify.com\/#\/schema\/logo\/image\/\"},\"sameAs\":[\"https:\/\/www.facebook.com\/Stackify\/\",\"https:\/\/x.com\/stackify\",\"https:\/\/www.instagram.com\/stackify\/\",\"https:\/\/www.linkedin.com\/company\/2596184\",\"https:\/\/www.youtube.com\/stackify\"]},{\"@type\":\"Person\",\"@id\":\"https:\/\/stackify.com\/#\/schema\/person\/3087594560b933be18c662a37d09b51a\",\"name\":\"Alexandra Altvater\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/stackify.com\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/99e0459a6d11f4f510127934dfd98b94?s=96&d=mm&r=g\",\"contentUrl\":\"https:\/\/secure.gravatar.com\/avatar\/99e0459a6d11f4f510127934dfd98b94?s=96&d=mm&r=g\",\"caption\":\"Alexandra Altvater\"}}]}<\/script>\n<!-- \/ Yoast SEO Premium plugin. -->","yoast_head_json":{"title":"Common .NET Software Errors and How to Fix Them","description":"We've aggregated the 50 top .NET software errors. It includes exceptions, broken data bindings, memory leaks, etc. Find solutions on ways to fix each one.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/stackify.com\/top-net-software-errors\/","og_locale":"en_US","og_type":"article","og_title":"Common .NET Software Errors and How to Fix Them","og_description":"We've aggregated the 50 top .NET software errors. It includes exceptions, broken data bindings, memory leaks, etc. Find solutions on ways to fix each one.","og_url":"https:\/\/stackify.com\/top-net-software-errors\/","og_site_name":"Stackify","article_publisher":"https:\/\/www.facebook.com\/Stackify\/","article_published_time":"2017-06-07T21:20:10+00:00","article_modified_time":"2024-05-24T05:16:04+00:00","og_image":[{"width":881,"height":441,"url":"https:\/\/stackify.com\/wp-content\/uploads\/2017\/06\/DotNet-Mistakes-Header-min-881x441-1.jpg","type":"image\/jpeg"}],"author":"Alexandra Altvater","twitter_card":"summary_large_image","twitter_creator":"@stackify","twitter_site":"@stackify","twitter_misc":{"Written by":"Alexandra Altvater","Est. reading time":"23 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/stackify.com\/top-net-software-errors\/#article","isPartOf":{"@id":"https:\/\/stackify.com\/top-net-software-errors\/"},"author":{"name":"Alexandra Altvater","@id":"https:\/\/stackify.com\/#\/schema\/person\/3087594560b933be18c662a37d09b51a"},"headline":"Top .NET Software Errors: 50 Common Mistakes and How to Fix Them","datePublished":"2017-06-07T21:20:10+00:00","dateModified":"2024-05-24T05:16:04+00:00","mainEntityOfPage":{"@id":"https:\/\/stackify.com\/top-net-software-errors\/"},"wordCount":5434,"publisher":{"@id":"https:\/\/stackify.com\/#organization"},"image":{"@id":"https:\/\/stackify.com\/top-net-software-errors\/#primaryimage"},"thumbnailUrl":"https:\/\/stackify.com\/wp-content\/uploads\/2017\/06\/DotNet-Mistakes-Header-min-881x441-1.jpg","keywords":[".NET","errors","exceptions","logging"],"articleSection":["Developer Tips, Tricks &amp; Resources"],"inLanguage":"en-US"},{"@type":"WebPage","@id":"https:\/\/stackify.com\/top-net-software-errors\/","url":"https:\/\/stackify.com\/top-net-software-errors\/","name":"Common .NET Software Errors and How to Fix Them","isPartOf":{"@id":"https:\/\/stackify.com\/#website"},"primaryImageOfPage":{"@id":"https:\/\/stackify.com\/top-net-software-errors\/#primaryimage"},"image":{"@id":"https:\/\/stackify.com\/top-net-software-errors\/#primaryimage"},"thumbnailUrl":"https:\/\/stackify.com\/wp-content\/uploads\/2017\/06\/DotNet-Mistakes-Header-min-881x441-1.jpg","datePublished":"2017-06-07T21:20:10+00:00","dateModified":"2024-05-24T05:16:04+00:00","description":"We've aggregated the 50 top .NET software errors. It includes exceptions, broken data bindings, memory leaks, etc. Find solutions on ways to fix each one.","inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/stackify.com\/top-net-software-errors\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/stackify.com\/top-net-software-errors\/#primaryimage","url":"https:\/\/stackify.com\/wp-content\/uploads\/2017\/06\/DotNet-Mistakes-Header-min-881x441-1.jpg","contentUrl":"https:\/\/stackify.com\/wp-content\/uploads\/2017\/06\/DotNet-Mistakes-Header-min-881x441-1.jpg","width":881,"height":441},{"@type":"WebSite","@id":"https:\/\/stackify.com\/#website","url":"https:\/\/stackify.com\/","name":"Stackify","description":"","publisher":{"@id":"https:\/\/stackify.com\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/stackify.com\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/stackify.com\/#organization","name":"Stackify","url":"https:\/\/stackify.com\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/stackify.com\/#\/schema\/logo\/image\/","url":"https:\/\/stackify.com\/wp-content\/uploads\/2024\/05\/logo-1.png","contentUrl":"https:\/\/stackify.com\/wp-content\/uploads\/2024\/05\/logo-1.png","width":1377,"height":430,"caption":"Stackify"},"image":{"@id":"https:\/\/stackify.com\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/Stackify\/","https:\/\/x.com\/stackify","https:\/\/www.instagram.com\/stackify\/","https:\/\/www.linkedin.com\/company\/2596184","https:\/\/www.youtube.com\/stackify"]},{"@type":"Person","@id":"https:\/\/stackify.com\/#\/schema\/person\/3087594560b933be18c662a37d09b51a","name":"Alexandra Altvater","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/stackify.com\/#\/schema\/person\/image\/","url":"https:\/\/secure.gravatar.com\/avatar\/99e0459a6d11f4f510127934dfd98b94?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/99e0459a6d11f4f510127934dfd98b94?s=96&d=mm&r=g","caption":"Alexandra Altvater"}}]}},"_links":{"self":[{"href":"https:\/\/stackify.com\/wp-json\/wp\/v2\/posts\/11332"}],"collection":[{"href":"https:\/\/stackify.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/stackify.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/stackify.com\/wp-json\/wp\/v2\/users\/3"}],"replies":[{"embeddable":true,"href":"https:\/\/stackify.com\/wp-json\/wp\/v2\/comments?post=11332"}],"version-history":[{"count":0,"href":"https:\/\/stackify.com\/wp-json\/wp\/v2\/posts\/11332\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/stackify.com\/wp-json\/wp\/v2\/media\/38376"}],"wp:attachment":[{"href":"https:\/\/stackify.com\/wp-json\/wp\/v2\/media?parent=11332"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/stackify.com\/wp-json\/wp\/v2\/categories?post=11332"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/stackify.com\/wp-json\/wp\/v2\/tags?post=11332"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}