2012 error message .aspx

2012 error message .aspx

Net code to trap and respond to errors when they occur in ASP.Net or rather I would say in our web application. Think this error will appear if you install the iis after you have installed.net. #64086. Dec 10, 2012 16:50. Many solutions on the internet suggest to create a base controller class and implement the method in one location for a generic error handler.

Similar video

ASP.NET - Validation Controls

Server Error in '/' Application.

Hi there,

Just installed EPiServer 7 - a fresh install on my Windows 2012 error message .aspx box (64bit), 2012 error message .aspx.  The installation proceeded without any errors.  I then created a new EPiServer 7 website, choosing to install the Alloy ricoh error code sc 672 as well.  

The website is created without any errors reported, but as soon as I try and access it I get the following:


The resource cannot be found.

Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable.  Please review the following URL and make sure that it is spelled correctly. 

Requested URL: /.aspx


Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.17929

 

No other configuration changes made.  I am thinking that either there is an assumed system configuration setting which my PC does not have, or the automatic installation routine has a bug in it somewhere.

I would appreciate any advice!

Many thanks,

Wayne

#63819

So you just moved your application to an IIS7 server, and now you are getting an error when you make a request to it.  This seems to be a popular theme on IIS.NET forums these days, 2012 error message .aspx, and after answering a hundred or so of these posts, I figured I should do something to help people track down and fix their issues with a little less frustration. 

Dealing with 500, 503 IIS errors? These are likely hiding bigger application issues that are hurting your application.   

It can be very hard to link generic IIS errors to underlying issues that you can fix. Head over to LeanSentry to get a comprehensive application checkup. We’ll find your actual IIS and ASP.NET issues, and even show you how to fix them in code.

Server software, and web servers specifically, 2012 error message .aspx, are very complex and highly configurable systems that support multi-tier applications using a variety of technologies and subsystems, and endure further complexity due to security, performance, and reliability demands, so it’s a wonder it all works as well as it does in the end.  IIS7 strives to improve the experience of diagnosing and solving problems when they do occur, so knowing how to use the new IIS7 diagnostics features can come a long way in helping you become a pro at troubleshooting server problems.

First things first – what’s the problem?

I often find myself asking this question on the forums when someone posts something like “Help, I moved to IIS7 and now my application doesn’t work!”.  Huh, what doesnt work? When your site stops working, the first thing you need to do is determine what the error actually is before we can move any further.  IIS7 has much better error messages that will often tell you exactly what the problem is, and help you fix it.

Unfortunately, sometimes getting to this error is the main challenge.  Let’s look at a few things you may need to do to get there:

1) Disable IE “Friendly HTTP error messages”
IE will by default replace the actual error messages coming from the server with a “friendly” error message, which hides the error contents we need to see.  For example, 2012 error message .aspx, for a 404 Not Found error, you may instead see the following:

IE Friendly Error

 To disable this and see the real error coming from the server, you need to go to “Tools > Internet Options”, choose the Advanced tab, and clear the “Show friendly HTTP error messages” checkbox.  Then, close the browser, open it again, and re-request the page.

Disable IE friendly HTTP error messages

Now, suppose you are still seeing the generic “cannot display the webpage” or “page not found” error.   This is typically caused by IE failing to connect to your website, so there is no server error message to look at here.  I have a detailed guide to troubleshooting this condition here: Where did my IIS7 server go? Troubleshooting “server not found” errors.

An aside: 2012 error message .aspx you don’t want to mess with IE for troubleshooting (especially if you suspect you are getting cached pages, due to IE’s super- aggressive caching), the best thing to do is server error incorrect out a trusty simple http tool of choice and make the request with it.  I recommend WFETCH, which is included in the IIS6 Resource Kit tools (you can install on XP/Windows 2003 only, and can either run it from there or copy wfetch.exe to your Vista/LHS box).

2) Enable IIS7 detailed errors
IIS7 introduces a new custom errors feature, which by default hides the error responses issued by the server to remote clients, replacing them with a basic error message.  This is critical for security of your site, as errors frequently contain sensitive information that you don’t want others to see, but makes getting to the bottom of the problem harder since you cannot see those very error details. So, if you are requesting your site from another machine, 2012 error message .aspx, you may still get a basic error that looks like this:

IIS7 custom error page

You have two options here:

1) Make the request locally from the server machine

By default, you will get the detailed error.

2) Enable detailed errors for remote clients.  
First, if your error is an ASP.NET exception (you can 2012 error message .aspx if it says “Runtime Error” and has the framework version), please be aware that ASP.NET overrides the IIS custom error mechanism with its own implementation of custom errors, so you should turn the ASP.NET custom errors off to see detailed ASP.NET exceptions.  You DO NOT have to configure IIS7 custom errors for ASP.NET exceptions (it would be silly to have to do it in two places).  To turn off ASP.NET custom errors, place the following in your web.config:

<system.web>
   <customErrors mode=”Off” />
</system.web>

If the error is not an ASP.NET error, 2012 error message .aspx, turning off IIS7 custom errors will allow error responses from your application to be sent to remote clients without being censored by the IIS7’s custom errors module.

You can do this from the IIS7 Admin tool by running “Start>Run>inetmgr.exe”, selecting your website/application/virtual directory in the left-hand tree view, clicking on the “Error Pages” icon, clicking “Edit Feature Settings” action, and then selecting “Detailed Errors”.

Enable IIS7 Detailed Errors

You can alternatively do this from an elevated command line prompt (Run as Administrator):

> %windir%system32inetsrvappcmd.exe set config “Default Web Site/yourapp” /section:httpErrors /errorMode:Detailed

Where “Default Web Site” should be replaced with your site’s name if different, and “/yourapp” with the virtual path you’d like to enable detailed errors for.

NOTE: When you are done debugging, please return the settings back 2012 error message .aspx custom errors for remote requests, or the security of your website may be compromised.  Here is how to do it with AppCmd:

> %windir%system32inetsrvappcmd.exe set config “Default Web Site/yourapp” /section:httpErrors /errorMode:DetailedLocalOnly
 
Now, you should be getting detailed errors back – for example, the error I was getting before now looks like this (this is the Vista error page – Longhorn Server and 2012 error message .aspx SP1 error pages will look much nicer, see this for an example):

IIS7 Detailed Error Page

Notice that this error contains quite a bit of useful information:
1) The heading contains the substatus code, 404.0, which is an IIS specific code that further describes the problem.  The majority of common errors has a unique <status_code>.<substatus_code> combination that you can easily google for additional information.
2) The page indicates what module (IIS Web Core), and in what notification (MapRequestHandler) an error occurred.  This information is critical whenever you are debugging server problems, especially on the IIS7+ world when most of them occur in one of the modules that take part in the processing of the request.
3) The page shows you some 2012 error message .aspx request information, such as the requested url and the physical path to which it resolved.  Most 404 errors will be resolved right here, by seeing that the request is being made to a wrong url or resolving to a wrong physical path due to incorrect virtual directory mapping.
4) The “most likely causes” and “what you can try” sections offer the most likely explanation for the error and what you can do about it.  They are dead on for the majority of common IIS7 errors.

NOTE: When you are coming to the forums with an error, we expect you to have gotten this far and that you will provide the detailed error to help us with your problem.  For more information about the custom errors support in IIS7, check out http://www.iis.net/articles/view.aspx/IIS7/Managing-IIS7/Diagnostics-in-IIS7/Deciphering-Error-Messages/How-to-Use-HTTP-Detailed-Errors-in-IIS7.

3) Detour – the 503 “Service Unavailable” error
Sometimes, you will get an error that looks like this:

503 Service Unavailable

This error most likely either indicates a critical misconfiguration of the server that is causing IIS to fail to start a worker process/process your request, or a system overload condition that is causing requests to be rejected early, so no further error information will be available in the response.  If you are getting this error, please follow my detailed guide: Where did my IIS7 server go? Troubleshooting “service unavailable” errors.

Deeper diagnostics with Failed Request Tracing (formerly known as FREB)

If the error alone is not sufficient to 2012 error message .aspx the condition, 2012 error message .aspx, or more information is needed to determine what lead up to the error occurring, or, there is no error (for example, request times out), you can take advantage of the wonderful IIS7 feature called “Failed Request Tracing”.

This feature can be used to generate a detailed trace of events leading up to the failure, much like ETW, but now with more/more useful events and significantly easier to turn on and use for troubleshooting.

More importantly, you can configure Failed Request Tracing to only trace requests that encounter a specific failure condition, such as a specific response status/substatus codes, an event of specific verbosity, or a timeout.

