Thursday, August 30, 2012

ASP.NET 4.0 potentially dangerous Request.Form value was detected

Few days ago, while working on an ASP.NET 4.0 Web project, I got an issue. The issue was, when user enters unencoded HTML content into a comment text box s/he got something like the following error message:
"A potentially dangerous Request.Form value was detected from the client".


This was because .NET detected something in the entered text which looked like an HTML statement. Then I got a link Request Validation, that is a feature put in place to protect your application cross site scripting attack and followed accordingly.

To disable request validation, I added the following to the existing "page" directive in that .aspx file.

ValidateRequest="false"


But still I got the same error.

Later I found, for .NET 4, we need to add requestValidationMode="2.0" to the httpRuntime configuration section of the web.config file like the following:

<httpRuntime requestValidationMode="2.0"/>


But if there is no httpRuntime section in the web.config file, then this goes inside the <system.web> section.

If anyone wants to turn off request validation for globally user, the following line in the web.config file within <system.web> section:

<pages validateRequest="false" /> 


Wednesday, August 29, 2012

How to fix LINQ Error: Sequence contains no elements


I’ve read some posts regarding this error when using the First() or Single() command.   They suggest using FirstOrDefault() or SingleorDefault() instead.

But I recently encountered it when using a Sum() command in conjunction with a Where():

var effectiveFloor = policies.Where(p => p.PricingStrategy == PricingStrategy.EstablishFloor).Max(p => p.Amount);


When the Where() function eliminated all the items in the policies collection, the Sum() command threw the “Sequence contains no elements” exception.



Inserting the DefaultIfEmpty() command between the Where() and Sum(), prevents this error:

var effectiveFloor = policies.Where(p => p.PricingStrategy ==PricingStrategy.EstablishFloor).DefaultIfEmpty().Max(p => p.Amount);

but now throws a Null Reference exception!


The Fix:
Using a combination of DefaultIfEmpty() and a null check in the Sum() command solves this problem entirely:
var effectiveFloor = policies.Where(p => p.PricingStrategy ==PricingStrategy.EstablishFloor).DefaultIfEmpty().Max(p =>  p==null?0 :p.Amount);


LINQ: Sequence contains no elements. Extension methods to the rescue.


When you start playing with LINQ queries over sequences of elements (e.g. getting min / max value for enumerable source) sooner or later you will come across this one -- the InvalidOperationException (“Sequence contains no elements”).
The problem occurs as by default queries like IEnumerable<T>.Min(…) andIEnumerable<T>.Max(…) do not play nicely if you try to execute them on an empty sequence and just throw the exception described above. Unfortunately these methods do not have a corresponding counterpart like Single(…) / SingleOrDefault(…) that is smart enough to query the sequence if it is not empty or alternatively use the default value without raising an exception.
Basically you got two options now:
  • Either perform the check on the enumerable sequence every time you are querying it
  • OR integrate the logic in an extension method.
The second approach is much preferable so let’s add the missing link below:
namespace ExtensionMethods {
    
using System;
    
using System.Collections.Generic;
    
using System.Linq;

    
public static class IEnumerableExtensions
    
{
        
/// <summary>         /// Invokes a transform function on each element of a sequence and returns the minimum Double value          /// if the sequence is not empty; otherwise returns the specified default value.          /// </summary>         /// <typeparam name="TSource">The type of the elements of source.</typeparam>         /// <param name="source">A sequence of values to determine the minimum value of.</param>         /// <param name="selector">A transform function to apply to each element.</param>         /// <param name="defaultValue">The default value.</param>         /// <returns>The minimum value in the sequence or default value if sequence is empty.</returns>         public static double MinOrDefault<TSource>(this IEnumerable<TSource> source, Func<TSource, double> selector, double defaultValue)
        
{
            
if (source.Count<TSource>() == 0)
                
return defaultValue;

            
return source.Min<TSource>(selector);
        
}

        
/// <summary>         /// Invokes a transform function on each element of a sequence and returns the maximum Double value          /// if the sequence is not empty; otherwise returns the specified default value.          /// </summary>         /// <typeparam name="TSource">The type of the elements of source.</typeparam>         /// <param name="source">A sequence of values to determine the maximum value of.</param>         /// <param name="selector">A transform function to apply to each element.</param>         /// <param name="defaultValue">The default value.</param>         /// <returns>The maximum value in the sequence or default value if sequence is empty.</returns>         public static double MaxOrDefault<TSource>(this IEnumerable<TSource> source, Func<TSource, double> selector, double defaultValue)
        
{
            
if (source.Count<TSource>() == 0)
                
return defaultValue;

            
return source.Max<TSource>(selector);
        
}
    
} }

Now you only need to add the using ExtensionMethods; directive in your project and you are all set.

Thursday, August 2, 2012

How to Force Google Chrome to Download PDF Files



  • Click the wrench button on upper right.
  • Go to "Settings" 
  • Click on Show advanced settings...
  • Go to: Content Settings -> Plug-ins
  • Click on "Disable Individual Plug-ins...
  • Locate the Adobe Acrobat plugin (or any other PDF viewer) and 
  • Click "Disable"