Operation is not valid due to the current state of the object.

Issue:

System.InvalidOperationExceptionOperation is not valid due to the current state of the object.

System.InvalidOperationException: Operation is not valid due to the current state of the object.
   at System.Web.HttpRequest.FillInFormCollection()
   at System.Web.HttpRequest.get_Form()
   at Rhino.Commons.LongConversationManager.LoadConversationFromRequest(Boolean& privateConversation)
   at Rhino.Commons.LongConversationManager.LoadConversation()
   at Rhino.Commons.HttpModules.UnitOfWorkApplication.UnitOfWorkApplication_BeginRequest(Object sender, EventArgs e)
   at System.Web.HttpApplication.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
   at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
		
Cause:

Microsoft recently (12-29-2011) released an update to address several serious security vulnerabilities in the .NET Framework. MS11-100 was introduced just recently that handles potential DoS attacks.

Unfortunately the fix has also broken page POSTs with very large amounts of posted data (form fields). MS11-100 places a limit of 500 on postback items. The new default max introduced by the recent security update is 1000.

Adding the setting key to the web-config file overcomes this limitation, as in this example increases it to 2000.

<appSettings>
    <add key="aspnet:MaxHttpCollectionKeys" value="2000" />
 </appSettings>

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

jQuery - upgrade from version 1.6.x to 1.7

Goal:

Issues to consider when upgrading from jQuery version 1.6 to 1.7. This is a short list and may help identify the real issues you need to concern yourself with in stead of reading through all the release notes

Summary of issues encountered during upgrade:

As you prepare for upgrade to jQuery 1.7 from 1.6.x, this is a quick glimpse of all the issues that are relevant, not sure if it covers all but may be all you need to worry about.