To do this, you are going to need to install it first (if you haven’t already):
On Vista: Control Panel, Programs, 2012 error message .aspx, Turn Windows Features on or off, check Internet Information ServicesWorld Wide Web ServicesHealth and DiagnosticsTracing.
On Windows Server 2008: Start>Run>Server Manager, Roles, Web Server(IIS),  Add Role Services, check Web ServerHealth and DiagnosticsTracing

Then, to enable IIS to generate these logs, vray vrender2009. dlr error need 2012 error message .aspx do two things:
1) Enable Failed Request Tracing for the site you want to trace

In InetMgr, select your site in the left-hand tree view, then under Actions on the right click “Failed Request Tracing …”.  There, select the Enable box.

Enable Failed Request Tracing for a site

2) Create a Failed Request Tracing rule with the events and failure definition of choice

In InetMgr, select the site/application/virtual directory that you’d like to trace in the tree view, click the “Failed Request Tracing Rules” icon, click the “Add…” action, 2012 error message .aspx, and follow 2012 error message .aspx wizard to create the rule.

You will be asked what content you’d like to trace (based on an extension), when to consider the request as failed (a list of response status codes, and in Longhorn Server, also event verbosity) or a timeout, and finally the events you’d like 49, 460e service error hp trace.  I recommend to leave all events selected by default, unless you are sure you know what you are looking for.

Create a Failed Request Tracing rule

Now, when you make a request, if it meets the failure definition, the detailed trace will be logged as an XML file that you can inspect (or send to us for inspection). 

You can by default find this file in %systemdrive%inetpublogsFailedReqLogFilesW3SVC<ID> folder. 

If you double-click this file, it will open with the provided XSL stylesheet that shows the trace events.  In Longhorn Server, this stylesheet has gotten a major overhaul to highlight the important information better – for more information, see this: http://blogs.iis.net/bills/archive/2006/10/19/Making-Failed-Request-Tracing-More-Approachable.aspx.  You can download the new stylesheet and use it today for your Vista machine.

The Failed Request Tracing log provides verbose execution information for the request, that can be used in a number of ways to further diagnose more complex problems that may result from the operation of 2012 error message .aspx than one module.  For example, 2012 error message .aspx, if a url rewriter module changes a url in the request, which later leads to the static file handler failing to find the file, the SetUrl event can provide the needed information.  The log also provides such key info as the times taken by each module to execute, the outcome of each of the built-in module’s operation (often including the reason why something didn’t work), and any times when a module fails a request by setting an error response status code.

Finally, one of the main strengths of Failed Request Tracing is that you do not have to be the client to receive the error information.  As an administrator, you can windows xp install stop error 7b it to monitor for errors and log the forensic trace when they occur, allowing you to just leave the feature on in production.  Think of it as request logs on steroids.  To learn more about Failed Request Tracing, see http://www.iis.net/articles/view.aspx/IIS7/Managing-IIS7/Diagnostics-in-IIS7/Using-Failed-Request-Tracing/Troubleshooting-Failed-Requests-using-Tracing-in-I.

I will post more specific strategies on how to troubleshoot with Failed Request Tracing logs in a future post.  In the meantime, you should now be a lot more prepared to deal with errors when they occur, and resolve them before you type that first forum post.  And if you do make a post (which you 2012 error message .aspx welcome to do), you’ll be able to provide us with the key information to help you solve your problem.

Thanks,

Mike

 

How to fix ASP.NET 3.5 websites not running on Windows Server 2012

ASP.NET 3.5 websites not running on a newly setup Windows Server 2008

I had an issue the other day where a new Windows Server 2012 installation was not running my older ASP.NET 3.5 web sites. Everytime I would try to navigate to a .net 3.5 website I would see a '404: page not found' error message.

If I manually typed in a path containing a '.html' file this would load without any issues for me but '.aspx' files would not load. I noticed that the Mapping Handler was missing settings for older asp.net code - everything was asp.net 4.0. This explained why .html files were ok but .aspx files were returning a 404. The server just didn't know what to do with .aspx files for older .net sites.

I opened the Add Roles and Features Wizard (go to Control Panel, 2012 error message .aspx, Turn Windows features on or off) and drilled into the IIS web server to ensure that asp.net 3.5 was installed but noticed that only ASP.NET 4.0 was installed on the server. To fix this I simply had to tick the checkbox for .Net Extensibility 3.5 and ASP.NET 3.5. You can find these checkboxes by drilling into the following tree menu:

  • Web Server (IIS) (installed)
    • Web Server (Installed)
      • Application Development (Installed)
        • .Net Extensibility 3.5
        • ASP.NET 3.5

If you get asked about restarting the server you can leave that checkbox unchecked as this install won't require a server reboot. Remember to restart IIS or recycle the app pool and website before you try and browse to your .net 3.5 website for the new settings to take effect.

.Net, IIS, Windows Server

Developing in .NET provides several powerful benefits, including less overall code, 2012 error message .aspx, improved security, ease of updates/changes, and language independence.

That said, the system isn’t 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 errors from around the web. It includes exceptions, broken data bindings, memory leaks, LINQ issues, mistyping errors, and dozens more. We also look at ways to fix each one.

When you’re ready to start coding, download our free guide to .NET Profilers for some insider knowledge and everything you need to know about code profiling for .NET. And while you’re at it, be sure to check out Prefix, our own lightweight profiler for .NET and Java developers. (And, if you’re thinking about .NET Core, read our opinion on why it’s the next big thing here.)


Try this before your <b>2012 error message .aspx</b> .NET push

1. NullReferenceException

This .NET exception gets thrown whenever we try to use a class reference that’s set to null/Nothing, when the code expects otherwise. In the very simple example below, the string “foo” is set to null.

string foo = null; foo.ToUpper();

The second line above will throw a NullReferenceException because we can’t call the method on a string that points to null.

To fix/avoid this error:

2. DivideByZeroException

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’s an example:

