Monday, 25 January 2010

Invalid ViewState and WebResource.axd errors

Form submission

ViewState includes a Message Authentication Code (MAC). The MAC is generated using a validation key on the server. When the form is posted back the server compares the MAC in the ViewState with one regenerated on the server. If they differ the ViewState is regarded as invalid.

The value of the MAC can change when:

  • Data in the ViewState has changed (e.g. a hack attempt)
  • Truncated form data (e.g. timeout)
  • Using Server.Transfer can cause it to happen
  • The validation key used to generate the ViewState MAC is different than the key being used to generate the MAC for comparison

Note that the validation key may be different on different servers in a farm. You must take steps to ensure the validation keys match across machines. Validation keys can be different across application pools. Validation keys can change if the application pool restarts (e.g. if the key is set to AutoGenerate).

To avoid MAC mismatches:

  • Don't use the ViewState if you don't need to.
  • Turn off MAC generation by setting enableViewStateMac=false in the page or web.config. NOT RECOMMENDED!
  • Prevent your application pool from restarting by disabling the auto recycle and idle timeout settings in the application pool.
  • Hard-code the MAC validation key so that it's always the same (good for web farms). Hardcode the key in the <machineKey> tag in the machine.config or web.config.

See http://www.developmentnow.com/blog/InvalidViewstate+Or+Unable+To+Validate+Data+Error.aspx for a detailed overview.

Web resources

Similar issues can affect web resources accessed via webresource.axd. Requests to web resources will include a ‘d’ parameter (decryption key?). As such it is subject to the same issues with the key changing as above. This key will be an encrypted version of the web resource identifier used to retrieve the resource from the appropriate assembly.

One way in which web resources can be used is in Ajax or other JavaScript enabled web controls by adding the [WebResource] attribute to reference JavaScript files stored as resources. When the control is rendered on the page a reference to the script file will be generated as a request to webresource.axd

Also be aware of ScriptResource.axd (which contains all of the client-side JavaScript for Ajax) in web.config files.

Problems with web resources etc can give rise to the “Padding is invalid and cannot be removed” errors.

See http://msdn.microsoft.com/en-us/library/system.web.ui.webresourceattribute.aspx and http://msdn.microsoft.com/en-us/library/system.web.handlers.scriptresourcehandler.aspx.

Wednesday, 13 January 2010

How to export details of scheduled tasks

Run the following command to export all scheduled tasks to CSV format:

schtasks /query /FO CSV /V > c:\output.csv

This can then be opened with Excel. Alternatively, to make a copy/backup of all the scheduled tasks on a machine right-click on the %systemroot%\Tasks folder and copy it. Paste it where you want.

Wednesday, 13 January 2010

Tuesday, 12 January 2010

Rebuilding execution plans

To force SQL Server to rebuild its execution plans for a particular database run the following SQL:

DECLARE @intDBID INTEGER SET @intDBID = 
(SELECT dbid FROM master.dbo.sysdatabases WHERE name = 'DatabaseNameHere') DBCC FLUSHPROCINDB (@intDBID)

To rebuild execution plans for all databases run the following SQL:

DBCC FREEPROCCACHE

You can see the execution plans for a procedure by using the SET command:

USE [DatabaseNameHere]
GO

SET SHOWPLAN_ALL OFF 
GO

EXEC [WidgetQueries_RecentlyAddedContent] 0
GO

You can also force a recompilation for a specific procedure or trigger using sp_recompile stored procedure:

sp_recompile [ @objname = ] 'object'

There are many other options. Check the documentation for details.

Wednesday, 30 December 2009

Restore a database using TSQL

To restore a database use the following SQL:

USE [tempdb]
ALTER DATABASE [DatabaseName]

SET SINGLE_USER WITH
ROLLBACK IMMEDIATE
GO

RESTORE DATABASE [DatabaseName]
FROM DISK = 'C:\BackupName.BAK'
WITH MOVE 'MDF_logical_name' TO 'C:\MDFName.mdf',
MOVE 'LDF_logical_name' TO 'C:\LDFName.ldf'
GO

ALTER DATABASE [DatabaseName] SET MULTI_USER
GO

Note that this puts the database into single user mode first (i.e. it kicks off other users). Don’t forget the USE [tempdb] statement or you may find the database still in use and the restore may fail. If you’re doing a straight restore you can get the logical filenames etc. from the backup file:

RESTORE FILELISTONLY FROM DISK = 'C:\BackupName.BAK'
GO

Wednesday, 16 December 2009