Use this method only for checking checkboxes and radio buttons:
$("input:checked")
This will work regardless of the version of jQuery you are using. Note that $("input).attr("checked") returns true prior to jQuery 1.6. Only retrieve "real" attributes with "attr", in order versions it would also retrieve properties like "tagName", this no longer works with jQuery 1.6.1+

Why does $("input").attr("checked") no longer (from version 1.6.1+) return TRUE or FALSE, because if you look at the HTML (as well as W3C spec) it does not contain a true/false, but the value checked="checked", which is what it should have returned in the first place. $("input").prop("checked") works, return true, because there is in fact a DOM property for "checked" with the value being "true" or "false".

Furthermore, if you want to upgrade to jQuery 1.7 you should only have to worry about this for most part:
1. isNumeric() is new, be careful as the older version jQuery.isNaN() has been deprecated
2. jqXHR success and error have been deprecated
3. When rendering content with text(), white space issue cross-browsers: http://bugs.jquery.com/ticket/3144

Other than the issues above I am not aware of any deprecations you need to worry about.

Hope this helps to get everyone up to version 1.7

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

SQL Server - Rebuilding Indexes

Goal:

Rebuild indexes in SQL server. This can be done one at a time or with the example script below to rebuild all index for a specified table or for all tables in a given database.


Why?
The data in indexes gets fragmented over time. That means that as the index grows, the newly added rows to the index are physically stored in other sections of the allocated database storage space. Kind of like when you load your Christmas shopping into the trunk of your car and it is full you continue to load some on the back seat, in the same way some storage buffer is created for your index but once that runs out the data is then stored in other storage space and your data in your index is no longer stored in contiguous physical pages. To access the index the database manager has to "string together" disparate fragments to create the full-index and create one contiguous set of pages for that index. Defragmentation fixes that.

What does the fragmentation affect?
Depending of course on how large the table is and how fragmented the data is, can cause SQL Server to perform unnecessary data reads, slowing down SQL Server’s performance.

Which index to rebuild?
As a rule consider that when reorganize a table's clustered index, all other non-clustered indexes on that same table will automatically be rebuilt. A table can only have one clustered index.

How to rebuild all the index for one table:
The DBCC DBREINDEX command will not automatically rebuild all of the indexes on a given table in a database

How to rebuild all indexes for all tables in a given database:

USE [myDB]    -- enter your database name here

DECLARE @tableName varchar(255)

DECLARE TableCursor CURSOR FOR
SELECT table_name FROM information_schema.tables
WHERE table_type = 'base table'

OPEN TableCursor

FETCH NEXT FROM TableCursor INTO @tableName
WHILE @@FETCH_STATUS = 0
BEGIN
DBCC DBREINDEX(@tableName,' ',90)     --a fill factor of 90%
FETCH NEXT FROM TableCursor INTO @tableName
END

CLOSE TableCursor

DEALLOCATE TableCursor


What does this script do?
Reindexes all indexes in all tables of the given database. Each index is filled with a fill factor of 90%. While the command DBCC DBREINDEX runs and rebuilds the indexes, that the table becomes unavailable for use by your users temporarily until the rebuild has completed, so don't do this during production  hours as it will create a shared lock on the tables, although it will allow for read-only uncommitted data reads; i.e.e SELECT.

What is the fill factor?
Is the percentage of space on each index page for storing data when the index is created or rebuilt. It replaces the fill factor when the index was created, becoming the new default for the index and for any other nonclustered indexes rebuilt because a clustered index is rebuilt. When fillfactor is 0, DBCC DBREINDEX uses the fill factor value last specified for the index. This value is stored in the sys.indexes catalog view.

If fillfactor is specified, table_name and index_name must be specified. If fillfactor is not specified, the default fill factor, 100, is used.

How do I determine the level of fragmentation?
Run the DBCC SHOWCONTIG command. However this requires you to specify the ID of both the table and index being. To make it a lot easier by only requiring you to specify the table name and/or index you can run this script:

DECLARE
@ID int,
@IndexID int,
@IndexName varchar(128)

--Specify the table and index names
SELECT @IndexName = ‘index_name’    --name of the index
SET @ID = OBJECT_ID(‘table_name’)  -- name of the table

SELECT @IndexID = IndID
FROM sysindexes
WHERE id = @ID AND name = @IndexName

--Show the level of fragmentation
DBCC SHOWCONTIG (@id, @IndexID)


Here is an example:

DBCC SHOWCONTIG scanning 'Tickets' table...
Table: 'Tickets' (1829581556); index ID: 1, database ID: 13
TABLE level scan performed.
- Pages Scanned................................: 915
- Extents Scanned..............................: 119
- Extent Switches..............................: 281
- Avg. Pages per Extent........................: 7.7
-
Scan Density [Best Count:Actual Count].......: 40.78% [115:282]
- Logical Scan Fragmentation ..................: 16.28%
- Extent Scan Fragmentation ...................: 99.16%
- Avg. Bytes Free per Page.....................: 2457.0
- Avg. Page Density (full).....................: 69.64%
DBCC execution completed. If DBCC printed error messages, contact your system administrator.


What's important here?
The Scan Density; Ideally it should be 100%. As time goes by it drops as fragmentation occurs. When the level drops below 75%, you should consider re-indexing.

Here are the results of the same table and clustered index after running the script:

DBCC SHOWCONTIG scanning 'Tickets' table...
Table: 'Tickets' (1829581556); index ID: 1, database ID: 13
TABLE level scan performed.
- Pages Scanned................................: 692
- Extents Scanned..............................: 87
- Extent Switches..............................: 86
- Avg. Pages per Extent........................: 8.0
-
Scan Density [Best Count:Actual Count].......: 100.00% [87:87]
- Logical Scan Fragmentation ..................: 0.00%
- Extent Scan Fragmentation ...................: 22.99%
- Avg. Bytes Free per Page.....................: 639.8
- Avg. Page Density (full).....................: 92.10%
DBCC execution completed. If DBCC printed error messages, contact your system administrator.


What's different?
The Scan Density has increased from 40.78% to 100%; no fragmentation on the clustered index. Note that since we rebuilt the clustered index, all other index were also rebuilt.
  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

HTML5 data-* (custom data attribute)

Goal:

Store custom data with the data attribute on any DOM element and retrieve it. Previously under HTML4 we used to use classes to store custom data, something to the affect of <input class="account void limit-5000 over-4999" /> and then have to parse the data out of the class In a book published by Peter-Paul Koch in 2007, ppk on JavaScript, he explains why and how to use custom attributes to make data more accessible to JavaScript, using name-value pairs. Accessing a custom attribute account-limit=5000 is much easier and more intuitive than trying to parse it out of a class, Plus, what if the class name for example "color-5" has a representative class definition in a CSS stylesheet that hides it away or worse some JavaScript plugin that automatically adds 5000 to it, or something crazy like that, just because it is a valid class name. As you can see there are quite a few reasons why using classes is a bad design and why it was important to define custom data attributes in HTML5.

Syntax:

You define the data attribute by simply prefixing any data item you want to store with any HTML element with "data-". For example to store our customers account data with a hidden input element:

<input type="hidden" data-account="void" data-limit=5000 data-over=4999  />

How to access the data:

account  -     element.dataset.account

limit    -     element.dataset.limit

You can also access it by using the more traditional get/setAttribute method or if using jQuery $('#element').attr('data-account','void')

Browser support:

All except for IE. There is an IE hack around this at http://gist.github.com/362081.

Special Note:

Be AWARE, do not use upper-case when defining your data elements as it is all converted to lower-case when reading it, so:

data-myAccount="A1234"

will not be found when you read it with:

element.dataset.myAccount

Use only lowercase when reading so this will work:

element.dataset.myaccount

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Visual Studio 2010 HTML5

Goal:

Enabling HTML5 validation and  IntelliSense for Visual Studio 2010. By default it is set to XHTML 1.1.

HTML5 support only came included with SP1 of Visual Studio 2010. However since HTML5 is not an official standard as yet and some of the 30 new elements are not suported in all browsers, so only a subset of the entire HTML5 specification is supported; support for both intellisense and validation for HTML5 with SP1.

How to:

After installing SP1 you have to tell Visual Studio to start using the HTML5 schema. Go to Tools -> Options, and then select Text Editor -> HTML -> Validation. Select HTML5 or XHTML5 as the target schema.

Selecting HTML5 in HTML validation options in VS 2010 tools

So start building or converting older Visual Studio projects to HTML5 and CSS3 web applications.

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Adding Output Caching and Expire Header in IIS7 to improve performance

The problem:

Images and other static files will not be cached unless you tell it to. In IIS7 it is remarkably easy to do this.

Web pages are becoming increasingly complex with more scripts, style sheets, images, and Flash on them. A first-time visit to a page may require several HTTP requests to load all the components. By using Expires headers these components become cacheable, which avoids unnecessary HTTP requests on subsequent page views. Expires headers are most often associated with images, but they can and should be used on all page components including scripts, style sheets, and Flash.

Every time a page is loaded, every image and other static content like JavaScript files and CSS files will be reloaded on every page request. If the content does not change frequently why not cache it and avoid the network traffic?!

The solution:

In IIS7 there are two ways to cache content, using the web.config file to set caching for all static content, and in IIS7 itself setting aching by file extension that gives you that extra level of granularity.

Web.config:

In IIS7, Expires Headers can be enabled in the system.webServer section of the web.config file:

  <staticContent>
    <clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="1.00:00:00" />
  </staticContent>

In the above example a cache expiration of 1 day was added. It will be a full day before the content is downloaded from the web server again.

To expire the content on a specific date:

  <staticContent>
    <clientCache cacheControlMode="UseExpires" httpExpires="Sun, 31 Dec 2011 23:59:59 UTC" />
  </staticContent>

This will expire the content on December 31st 2011 one second before midnight.

Issues/Challenges:

Once the file has been set to be cached it wont be updated on the user's browser for the set cache expiration. So be careful here with content that may change frequently, like during development. Typically in development you don't want to cache at all for testing purposes. You could also suffix files with timestamp or versions to force a reload into the user's browser cache.

IIS7 Expire Web Content

Open up your web app in IIS. Open up the sub-folders until you find the folder or file you want to ad an expiration date to. In IIS6 you used to right-click and select properties, no such luck in IIS7, double click HTTP Response. Once the window loads for the HTTP Response Headers, look to the Actions navigation bar to the right, all the way at the top select SET COMMON HEADERS. The Enable HTTP keep-alive will already be pre-selected. Go ahead and add the appropriate expiration header to the file or folder. Note that if you selected a folder, it will apply that setting to all images inside that folder and all nested content, even subfolders.

So, two approaches, depending on what level or granularity you need.

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Free Anti-Virus software that is reliable

I often get this question: "I want a free but good and reliable anti-virus software". I can honestly say that the AVG anti-virus package is not only free, but well supported and I have used it for probably over ten years and never had an issue with neither the software nor with viruses on my machine.

 

 I however also have to add that I think we should support the commercial versions as those folks also have to make a living, and when comparing prices AVG is very competitive. Of course the commercial version offers a whole slew of features that are very useful that the free version does not offer.

You can find their official site here:

http://www.avg.com

The free version can be downloaded from here:

http://download.cnet.com/AVG-Anti-Virus-Free-Edition-2012/3000-2239_4-10320142.html?part=dl-avg_free_us&subj=dl&tag=button

See the list of protection the free version offers as compared to others:

http://free.avg.com/us-en/free-antivirus-download

 Hope this helps. If you know of another great free anti-virus, let me know in this blog.

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

.Net Rounding issue (MidpointRounding)

Issue:

.Net rounding does not work as you would expect. -2.5 rounds to -2 and not -3. What?! Yes! By default .Net uses MidpointRounding.ToEven which will round it to -2. BUT if you round off -3.5 it works as you would expect to -4. If you round off -6.5 you think it would also round off to -7, but you would be wrong, -6! What about 2.5, the default rounds off the 2 and not 3 as you would expect.

So what is going on? You can read more about it at http://msdn.microsoft.com/en-us/library/system.midpointrounding.aspx.

The fix below is to make sure it ALWAYS rounds off the same way.

Fix:

To make sure it consistently rounds off the same way, use the .Net enum MidpointRounding:

var amount = Math.Round(notRoundedDecimalValue, 0, MidpointRounding.AwayFromZero);

This will make sure -2.5, rounds to -3

Some other examples:

base           rounded to 0 decimals after comma

-1.5            -2 (same for both))