try { int x = SomeService.Calculate(); int y = 10 / x; } catch (DivideByZeroException ex) { //TODO: Write code that should run when x is 0 }

Ways to fix/prevent DivideByZeroException:

  • Use Try/Catch blocks to catch the exception.
  • Set guards on functions that throw errors in the event of a zero value.
  • Use validation on critical user inputs to prevent zero values.
  • For more detail on how to handle this .NET error, see this article from Dot Net Perls.

3. Broken Data Bindings in WPF

Data bindings in WPF can be a huge time saver – when they work well. When they break, they’re one of the more frustrating .NET errors out there. In the example below, there’s a TextBlock with a missing data context. Frustratingly, it won’t show errors in Visual Studio’s output window.

<Window x:Class="WpfApplication1.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525"> <Grid> <TextBlock Text="{Binding ThereIsNoDataContext}"/> </Grid> </Window> We can fix this by enabling tracing to the output window to reveal any problems: <Window x:Class="WpfApplication1.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:diag="clr-namespace:System.Diagnostics;assembly=WindowsBase" Title="MainWindow" Height="350" Width="525"> <Grid> <TextBlock Text="{Binding ThereIsNoDataContext, diag:PresentationTraceSources.TraceLevel=High}" /> </Grid> </Window>

Here are a couple of other fixes for the broken data bindings error:

  • Add a Value Converter that Breaks into the Debugger.
  • Add a TraceListener so you know right away when a data binding breaks.
  • There’s a great tutorial that gives more detail on fixing this issue here. (@atomicobject)

https://github.com/paologutierrez/.net50/blob/master/brokendatabindingswpf.md

4. Using a Reference Like a Value or Vice Versa

This problem is specific to C#. In C#, the programmer who writes 2012 error message .aspx 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.

Point point1 = new Point(20, 30); Point point2 = point1; point2.X = 50; Console.WriteLine(point1.X); // 20 (does this surprise you?) Console.WriteLine(point2.X); // 50 Pen pen1 = new Pen(Color.Black); Pen pen2 = pen1; pen2.Color = Color.Blue; Console.WriteLine(pen1.Color); // Blue (or does this surprise you?) Console.WriteLine(pen2.Color); // Blue

To fix the problem, look at definitions of the object types. In Visual Studio, do this by putting your cursor over the object’s name and pressing F12.

For a more in-depth explanation of the reference/value error, see this tutorial.

https://github.com/paologutierrez/.net50/blob/master/using-reference-like-value-vice-versa.md

5. Letting Compiler Warnings Accumulate

This very common issue erodes the strict type checking provided by the C# compiler. The temptation to hide warnings in Visual Studio’s “Error List” window can lead to a buildup of hidden or ignored warnings. Unheeded warnings can cause 2012 error message .aspx code problems like this:

class Account { int myId; int Id; // compiler warned you about this, 2012 error message .aspx, 2012 error message .aspx you didn’t listen! // Constructor Account(int id) { this.myId = Id; // OOPS! } }

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 this article for more.

https://github.com/paologutierrez/.net50/blob/master/allowing-compiler-warnings-accumulate.md

6, 2012 error message .aspx. Losing Scope Before Disposing an Object

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’s finalizer, but that isn’t always the case.

To fix this error, make sure all .NET objects are explicitly disposed.

  • Use the using statement to wrap all IDisposable objects. Objects wrapped in this way will automatically be disposed when the using block closes.
  • In some cases, the using statement isn’t enough. (@msdev) One example is when nesting constructors are protected by only one 2012 error message .aspx handler.
  • For additional protection, add specific code to check and dispose variables when needed, 2012 error message .aspx. The finally block below does this with the tempPort variable.
public SerialPort OpenPort1(string portName) { SerialPort port = new SerialPort(portName); port.Open(); //CA2000 2012 error message .aspx because this might throw SomeMethod(); //Other method operations can fail return port; } public SerialPort OpenPort2(string portName) { SerialPort tempPort = null; SerialPort port = null; try { tempPort = new SerialPort(portName); tempPort.Open(); SomeMethod(); //Add any other methods above this line port = tempPort; tempPort = null; } finally { if (tempPort != null) { tempPort.Close(); } } return port; }

7. Redundant Nested Exception Handling

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:

public class NestedExceptionHandling { public void MainMethod() { try { //some implementation ChildMethod1(); 2012 error message .aspx } catch (Exception exception) { //Handle exception } } private void ChildMethod1() { try { //some implementation ChildMethod2(); } catch (Exception exception) { //Handle exception throw; } 2012 error message .aspx } private void ChildMethod2() { try { //some implementation } catch (Exception exception) { //Handle exception throw; } 2012 error message .aspx } }

For a deeper look at this mistake, see this article. (@Codeguru)

https://github.com/paologutierrez/.net50/blob/master/nested-exception-handling.mdown

8, 2012 error message .aspx. Deferred Execution in LINQ

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:

public IEnumerable GetCustomers() { using(var context = new DBContext()) { return from c in context.Customers where c.Balance > 2000 select c; } }

The code seems fine until we try to enumerate the collection. At that point, we’ll get an “ObjectDisposedException.” That’s because link won’t actually perform the query until we attempt to enumerate the results.

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 here. (@VSMdev)

https://github.com/paologutierrez/.net50/blob/master/deferred-execution-in-linq.md

9. Iterating with Values Instead of with LINQ

Here’s another “not quite a .NET error” that’s 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.

foreach (Customer customer in CustomerList) { if (customer.State == "FL") { tax += customer.Balance; } }

The code above returns 1,000 customers. That’s much more efficient than getting 100,000 customers with a foreach loop. For more, see this post. (@Upwork)

https://github.com/paologutierrez/.net50/blob/master/iterating-through-values-instead-of-using-linq.md

10. Accessing Virtual Members within a Constructor

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.

In the example below, the virtual method 2012 error message .aspx is made on a class before the class’ constructor has been run.

public class Parent { public Parent() { Console.WriteLine("Parent Ctor"); Method(); } public virtual void Method() { Console.WriteLine("Parent method"); } } public class Child : Parent { public Child() { Console.WriteLine("Child Ctor"); } public override void Method() { Console.WriteLine("Child method"); } }

To fix the problem, first mark your class as sealed. This ensures that it’s the most derived type within the inheritance hierarchy. That way, when we call the virtual method, we don’t get a warning.

https://github.com/paologutierrez/.net50/blob/master/accessing-virtual-member-in-a-constructor.md

11. Logic Errors

Logic errors happen when we don’t get the result we expected. They don’t always result in error messages because they’re not technically “bugs.” Instead, they’re problems with programming logic. Take a look at the code 2012 error message .aspx. It tries to add up the numbers from one to ten.

private void button1_Click(object, sender, EventArgs e) { int startLoop = 11; int endLoop = 1; int answer = 0; for (int i = startLoop; i < endLoop; i++) { answer = answer + i; } MessageBox.Show("answer =" + answer.ToString()); }

Can you see the error? The answer is zero! The program didn’t run into any code errors, but it gave us the wrong answer. That’s a logic error. We should have set the startLoop variable as 1, and endLoop as 11. To nip logic errors in the bud:

  • Use C# .NET Breakpoints. This is where we tell C# to stop the code, so we can assess what’s in the variables.
  • Use the C# .NET Locals Window. This keeps track of what’s in local variables.
  • Use Try … Catch blocks.
  • For a full tutorial on how to implement the above fixes, click here.

https://github.com/paologutierrez/.net50/blob/master/logic-error.md

12. Mixing Strings and Numbers with +

Most languages use the + sign for both concatenation and arithmetic addition, 2012 error message .aspx. That means 2 + 2 is 4 and “hello ” + “world” is “hello world.” But what about “hello “ + 2? This would result in “hello 2”. This would be better expressed as “hello ” + “2”.

Here’s a less obvious example:

static void Main(string[] args) { int x = 4; string y = "12"; Console.WriteLine(string.Format("{0}", x + y)); // 412 Console.ReadKey(); }

In this case, x + y is 412, where 4 is a number and “12” is a string.

To head this mistake off:

  • Make sure all values you intend to add are actually numbers.
  • Use string.Format() instead of concatenating with +.
  • Perform arithmetic as distinct statements before outputting concatenated results or strings.
  • For an in-depth tutorial, click here. (@DreamInCode)

https://github.com/paologutierrez/.net50/blob/master/concatenating-rather-than-adding.md

13. Forgetting Strings Are Immutable

Strings are immutable in .NET. That means once we create a string, we can’t change its value. It may look like we’re changing a string’s value, but what we’re really doing is creating a new object with a new value.

The example below shows how forgetting that strings are immutable can lead us into a problem. (@amazedsaint)

string = "Take this out"; s.Replace("this", "that"); //wrong s = s.Replace("this", "that"); //correct

There’s another great example of an 2012 error message .aspx string error here that results in the creation of 10,000 unwanted string variables. (@codeproject) The article presents an elegant solution: using the StringBuilder class to change the text without making thousands of new String class instances.

https://github.com/paologutierrez/.net50/blob/master/forgetting-that-strings-are-immutable.md

14. Incorrect Granularity

Here’s a common C# error that results from a multithreading mistake. This happens when we use lock with poor code synchronization.

The example below checks for curse words in a string, printing a warning if it finds one. 2012 error message .aspx also performs several other operations. The code isn’t synchronized, however, 2012 error message .aspx it’s not thread safe. For instance, two threads might try to update the same counter at the same time, causing an exception.

private static List wordList; private static List curseWords; private static int currentWordIndex; private static Dictionary<string, int> wordCountDict; public static void CalculateWordCounts() { wordList = GetWordList(); curseWords = GetCurseWords(); currentWordIndex = 0; wordCountDict = new Dictionary<string, int>(); Thread threadA = new Thread(ThreadDoWork); Thread threadB = new Thread(ThreadDoWork); Thread threadC = new Thread(ThreadDoWork); Thread threadD = new Thread(ThreadDoWork); threadA.Start(); threadB.Start(); threadC.Start(); threadD.Start(); threadA.Join(); threadB.Join(); threadC.Join(); threadD.Join(); } private static void ThreadDoWork() { bool atLeastOneWordRemaining; int thisWordIndex = currentWordIndex; currentWordIndex = currentWordIndex + 1; if (thisWordIndex >= wordList.Count) atLeastOneWordRemaining = false; else atLeastOneWordRemaining = true; while (atLeastOneWordRemaining) { string thisWord = wordList[thisWordIndex]; bool firstOccurrenceOfWord = !wordCountDict.ContainsKey(thisWord); if (curseWords.Contains(thisWord)) Console.WriteLine("Curse word detected!"); if (firstOccurrenceOfWord) wordCountDict.Add(thisWord, 1); else wordCountDict[thisWord] = wordCountDict[thisWord] + 1; thisWordIndex = currentWordIndex; currentWordIndex = currentWordIndex + 1; if (thisWordIndex >= wordList.Count) atLeastOneWordRemaining = false; } }

To repair this:

  • Make sure only one thread can read/update a counter at a time.
  • Lock over checking/updating routines.
  • For a full tutorial on the incorrect granularity error, click here. (@Xenoprimate)

https://github.com/paologutierrez/.net50/blob/master/incorrect-granularity.md

15. Unhandled Exogenous Exceptions

This may sound like the lost Dali painting, but it’s just a fancy way of saying, “unhandled, handleable exceptions.” Since the definition of exogenous is “originating externally,” these exceptions are beyond our control and must be anticipated and handled.

The code below shows a good example.

try { using ( File f = OpenFile(filename, ForReading) ) { // Blah blah blah } } catch (FileNotFoundException) { // Handle file not found }

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.

See this tutorial for a good explanation of the different kinds of exceptions, plus whether and how to handle them. (@ericlippert)

https://github.com/paologutierrez/.net50/blob/master/failure-to-handle-exogenous-exceptions.md

16. Protection Level Conflicts

For any class, 2012 error message .aspx, the default protection level is “internal.” For any member in that class, the default level is “private.” We can run into an issue when we forget those facts.

class MyFirstClass //default protection = internal { public void NameFunction() { MySecondClass sc = new MySecondClass(); sc.strFirstName = "Harry"; sc.strLastName = "Potter"; Console.WriteLine("Name: " + sc.FirstName + " " + sc.strLastName); } } public class MySecondClass { string strFirstName = "Roy"; string strLastName = "Weasley"; //default protection = private }

When we declare “MySecondClass” public, its variables don’t also become public, 2012 error message .aspx. If we want MyFirstClass to be able to access the variables in MySecondClass, 2012 error message .aspx, we’ll need to set MyFirstClass and the MySecondClass variables to “public.” See this post for more details. (@DeveloperDrive)

https://github.com/paologutierrez/.net50/blob/master/protection-level-conflicts.md

17, 2012 error message .aspx. StackOverflowException

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’ll get an overflow exception.

The 2012 error message .aspx C# example below shows an infinite recursion that will trigger a StackOverflowException.

class Program { private static int hitCount; static void Main(string[] args) { hitCount = 0; MyRecursiveExample(null); } static void MyRecursiveExample(string value) { hitCount++; if (value == null) adobe premiere cs3 error compiling movie { MyRecursiveExample(value); } else { System.Console.WriteLine(value); } } }

To avoid the StackOverflowException error, try not to have objects mutually reference each other whenever possible. See this discussion and this article for more insight. (@StackOverflow and @ExpertsExchange)

https://github.com/paologutierrez/.net50/blob/master/stack-overflow-exception.md

18. Busy-Wait and Thread.Sleep

Using busy-wait instead of correct thread synchronization can deliver a troublesome error, 2012 error message .aspx. The code below will suck up 100% of the CPU core while the thread in Example() processes the while loop.

private static string userInput; private static void Example() { userInput = null; GetUserInput(); // tells the UI to request user input on the UI thread while (userInput == null) ; // wait for user input ProcessUserInput(userInput); // now use that input }

Some developers will try to use something like Thread.Sleep(100) to interrupt an infinite loop. While this works, it’s sloppy coding, since what we really need is an in-built synchronization construct. In general, we should only use Thread.Sleep:

  • To make some kind of timer functionality
  • For testing, but not for production
  • For a more in-depth look at 2012 error message .aspx to dodge the busy-wait and thread.sleep error, click here. (@Xenoprimate)

https://github.com/paologutierrez/.net50/blob/master/busy-waiting-and-thread-sleep.md

19. Handling Non-Exogenous Exceptions

Certain .NET errors in the form of exceptions that can’t be foreseen and that originate from outside our control must be handled. For example, let’s 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, 2012 error message .aspx. Consider the following three exceptions:

string val = null; int value = int.Parse(str); //Will throw ArgumentNullException string val = "100.11"; int value = int.Parse(val); //Will throw FormatException string val = "999999999999999999999999999999999999999999"; int value = int.Parse(val); //Will throw OverflowException››

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.

https://github.com/paologutierrez/.net50/blob/master/avoiding-exceptions-instead-of-working-with-them.mdown

20. Unsafe Assumptions in Multithreading

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.

One example is a torn read from non-atomic access to a variable. The following code will return unwanted values:

private const int NUM_ITERATIONS = 20000; private const decimal DENOMINATOR = 200m; private const decimal MAX_POSSIBLE_VALUE = NUM_ITERATIONS / DENOMINATOR; private static decimal sharedState; public static decimal SharedState { get { return sharedState; 2012 error message .aspx set { sharedState = value; } } static void Main(string[] args) { Thread writerThread = new Thread(WriterThreadEntry); Thread readerThread = new Thread(ReaderThreadEntry); writerThread.Start(); readerThread.Start(); writerThread.Join(); readerThread.Join(); Console.ReadKey(); } private static void WriterThreadEntry() { for (int i = 0; i < NUM_ITERATIONS; ++i) { SharedState = i / DENOMINATOR; } } private static void ReaderThreadEntry() { for (int i = 0; i < NUM_ITERATIONS; ++i) { var sharedStateLocal = SharedState; if (sharedStateLocal > MAX_POSSIBLE_VALUE) Console.WriteLine("Impossible value detected: " + sharedStateLocal); } }

The problem occurs because one thread can read the value of sharedState halfway through a write by another thread. This forces the variable into values we hadn’t anticipated (or wanted).

To fix the problem, make access to the variable atomic. To do this:

  • Use the lock statement
  • Use the Interlocked

For a detailed breakdown of incorrect multithreading assumptions in .NET and how to fix them, see this in-depth tutorial. (@Xenoprimate)

https://github.com/paologutierrez/.net50/blob/master/unsafe-assumptions-on-multithreading.md

21. The Nullable Paradox

A nullable value passed to the stack will create garbage. Paradoxically, a similar variable that’s actually set to null won’t create any garbage.

private static void DoTestA() { int? maybeInt = null; for (int i = 0; i < 100000; ++i) { DoSomething(maybeInt); } } private static void DoTestB() { int? maybeInt = 3; for (int i = 0; i < 100000; ++i) { DoSomething(maybeInt); } } private static void DoSomething(object o) { // Do something. }

In the example above, DoTestA() creates zero garbage, 806 vpn error vista DoTestB() quickly racks up a large amount.

The best way to fix this is to generify our DoSomething method:

Private static void DoSomething<T>(T o) { // Do something. }

For a more detailed explanation of this paradox and how to fix it, see this post. (@Xenoprimate)

https://github.com/paologutierrez/.net50/blob/master/nullable-paradox.md

22. Failure to Log Exceptions

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. 2012 error message .aspx this case, if registration fails, 2012 error message .aspx, our log stays empty.

public class UserService { private readonly IMessagingService _messagingService; public UserService(IMessagingService messagingService) { _messagingService = messagingService; } public bool RegisterUser(string login, string emailAddress, string password) { // insert user to the database // generate an activation code to send via email // save activation code to the database // create an email message object try { _messagingService.SendRegistrationEmailMessage(message); } catch (Exception) { // boom! } return true; } }

Of course, the fix for this error is to add logging to the try-catch block. To see the full tutorial, click here. (@codeproject)

https://github.com/paologutierrez/.net50/blob/master/eating-exceptions.md

23. Unnecessary Contention in Multithreading

Contention happens when two or more threads try to access the same resource at the same time. They contend for the resource. This situation causes several issues.

Even when we use thread-safe coding, contention can still add overhead. For example, when we use the lock keyword, we force some threads to wait while one thread accesses a scope.

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.

private static List wordList; private static List curseWords; private static int currentWordIndex; private static Dictionary<string, int> wordCountDict; private static readonly object wordCountCalculatorSyncObj = new object(); public static void CalculateWordCounts() { wordList = GetWordList(); curseWords = GetCurseWords(); currentWordIndex = 0; wordCountDict = new Dictionary<string, int>(); Thread threadA = new Thread(ThreadDoWork); Thread threadB = new Thread(ThreadDoWork); Thread threadC = new Thread(ThreadDoWork); Thread threadD = new Thread(ThreadDoWork); threadA.Start(); threadB.Start(); threadC.Start(); threadD.Start(); threadA.Join(); threadB.Join(); threadC.Join(); threadD.Join(); } private static void ThreadDoWork() { bool atLeastOneWordRemaining; int thisWordIndex; lock (wordCountCalculatorSyncObj) { thisWordIndex = currentWordIndex; currentWordIndex = currentWordIndex + 1; } if (thisWordIndex >= wordList.Count) atLeastOneWordRemaining = false; else atLeastOneWordRemaining = true; while (atLeastOneWordRemaining) { string thisWord = wordList[thisWordIndex] .ToUpper() .Replace("-", String.Empty) .Replace("'", String.Empty) .Trim(); if (curseWords.Contains(thisWord)) Console.WriteLine("Curse word detected!"); lock (wordCountCalculatorSyncObj) { bool firstOccurrenceOfWord = !wordCountDict.ContainsKey(thisWord); if (firstOccurrenceOfWord) wordCountDict.Add(thisWord, 1); else wordCountDict[thisWord] = wordCountDict[thisWord] + 1; thisWordIndex = currentWordIndex; currentWordIndex = currentWordIndex + 1; } if (thisWordIndex >= wordList.Count) atLeastOneWordRemaining = false; } }

The 2012 error message .aspx to this is to split 2012 error message .aspx work into equal chunks before 2012 error message .aspx processed. Then, let each thread 2012 error message .aspx a local count before it updates the global one. To see how that works, take a look at this article. (@Xenoprimate)

https://github.com/paologutierrez/.net50/blob/master/unnecessary-contention-in-multithreading.md

24. Using Weak Cryptographic Algorithms

Using old, outdated cryptographic algorithms is one of the most easily avoided errors. Algorithms like TripleDES, 2012 error message .aspx, SHA1, and RIPEMD160 can’t deliver the level of security that their more modern counterparts can.

using System.Security.Cryptography; . var hashAlg = SHA1.Create();

To avoid the CA5350 CheckID, use stronger algorithms.

  • Instead of TripleDES, use Aes encryption.
  • Instead of SHA1 or RIPEMD160, use SHA512, SHA384, or SHA256.
  • See this page from Microsoft for full documentation. (@msdev)

https://github.com/paologutierrez/.net50/blob/master/using-weak-cryptography.md

25, 2012 error message .aspx. Using the Wrong Collection Type

In .NET, using the right collection type can save time and avoid errors. Below is a list of the most commonly used C# collections.

var list = new List(); var dictionary = new Dictionary<int, Customer>(); var hashSet = new HashSet(); var stack = new Stack(); var queue = new Queue();
  • The List collection type can grow in size to accommodate growing data sets.
  • The Dictionary collection type is useful for fast lookups by keys.
  • The HashSet collection type works best for very fast lookups in a list of unique items.
  • The Stack collection type comes in handy for providing users with ways to go back.
  • This great tutorial gives a great explanation of how to avoid errors by using the right collection type for the job. (@moshhamedani)

https://github.com/paologutierrez/.net50/blob/master/Not-using-the-correct-collection-type-depending-on-the-situation.mdown

26. Unregistered Events

This common mistake happens when we create an event handler that handles events occurring in an object, but we don’t clear the link when we’ve finished. This oversight can leave behind an unwanted strong reference.

In the code below, we subscribe to an OnPlaced event in our Order class, and the following code executes on a button click:

Order newOrder=new Order (“EURUSD”, DealType.Buy, Price ,PriceTolerance, TakeProfit, StopLoss); newOrder.OnPlaced+=OrderPlaced; m_PendingDeals.Add(newOrder);

When the OrderPlaced method is called, the following code executes:

Void OrderPlace(Order pladedOrder) { m_PendingDeals.Remove(placedOrder); }

However, a reference to the Order object is still held by the OrderPlaced event handler. The Order object is therefore kept alive, even though we removed it from the collection. For more information on this, see:

https://github.com/paologutierrez/.net50/blob/master/unregistered-events.md

27. Readonly Shorthand Property Declaration

This WCF error happens when we fail to keep both getter and setter in our code when using the ReadOnly shorthand property declaration with the DataMember attribute. Without the setter part, we’ll get an error.

//Data Contract attribute applied to class to make it available to client. //Data Member attribute applied to the 'MyVar' readonly property. [DataContract] public class MyValueObject { 2012 error message .aspx public int MyVar { get; //This will not work, as WCF needs both getter and setter to access property. } } //Correct version 2012 error message .aspx both getters and setter defined. bios rom checksum error - system halted [DataContract] public class MyValueObject { [DataMember] public int MyVar { get; set {} //Empty setter block is supplied for readonly property. } }

We can circumvent this problem by setting a block with empty brackets, as shown in this article. (@codeproject)

https://github.com/paologutierrez/.net50/blob/master/readonly-shorthand-property-declaration-in-wcf.md

28. Mistyping the WF/WCF Service Configuration Name

When we use WCF with Visual Studio, 2012 error message .aspx, we can run into a problem that comes from default configurations.

<?xml version="1.0" encoding="utf-8" ?> <configuration> <system.serviceModel> <behaviors> <serviceBehaviors> <behavior> <serviceMetadata httpGetEnabled="true"/> <serviceDebug includeExceptionDetailInFaults="false"/> </behavior> </serviceBehaviors> </behaviors> </system.serviceModel> </configuration>

The code above doesn’t specify a <services> 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’ll need to manually change the name of our service in the configuration file, 2012 error message .aspx. See this tutorial for more. (@msdev)

https://github.com/paologutierrez/.net50/blob/master/mistyping-the-wf-wcf-service-configuration-name.md

29. Modifying SMSvcHost.exe.config for WCF

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:

<net.tcp listenBacklog=”10? maxPendingConnections=”100? maxPendingAccepts=”2? receiveTimeout=”00:00:10? teredoEnabled=”false”> <allowAccounts> // LocalSystem account <add securityIdentifier=”S-1-5-18?/> // LocalService account <add securityIdentifier=”S-1-5-19?/> // Administrators account <add securityIdentifier=”S-1-5-20?/> // Network Service account <add securityIdentifier=”S-1-5-32-544? /> // IIS_IUSRS account (Vista only) <add securityIdentifier=”S-1-5-32-568?/> </allowAccounts> </net.tcp>

Some common problems that arise from modifying the file include:

  • Modifying the wrong SMSvcHost.exe.config file.
  • Changing dummy settings in a comment within the file.
  • Failing to restart Net.Tcp Port Sharing service after making changes to the file.

For steps to avoid making these common mistakes, see this blog post from Microsoft. (@msdev)

https://github.com/paologutierrez/.net50/blob/master/modifying-smsvchost-exe-config.md

30. Leaving Tracing Enabled in Web-Based Applications

Tracing is a very useful .NET debugging tool. It’s also an excellent way for a hacker to access your system if it’s left in place in a production environment. Don’t fall into the trap shown below:

<configuration> <system.web> <trace enabled="true" localOnly="false">

In the configuration above, any user can access a detailed list of all recent requests to the app. How? By browsing the page “trace.axd.” The trace log provides a plethora of useful information to the hacker.

The best 2012 error message .aspx to prevent hacks through tracing data is to disable tracing. Do this by setting “enabled” to “false” for the <trace> element, 2012 error message .aspx. For more info, see this tutorial. (@dotnetstories)

https://github.com/paologutierrez/.net50/blob/master/leaving-tracing-enabled-in-web-Based-applications.md

31. Custom Errors Disabled

Disabling custom errors in .NET gives clients detailed error messages by default.

<configuration> <system.web> <customErrors mode=”Off“>

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.

To fix the problem:

  • Set customErrors mode to RemoteOnly or Doing this displays more generic, nondescript error messages.
  • Set the defaultRedirect attribute of the <customErrors> element to redirect the user to a new page.
  • See this post for a more detailed walk-through of fixing this issue. (@dotnetstories)

https://github.com/paologutierrez/.net50/blob/master/custom-errors-disabled.md

32. Binding Leak

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:

class Person { public Person(string name) { Name = name } public string Name {get; set;} }

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’t know when to deallocate the reference. Therefore, our source object remains in memory.

  • Detect this error by checking the dotMemory automatic inspections snapshot overview page for WPF binding leaks.
  • Fix the problem by making the object a DependencyProperty. For complete instructions, see this tutorial. (@jetbrains)

https://github.com/paologutierrez/.net50/blob/master/binding-leak.md

33. Forgetting to an XSRF Token to the Client

XRSF tokens protect against cross-site request forgeries, 2012 error message .aspx. 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.

The code below passes an XSRF token to the client, avoiding this egregious postfix 550 error message nastroika public class XsrfTokenController : Controller { private readonly IAntiforgery _antiforgery; public XsrfTokenController(IAntiforgery antiforgery) { _antiforgery = antiforgery; } [HttpGet] public IActionResult Get() { var tokens = _antiforgery.GetAndStoreTokens(HttpContext); return new ObjectResult(new { token = tokens.RequestToken, tokenName = tokens.HeaderName }); } }

Read the full tutorial on this here. (@OdeToCode)

https://github.com/paologutierrez/.net50/blob/master/not-protecting-clients-with-xsrf-tokens.md

34. DispatcherTimer Leak

A DispatcherTimer leak is an error where improper use of the DispatcherTimer causes a memory leak.

In the example below, the count 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.

public byte[] myMemory = new byte[50 * 2012 error message .aspx * 1024]; System.Windows.Threading.DispatcherTimer _timer = new System.Windows.Threading.DispatcherTimer(); int count = 0; private void MyLabel_Loaded(object sender, RoutedEventArgs e) { _timer.Interval = TimeSpan.FromMilliseconds(1000); _timer.Tick += new EventHandler(delegate(object s, EventArgs ev) { count++; textBox1.Text = count.ToString(); }); _timer.Start(); }

Fixing this is easy. Just stop the timer and set it to null. (@Simple_Talk)

_timer.Stop(); _timer=null;

https://github.com/paologutierrez/.net50/blob/master/dispatcher-timer-leak.md

35. x:Name 2012 error message .aspx 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’t build the UI correctly, we can introduce a memory leak.

Every time we declare a UI element in XAML using the x:Name directive, WPF will create a strong global reference.

We may think we can dynamically remove the element, but the control will stay in memory, even after we remove it from the Children collection of the parent control:

private void DeleteData_OnClick(object sender, RouteEventArgs e) { if (personEditor != null) { _grid.Children.Remove(personEditor); personEditor = null; } }

Here’s how to fix this common issue:

  • 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.
  • Fix it by calling the parent control’s UnregisterName method.
  • For a full brief on this error and its fix, see here. (@jetbrains)

https://github.com/paologutierrez/.net50/blob/master/x-name-leak.md

36. TextBox Undo Leak

This isn’t 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 sms 97 error their undo stacks.

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.

textBox1.IsUndoEnabled=true; textBox1.UndoLimit=-1

To rectify this, either set IsUndoEnabled to false, or set an UndoLimit other than -1 (such as 100).

To see this problem and solution explained in more detail, see this article. (@Simple_Talk)

https://github.com/paologutierrez/.net50/blob/master/textbox-undo-leak.md

37. Event Handler Leak

Yet another memory leak error is the event handler leak. In C#, we don’t always get a leak when we subscribe to an event and then forget to unsubscribe. In most cases, the events don’t stay in memory.

However, when an event publisher is long lived, then all its subscribers will be kept alive too, as in the following example:

public class ShortLivedEventSubscriber { public static int Count; public string LatestText 2012 error message .aspx get; private set; } public ShortLivedEventSubscriber(Control c) { Interlocked.Increment(ref Count); c.TextChanged += OnTextChanged; } private void OnTextChanged(object sender, EventArgs eventArgs) { LatestText = ((Control) sender).Text; } ~ShortLivedEventSubscriber() { Interlocked.Decrement(ref Count); } }

Here’s the code that creates the instances:

private void OnShortLivedEventSubscribersClick(object sender, EventArgs eventArgs e) { intcount = 10000; for (int n = 0; n < count; n++ { var shortlived2 = new ShortLivedEventSubscriber(this); } shortlivedEventSubscriberCreated += count; }

The solution here is simple. Any time you subscribe to an event, if it’s raised by a service that has a long life, you must unsubscribe from it.

https://github.com/paologutierrez/.net50/blob/master/event-handler-leak.md

38. Potentially Dangerous Request.Form Value

Here’s a workaround for an error caused when we want to send HTML code to a server. By default, we’ll 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.

As shown below, we can use the AllowHtml 2012 error message .aspx for the model class dns format error from invalid response disable ASP.NET MVC validation 2012 error message .aspx that particular property.

public class PersonModel { [Display(Name = "Resume:")] [AllowHtml] public string Resume { get; set; } }

For the full rundown of using the AllowHtml attribute to avoid this issue, 2012 error message .aspx, see this tutorial. (@ASPSnippets)

https://github.com/paologutierrez/.net50/blob/master/potentially-dangerous.md

39. “The Remote Name Could Not Be Resolved” (WCF/Azure Error)

Sometimes a service that works fine on a local machine doesn’t play well with Azure. In that case, we get a “failed to invoke the service” notification.

Inner Exception: The remote name could not be resolved: ‘rd00155d3ad8c4' at System.Net.HttpWebRequest.GetRequestStream(TransportContext& context) at System.Net.HttpWebRequest.GetRequestStream() at System.ServiceModel.Channels.HttpOutput.WebRequestHttpOutput.GetOutputStream()

This can be an extremely frustrating problem since there’s no obvious reason for it to happen in the first place and there’s no obvious fix. However, this blog post offers an elegant solution. Alter the web.config file as follows:

<behavior name=”MexGet”> <serviceMetadata httpGetEnabled=”true”  /> <useRequestHeadersForMetadataAddress> <defaultPorts> <add scheme=”http” port=”81? /> </defaultPorts> </useRequestHeadersForMetadataAddress> </behavior>

This sets up your service to operate in a load-balanced environment like Azure.

https://github.com/paologutierrez/.net50/blob/master/error-in-wcf-azure.md

40. PRB: 2012 error message .aspx is Denied”

When remotely debugging an ASP.NET application using Visual Studio, we can get the following error message:

“Error 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?”

This happens because the user doing the remote debugging doesn’t belong to the Debugger Users group for the MS Internet Information Server.

To solve this problem, add the user to the appropriate group by following the steps shown in this Microsoft support page. (@MicrosoftHelps)

PRB: “Access is Denied”

41. ViewBag Does Not Exist in the Current Context

This issue can arise after upgrading an application from ASP MVC 4 to ASP MVC 5.

To fix the problem, install the ASP.NET Web Helpers Library, then open the project’s web.config file and update the bindings as follows:

<dependentAssembly> <assemblyIdentity name=”System.Web.Mvc” publicKeyToken=”31bf3856ad364e35? /> <bindingRedirect oldVersion=”0.0.0.0-5.2.2.0? newVersion=”5.2.2.0” /> </dependentAssembly>

In the appsettings, find 2012 error message .aspx and update to version 3.0.0.0. Then restart Visual Studio. See this blog post for more. (@AhmedAlAsaad)

https://github.com/paologutierrez/.net50/blob/master/viewbag-does-not-exist.md

42. Error While Trying to Run Project

This error comes about when debugging an ASP.NET app with Visual Studio. The full 2012 error message .aspx message is:

“Error while trying to run project: Unable to start debugging on the web server. The project is not configured to be debugged.”

Error While Trying to Run Project

We can run into this error for two reasons:

  • The ASP.NET app is missing a web.config file.
  • The project folder’s Execute Permissions property in Internet Services Manager is set to

To fix the problem, either add a web.config file (if it’s missing) or set Execute Permissions to Scripts only. For more info, see this Microsoft help page. (@MicrosoftHelps)

43. Not Taking Advantage of Dependency Injection

Let’s say our Controller needs a FooService that lets it fetch a Foo that it can render to the user, 2012 error message .aspx, like so:

public class FooController { public IActionResult Index() how to fix jit-edocs api error var fooService = new FooService(new BarService(), new BazService()); return View(fooService.GetFoo()); } }

The trouble is, our Controller needs fine details about how to create a FooService. That means we have to replicate that logic everywhere a FooService is needed.

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.

To see all the steps to take advantage of this powerful feature, see this tutorial, 2012 error message .aspx. (@ArmenShimoon)

https://github.com/paologutierrez/.net50/blob/master/not-taking-advantage-of-dependency-injection.md

44. Misuse of the ‘var’ Keyword

Misuse and overuse of the var keyword is a common and basic error. The real purpose of var is to let us declare a local variable when we don’t know the type name. This is usually true with anonymous types when we don’t get the type name until compile time.

Yet some developers 2012 error message .aspx var every time they declare a variable. In a local variable declaration, the type name gives us an added layer of description:

// let's say we have a static method called GetContacts() // that returns System.Data.DataTable var individuals = GetContacts(ContactTypes.Individuals); // how is it clear to the reader that I can do this? return individuals.Compute("MAX(Age)", String.Empty);

Other reasons to limit the use of var:

  • It encourages Hungarian notation.
  • It destroys the layer of context provided by type names.
  • It increases reliance on IntelliSense.
  • It doesn’t provide backward compatibility.

For an in-depth argument about var as an error, see this article.

https://github.com/paologutierrez/.net50/blob/master/misuse-of-var-keyword.md

45. Incorrectly using IoC Containers

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:

public class HomeController { private readonly IExampleService _service; public HomeController() { _service = new ExampleService(); } public ActionResult Index() { return View(_service.GetSomething()); } }

However, when we use dependency injection improperly in the following ways, we 2012 error message .aspx into errors:

  • Using the container to retrieve dependencies instead of injecting them.
  • Abstracting the container.
  • Accessing the container to resolve components dynamically.

For an in-depth tutorial on using IoC containers correctly, click here. (@DevTrends)

https://github.com/paologutierrez/.net50/blob/master/incorrectly-using-ioc-containers.md

46. .ToLower() Not Working in LINQ Query

The String.ToLower method returns a copy of a error texture file 800corner1, 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:

list = (from sr in dbContext.SERVICE_REQUEST join sc in dbContext.SERVICE_CUSTOMER on sr.CUSTOMER_ID equals sc.CUSTOMER_ID) where (sr.SERVICE_REQUEST_NO.ToLower().Contains(objtobeAdvSearch.ServiceRequestNumber.ToLower()))

One solution (@ExpertsExchange) is to avoid the use of .ToLower here and instead use IndexOf with the case-insensitive OrdinalIgnoreCase

What is view state?

View state is information that is round-tripped between WebForms (.aspx) pages in an ASP.NET application. The HTML markup for the __VIEWSTATE field resembles the following:

<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="." />
One example of an item that might be stored in the __VIEWSTATE centos make menuconfig error is the text of a Button control. If a user clicks the button, the Button_Click event handler will be able to extract the Button's text from the view state field. See the ASP.NET View State Overview topic on the Microsoft Developer Network (MSDN) website for a much more detailed overview of the ASP.NET view state.

Because the __VIEWSTATE field contains important information that is used to reconstruct the page on postback, make sure that an attacker cannot to tamper with this field. If an attacker submitted a malicious __VIEWSTATE payload, the attacker could potentially trick the application into performing an action that it otherwise would not have performed.

To prevent this kind of tampering attack, the __VIEWSTATE field is protected by a message authentication code (MAC). ASP.NET validates the MAC that is submitted together with the __VIEWSTATE payload when a postback occurs. The key that is used to calculate the MAC is specified in the application's element in the Web.config file. Because the attacker cannot guess the contents of the <machineKey> element, the attacker cannot provide a valid MAC if the attacker tries to tamper with the __VIEWSTATE payload. ASP.NET will detect that a valid MAC hasn't been provided, 2012 error message .aspx, and ASP.NET will reject the malicious request.

What causes MAC validation errors?

A MAC validation error will resemble the following example:

Server Error in '/' Application.

Validation of viewstate MAC failed. If this application is hosted by a web farm or cluster, ensure that <machineKey> configuration specifies the same validationKey and validation algorithm. AutoGenerate cannot be used in a cluster.

Description: An unhandled exception occurred during the execution of the current web request, 2012 error message .aspx. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Web.HttpException: Validation of viewstate MAC failed. If this application is hosted by a Web Farm or cluster, ensure that <machineKey> configuration specifies the same validationKey and validation algorithm. AutoGenerate cannot kx driver error selecting device used in a cluster.

Source Error: [No relevant source lines]

Source File: . Line: 0

Stack Trace:

[ViewStateException: Invalid viewstate.
Client IP: ::1
Port: 40653
Referer: http://localhost:40643/MyPage.aspx
Path: /MyPage.aspx
User-Agent: Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)
ViewState: .]

[HttpException (0x80004005): Validation of viewstate MAC failed. If this application is hosted by a Web Farm or cluster, ensure that <machineKey> configuration specifies the same validationKey and validation algorithm. AutoGenerate cannot be used in a cluster.

See http://go.microsoft.com/fwlink/?LinkID=314055 for more information.]
System.Web.UI.ViewStateException.ThrowError(Exception inner, String persistedState, String errorPageMessage, Boolean macValidationError) +190
System.Web.UI.ViewStateException.ThrowMacValidationError(Exception inner, String persistedState) +46
System.Web.UI.ObjectStateFormatter.Deserialize(String inputString, Purpose purpose) +861
System.Web.UI.ObjectStateFormatter.System.Web.UI.IStateFormatter2.Deserialize(String serializedState, Purpose purpose) +51
System.Web.UI.Util.DeserializeWithAssert(IStateFormatter2 formatter, String serializedState, Purpose purpose) +67
System.Web.UI.HiddenFieldPageStatePersister.Load() +444
System.Web.UI.Page.LoadPageStateFromPersistenceMedium() +368
System.Web.UI.Page.LoadAllState() +109
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +7959
System.Web.UI.Page.ProcessRequest(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +429
System.Web.UI.Page.ProcessRequest() +125
System.Web.UI.Page.ProcessRequestWithNoAssert(HttpContext context) +48
System.Web.UI.Page.ProcessRequest(HttpContext context) +234
ASP.mypage_aspx.ProcessRequest(HttpContext context) in .:0
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +1300
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +140

Cause 1: The web application is running in a farm (multi-server environment)

ASP.NET automatically generates a cryptographic key for each application and stores the key in the HKCU registry hive. This auto-generated key is used if there is no explicit <machineKey> element in the application’s configuration. However, because this auto-generated key is local to the computer that created the key, this scenario causes a 2012 error message .aspx for applications that run in a farm. Each server in the farm will generate its own local key, and none of the servers in the farm will agree on which key to use. The result is that, if one server generates a __VIEWSTATE payload that a different server consumes, the consumer will experience a MAC validation failure.

  • Resolution 1a: Create an explicit <machineKey> element

    By adding an explicit <machineKey> element to the application's Web.config file, the developer tells ASP.NET not to use the auto-generated cryptographic key. See Appendix A for instructions on how to generate a <machineKey> element. After this element is added to the Web.config file, redeploy the application to each server in the farm.

    Note Some web hosting services, such as Microsoft Azure websites, take steps to synchronize each application's auto-generated key across their back-end servers. This lets applications that have not specified an explicit <machineKey> element to continue working in these environments, even if the application is running in a farm. If your application is running on a third-party hosting service, please contact your hosting provider to determine whether this situation applies to you.

  • Resolution 1b: Enable affinity in the load balancer

    If your sites are operating behind a load balancer, you can enable server affinity to temporarily work around the issue. This helps ensure that any given client only interacts with one physical server behind the load balancer so that all cryptographic payloads will be both generated by and consumed by the same server.

    This should not be considered a long-term solution to the problem. Even when server e32 12 6a00 ap position error is enabled, most load balancers will redirect the client to a different physical server if the original server to which the load balancers were affinitized goes offline. This causes the new server to reject cryptographic payloads (such as __VIEWSTATE, forms authentication tickets, MVCs anti-forgery tokens, and other services) that the client currently has.

    Using an explicit <machineKey> element and redeploying the application should be preferred over enabling server affinity.

Cause 2: The worker process uses the IIS 7.0 application pool identity

Internet Information Services (IIS) 7.0 (Windows Vista, Windows Server 2008) introduced application pool identity, a new isolation mechanism that helps provide increased security for servers that run ASP.NET applications. However, sites that are running under the application pool identity do not have access to the HKCU registry. This is where the ASP.NET runtime stores its auto-generated <machineKey> keys. The result is that ASP.NET cannot persist the auto-generated key when the application pool is reset. Therefore, every time w3wp.exe is reset, a new temporary key is generated.

Note This is not an issue in IIS 7.5 (Windows 7, Windows Server 2008 R2) and later versions, 2012 error message .aspx. On these versions of IIS, ASP.NET can persist its auto-generated keys in a different location that survives application pool resets.

  • Resolution 2a: Use the aspnet_regiis utility

    ASP.NET installations contain a utility, aspnet_regiis.exe. This utility lets ASP.NET interface with IIS to perform the configurations that are required to run a managed application. One of these configurations creates the necessary keys in the registry hive to enable persistence of auto-generated machine keys.

    First, you have to determine which application pool your site is using. This can be determined by using the inetmgr utility that is included with IIS. Select your site in the tree view at the left, right-click Manage Website, and then click Advanced Settings. The dialog box that appears will show the application pool name.

    Advanced Settings

    To scaffold the appropriate registry keys for an ASP.NET 4.0 application pool, follow these steps:

    1. Open an administrative command prompt.

    2. Locate the appropriate directory, depending on whether your application pool is 32-bit or 64-bit:

      • 32-bit application pool: cd /d %windir%\Microsoft.NET\Framework\v4.0.30319

      • 64-bit application pool: cd /d %windir%\Microsoft.NET\Framework64\v4.0.30319

    3. Move to the directory, type the following command, and then press Enter:

      aspnet_regiis -ga "IIS APPPOOL\app-pool-name"


    If the application pool is an ASP.NET 2.0 or 3.5 application pool, follow these steps:

    1. Open an administrative command prompt.

    2. Locate the appropriate directory, depending on whether your application pool is 32-bit or 64-bit:

      • 32-bit application pool: cd /d %windir%\Microsoft.NET\Framework\v2.0.50727

      • 64-bit application pool: cd /d %windir%\Microsoft.NET\Framework64\v2.0.50727

    3. Move to the directory, type the following command, and then press Enter:

      aspnet_regiis -ga "IIS APPPOOL\app-pool-name"


    For example, if your application pool is named My App Pool (as in the previous image), run the following command:

    aspnet_regiis -ga "IIS APPPOOL\My App Pool"

    Note The system services APPHOSTSVC and WAS may have to be running for the aspnet_regiis utility to resolve IIS 2012 error message .aspx names appropriately.

  • Resolution 2b: Create an explicit <machineKey> element

    By adding an explicit <machineKey> element to the application's Web.config file, the developer tells ASP.NET not to use the auto-generated cryptographic key. See Appendix A for instructions on how to generate a <machineKey> element.

Cause 3: The application pool is configured by using LoadUserProfile=false

If the application pool is running with a custom identity, IIS may not have loaded the user profile for the identity. This has the side effect of making the HKCU registry unavailable for ASP.NET to persist the auto-generated <machineKey>. Therefore, a new auto-generated key will be created every time that 2012 error message .aspx application restarts. See the User Profile section on the Microsoft website for more information.

  • Resolution 3a: Use the aspnet_regiis utility

    The instructions for this are the same as Resolution 2a. See that section for more information.

  • Resolution 3b: Use an explicit <machineKey>

    By adding an explicit <machineKey> element to the application's Web.config file, the developer tells ASP.NET not to use the auto-generated cryptographic key. See Appendix A for instructions on how to generate a <machineKey> element.

  • Resolution 3c: Provision the required HKCU registry keys manually

    2012 error message .aspx you cannot run the aspnet_regiis utility, you can use a Windows PowerShell script to provision the appropriate registry keys in HKCU. See Appendix B for more information.

  • Resolution 3d: Set LoadUserProfile=true for this application pool

    You can also enable loading the user profile inside this application pool. This makes the HKCU registry hive, temporary folder, and other user-specific storage locations available to the application. However, 2012 error message .aspx, this may cause increased disk or memory usage for the worker process. See the element for more information about how to enable this setting.

Cause 4: The Page.ViewStateUserKey property has an incorrect value

Software developers can decide to use the Page.ViewStateUserKey property to add cross-site request forgery protection to the __VIEWSTATE field. If you use the Page.ViewStateUserKey property, it is typically set to a value such as the current user’s username or the user's session identifier. The project templates for WebForms applications in Microsoft Visual Studio 2012 and later versions contain samples that use this property. See the Page.ViewStateUserKey Property topic on the Microsoft Developer Network (MSDN) website for more information.

If the ViewStateUserKey property is specified, its value is burned into __VIEWSTATE at generation time. When the __VIEWSTATE field is consumed, the server checks the current Page's ViewStateUserKey property and validates it against the value that was used to generate the __VIEWSTATE field. If the values do not match, the request is rejected as potentially malicious.

An example of a ViewStateUserKey-related failure would be a client who has two tabs open in the browser. The client is logged in as User A, and in the first tab, a Page is rendered with a __VIEWSTATE whose ViewStateUserKey property contains "User A." In the second tab, the client logs out and then logs back in as User B. The client goes back to the first tab and submits the form, 2012 error message .aspx. The ViewStateUserKey property might contain "User B" (because that is what the client's authentication cookie says). However, the __VIEWSTATE field that the client submitted contains "User A." This mismatch causes the failure.

  • Resolution 4a: Verify that ViewStateUserKey is set correctly

    If your application uses the ViewStateUserKey property, verify that the property's value is the same both when view state is generated and when it is consumed. If you are using the current logged-in user's username, make sure that the user is still logged in and that the user's identity has not changed at the time of postback. If you are using the current user's session identifier, make sure that the session hasn't timed out.

    If you are running in a farm environment, make sure that the <machineKey> elements match. See Appendix A for instructions about how to generate these elements.

Appendix A: How to generate a <machineKey> element

Security warning

There are many web sites that will generate a <machineKey> element for you with the click of a button, 2012 error message .aspx. Never use a <machineKey> element that you obtained from one of these sites. It is impossible to know whether these keys were created securely or if they are being recorded to a secret database. You should only ever use <machineKey> configuration elements that you created yourself.



To generate a <machineKey> element yourself, you can use the following Windows PowerShell script:


For ASP.NET 4.0 applications, you can just call Generate-MachineKey without parameters to generate a <machineKey> element as follows:


ASP.NET 2.0 and 3.5 applications do not support HMACSHA256. Instead, you can specify SHA1 to generate a compatible <machineKey> element as follows:


As soon as you have a <machineKey> element, you can put it in the Web.config file. The <machineKey> element is only valid in the Web.config file at the root of your application and is not valid at the subfolder level.


For a full list of supported algorithms, run help Generate-MachineKey from the Windows PowerShell prompt.

Appendix B: Provisioning the registry to persist auto-generated keys

By default, because ASP.NETs auto-generated keys are persisted in the HKCU registry, these keys may be lost if the user profile hasn’t been loaded into the IIS worker process and then the application pool recycles. This scenario could affect shared hosting providers that are running application pools speedcore terror kinetic standard Windows user accounts.

To work around this situation, ASP.NET enables persisting the auto-generated keys in the HKLM registry instead of the HKCU registry. This is typically canon ip1500 error 5600 by using the aspnet_regiis utility (see instructions in the "Resolution 2a: Use the aspnet_regiis utility" section). However, for administrators who do not want to run this utility, the following Windows PowerShell script may be used instead:


The following example shows how to provision the appropriate HKLM registry entries for an application pool that runs as the user, [email protected] (this is the UPN of the Windows user account). This application pool is a 32-bit application pool that is running the CLR v2.0 (ASP.NET 2.0 or 3.5).


If the application pool instead is a 64-bit application pool that is running CLR v4.0 (ASP.NET 4.0 or 4.5), the command is as follows:


Even though the auto-generated keys are stored in HKLM, the registry subkey that holds each user account’s secret cryptographic material is added to an access control list (ACL) so that the cryptographic material cannot be read by other user accounts.

Appendix C: Encrypting the <machineKey> element in configuration files

Server administrators may not want highly sensitive information such as the <machineKey> key material to bein plaintext form in configuration files. If this is the case, administrators may decide to take advantage of a .NET Framework feature known as "protected configuration." This feature lets you encrypt certain sections of the .config files. If the contents of these configuration files are ever disclosed, these sections' contents will still remain secret.

You can find a brief overview of protected configuration on the MSDN website. It also contains a tutorial about how to protect the <connectionStrings> and <machineKey> elements of the Web.config file.

WEBfactory 2010

HTTP Error 503. The service is unavailable under simple ASP.NET web site

Abstract

Check out this article and learn how to overcome an HTTP error 503 under simple ASP.NET web site.

The HTTP 503 error can occur in the following situations:

  • a user tries to access a simple web page like http://localhost/welcome.png;

  • WEBfactory web service calls returns the HTTP 503 error

Some possible reasons are described in the link: http://stackoverflow.com/questions/6105764/http-error-503-the-service-is-unavailable-under-simple-asp-net-4-0-web-site

Also, there can be a security issue that causes the HTTP 503 error:

  • the web.config file under C:\Windows\Microsoft.NET\Framework\v4.0.30319\Config or C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Config may not be accessible due to security issues.

IMPORTANT: The user should check the Window Event Log where errors are reported. If the cause is the security issue, the log should indicate that the access to web.config file is restricted due to security issues.

To solve the web.config security issue, 2012 error message .aspx, set the security rights for the web.config file to "everyone" with full access:

  1. Right-click on the web.config file and select Properties. Go to the Security tab and click Edit

  2. In the Permissions for web window, click on the Add button to add the full permissions for "everyone".

  3. Type "everyone" in the Enter the object names to select text field and click on the Check Names to validate. Press OK to confirm.

  4. Back to the Permissions for web window, make sure that the permissions for "everyone" is set to Allow Full control.

  5. Click OK to confirm the dialogs. Windows may display a warning stating that allowing full permissions may compromise the system security. Confirm the message and apply the settings.

Alert displaying error when submitting

I am also getting this error, but could not resolve it. I moved from ASP.NET 2.0 to 4.0 on IIS7.0.
Here is complete error message

Global Handler: System.Web

Page: /Claims/Telerik.RadUploadProgressHandler.ashx

The file '/Claims/Telerik.RadUploadProgressHandler.ashx' does not exist.

at System.Web.Compilation.BuildManager.GetVPathBuildResultInternal(VirtualPath virtualPath, Boolean noBuild, Boolean allowCrossApp, Boolean allowBuildInPrecompile, Boolean throwIfNotFound, Boolean ensureIsUpToDate)
at System.Web.Compilation.BuildManager.GetVPathBuildResultWithNoAssert(HttpContext context, 2012 error message .aspx, VirtualPath virtualPath, Boolean noBuild, Boolean allowCrossApp, Boolean allowBuildInPrecompile, Boolean throwIfNotFound, Boolean ensureIsUpToDate)
at System.Web.Compilation.BuildManager.GetVPathBuildResult(HttpContext context, VirtualPath virtualPath, Boolean noBuild, Boolean allowCrossApp, Boolean allowBuildInPrecompile, Boolean ensureIsUpToDate)
at System.Web.UI.SimpleHandlerFactory.System.Web.IHttpHandlerFactory2.GetHandler(HttpContext context, String requestType, VirtualPath virtualPath, String physicalPath)
at System.Web.HttpApplication.MaterializeHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) 

2012 error message .aspx

0 Comments

Leave a Comment