Keyboard shortcuts for Remote Desktop sessions

  • CTRL+ALT+END: Open the Microsoft Windows NT Security dialog box (CTRL+ALT+DEL)
  • ALT+PAGE UP: Switch between programs from left to right (CTRL+PAGE UP)
  • ALT+PAGE DOWN: Switch between programs from right to left (CTRL+PAGE DOWN)
  • ALT+INSERT: Cycle through the programs in most recently used order (ALT+TAB)
  • ALT+HOME: Display the Start menu (CTRL+ESC)
  • CTRL+ALT+BREAK: Switch the client computer between a window and a full screen
  • ALT+DELETE: Display the Windows menu
  • CTRL+ALT+Minus sign (-): Place a snapshot of the entire client window area on the Terminal server clipboard (ALT+PRT SC)
  • CTRL+ALT+Plus sign (+): Place a snapshot of the active window in the client on the Terminal server clipboard (PRT SC)

User-defined Functions in SQL Server

User-defined functions (UDFs) encapsulate logic for use in other queries. Views are limited to a single SELECT statement but user-defined functions can have multiple SELECT statements.

There are basically 3 categories of UDF:

  • Scalar-valued function
    • Returns a single, scalar value.
    • Can be used as column name in queries.
    • Can contain an unlimited number of statements as long as only one value is returned.
  • Inline function
    • Returns a variable of data type table.
    • Can only contain a single SELECT statement.
    • The structure of the returned value is generated from the columns that compose the SELECT statement.
    • A table variable need not be explicitly declared and defined.
  • Table-valued function
    • Can contain any number of statements that populate the table variable to be returned.
    • Useful when you need to return a set of rows.
    • A table variable must be explicitly declared and defined.
    • An advantages over a view is that the function can contain multiple SQL statements whereas a view is composed of only one statement.

Differences between Stored Procedures and UDFs:

  • UDF can be used in SQL statements whereas SPs can’t.
  • UDFs that return tables can be treated as another rowset and can be used in JOINs.
  • Inline UDF's can be thought of as views that take parameters and can be used in JOINs etc.

Monday, 14 December 2009

Model-View-ViewModel (MVVM) pattern

MVVM is gaining considerable traction in the WPF and Silverlight communities. The MVVM pattern can be said to be a specialisation of Fowler’s Presentation Model pattern.

The essence of a Presentation Model is of a fully self-contained class that represents all the data and behavior of the UI window, but without any of the controls used to render that UI on the screen. A view then simply projects the state of the presentation model onto the glass.

There is also some similarity with the Model-View-Presenter (MVP) pattern, with the ViewModel being roughly analogous to the Presenter.  However, unlike MVP the ViewModel doesn’t need a reference to the View – the view uses data binding to be made aware of changes. The ViewModel and not the View performs all modifications made to the model data.

Some features of MVVM:

  • View classes are unaware of Model classes
  • ViewModel and Model classes are unaware View classes (the ViewModel mustn’t assume types of rendering in the View  - e.g. that a button exists)
  • Model classes are unaware of ViewModel and View classes
  • ViewModel classes are aware of Model classes
  • View classes are aware of ViewModel classes

To summarise:

Aware of View Aware of Model Aware of ViewModel
View N/A No Yes
Model No N/A No
ViewModel No Yes N/A

Data binding facilitates loose coupling between the View and the ViewModel. It also supports a standardised input validation model.

The data is typically implemented as properties on the ViewModel. The View consumes that data via data binding. Application logic is typically implemented as methods on the ViewModel that the View can invoke through commanding.

A possible weakness with MVVM in Silverlight applications is the lack of support for Commands.

The following are the differences between Silverlight and WPF regarding commanding:

  • Routed commands are not available in Silverlight. However, the ICommand interface is available in Silverlight, allowing developers to create their own custom commands. The Composite Application Library provides the DelegateCommand and CompositeCommand classes to simplify command implementation. For more information, see the Commands technical concept.
  • In WPF, controls can be hooked up to commands through their Command property. By doing this, developers can declaratively associate controls and commands. This also means a control can interact with a command so that it can invoke the command and have its enabled status automatically updated. Silverlight controls do not currently support the Command property. To help work around this issue, the Composite Application Library provides an attached property-based extensibility mechanism that allows commands and controls to be declaratively associated with each other. For more information, see "Using Commands in Silverlight Commands" in the Commands technical concept.
  • There is no input gesture or input binding support in Silverlight.

http://msdn.microsoft.com/en-us/library/dd458872.aspx

ViewModel classes are easy to test, taking key logic out of the dreaded code behind files.

I need to check out a few things:

See also http://andysonlinenotes.blogspot.com/2010/06/stuff-i-should-be-interested-in.html