-2.5            -3 (default -2)

-3.5            -4 (same for both))

-4.5            -5 (default -4)

-5.5            -6 (same for both))

-6.5            -7 (default -6)

-7.5            -8 (same for both)

1.5            2 (same for both)

2.5            3 (default 2)

6.5            7 (default 6)

So to make sure it consistently rounds of the same way regardless of the number range you are in use:

MidpointRounding.AwayFromZero

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

.Net - find business days

Goal:

Find the business days; i.e. exclude weekends

How to:

Here is some code to get the first business day after or before the weekend. It is surprisingly simple but thought the code may help save folks some time. Just a note that there is no built-in .Net feature to give you public US or other holiday calendar dates, you need to build your own using a table to keep track of public holidays in most situations. Simple enough to do, extend the methods below to query a database or xml or JSON, etc, file with your company or country holiday calendar.

 

    public static class DayOfWeekUtility
    {
        public static DateTime GetFirstBusinessDayAfter(DateTime baseDate)
        {
            var businessDate = baseDate;
            var dayOfWeek = businessDate.DayOfWeek;
           
            if (dayOfWeek == DayOfWeek.Saturday || dayOfWeek == DayOfWeek.Sunday)
            {
                if (dayOfWeek == DayOfWeek.Saturday)
                    businessDate = businessDate.AddDays(2);
                if (dayOfWeek == DayOfWeek.Sunday)
                    businessDate = businessDate.AddDays(1);
            }
            return businessDate;
        }

        public static DateTime GetFirstBusinessDayBefore(DateTime baseDate)
        {
            var businessDate = baseDate;
            var dayOfWeek = businessDate.DayOfWeek;

            if (dayOfWeek == DayOfWeek.Saturday || dayOfWeek == DayOfWeek.Sunday)
            {
                if (dayOfWeek == DayOfWeek.Saturday)
                    businessDate = businessDate.AddDays(-1);
                if (dayOfWeek == DayOfWeek.Sunday)
                    businessDate = businessDate.AddDays(-2);
            }
            return businessDate;
        }

    }

 

 

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

System.Web.Script.Serialization.JavaScriptSerializer - prevent serializing a property

Issue:

Use the .Net JavaScriptSerializer  to serialize an object but due to circular references need to prevent from those properties from being serialized.

Solution:

In order to ignore certain properties from getting serialized, simply add the ScriptIgnoreAttribute attribute to the property:

        [ScriptIgnore]
        public virtual MyClassCausingCircularRefError MyProperty
        {
            get { return _privateField; }
        }

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati
Twitter