views:

62

answers:

2

All forms work on my site except this one, when I submit this form I get the following error:

Server Error in '/**' Application. Validation of viewstate MAC failed. If this application is hosted by a Web Farm or cluster, ensure that 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. 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 configuration specifies the same validationKey and validation algorithm. AutoGenerate cannot be used in a cluster.

Source Error:

[No relevant source lines]

Source File: c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\alphapack\b9be7787\4e4ee265\App_Web_al4orjqe.6.cs Line: 0

Stack Trace:

[HttpException (0x80004005): Unable to validate data.]
System.Web.Configuration.MachineKeySection.GetDecodedData(Byte[] buf, Byte[] modifier, Int32 start, Int32 length, Int32& dataLength) +289 System.Web.UI.ObjectStateFormatter.Deserialize(String inputString) +140

[ViewStateException: Invalid viewstate. Client IP: 10.10.0.103 Port: 2332 User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.2.8) Gecko/20100722 Firefox/3.6.8 ( .NET CLR 3.5.30729) ViewState: /wEPDwUJNjMxODAxMzg2D2QWAmYPZBYGAgcPDxYEHghDc3NDbGFzcwUKbmF2QnV0dG9uTx4EXyFTQgICZGQCEQ8PFgIeBFRleHQFD0FkZCBOZXcgUHJvZHVjdGRkAhMPZBYCAgEPZBYEAgUPEGQPFhQCAQICAgMCBAIFAgYCBwIIAgkCCgILAgwCDQIOAg8CEAIRAhICEwIUFhQQBQRDYXJzBQE5ZxAFF8KgwqDCoMKgwqDCoMKgwqBGZXJyYXJpBQIxMWcQBSvCoMKgwqDCoMKgwqDCoMKgwqDCoMKgwqDCoMKgwqDCoEJyb2tlbiBPbmVzBQIxOGcQBTnCoMKgwqDCoMKgwqDCoMKgwqDCoMKgwqDCoMKgwqDCoMKgwqDCoMKgwqDCoMKgwqBObyBXaGVlbHMFAjIyZxAFOsKgwqDCoMKgwqDCoMKgwqDCoMKgwqDCoMKgwqDCoMKgwqDCoMKgwqDCoMKgwqDCoE5vIFdpbmRvd3MFAjIzZxAFLcKgwqDCoMKgwqDCoMKgwqDCoMKgwqDCoMKgwqDCoMKgRnVsbHkgV29ya2luZwUCMTlnEAUWwqDCoMKgwqDCoMKgwqDCoExhbWJvcwUCMTBnEAUmwqDCoMKgwqDCoMKgwqDCoMKgwqDCoMKgwqDCoMKgwqBZZWxsb3cFAjE1ZxAFI8KgwqDCoMKgwqDCoMKgwqDCoMKgwqDCoMKgwqDCoMKgUmVkBQIxNmcQBSTCoMKgwqDCoMKgwqDCoMKgwqDCoMKgwqDCoMKgwqDCoEJsdWUFAjE3ZxAFBkhvdXNlcwUCMTJnEAUYwqDCoMKgwqDCoMKgwqDCoE1hbnNp...]

[HttpException (0x80004005): Validation of viewstate MAC failed. If this application is hosted by a Web Farm or cluster, ensure that configuration specifies the same validationKey and validation algorithm. AutoGenerate cannot be used in a cluster.]
System.Web.UI.ViewStateException.ThrowError(Exception inner, String persistedState, String errorPageMessage, Boolean macValidationError) +106
System.Web.UI.ViewStateException.ThrowMacValidationError(Exception inner, String persistedState) +14
System.Web.UI.ObjectStateFormatter.Deserialize(String inputString) +242
System.Web.UI.ObjectStateFormatter.System.Web.UI.IStateFormatter.Deserialize(String serializedState) +4
System.Web.UI.Util.DeserializeWithAssert(IStateFormatter formatter, String serializedState) +37 System.Web.UI.HiddenFieldPageStatePersister.Load() +207 System.Web.UI.Page.LoadPageStateFromPersistenceMedium() +105 System.Web.UI.Page.LoadAllState() +43 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +6785
System.Web.UI.Page.ProcessRequest(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +242
System.Web.UI.Page.ProcessRequest() +80 System.Web.UI.Page.ProcessRequestWithNoAssert(HttpContext context) +21
System.Web.UI.Page.ProcessRequest(HttpContext context) +49
ASP.admin_productcats_aspx.ProcessRequest(HttpContext context) in c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\alphapack\b9be7787\4e4ee265\App_Web_al4orjqe.6.cs:0 System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +181 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +75

Code is:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections;

namespace ********
{
    public partial class productAdd : System.Web.UI.Page
    {
        // Navigation stuff
        Category tree = null;
        Dictionary<int, Category> dict = new Dictionary<int, Category>();
        ArrayList dicIndexes = new ArrayList();

        // Validate stock count
        protected void validateStockCount(object source, ServerValidateEventArgs args)
        {
            try
            {
                int theCount = Convert.ToInt32(stockCount.Text);
                if (theCount < 0)
                {
                    args.IsValid = false;
                }
                else
                {
                    args.IsValid = true ;
                }
            }
            catch
            {
                args.IsValid = false ;
            }               
        }

        protected void Page_Load(object sender, EventArgs e)
        {

            limitedStock.Attributes.Add("onclick", "showHide()");

            // Action of the page
            string pageAction = Request.QueryString["action"];

            using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["LocalSqlServer"].ToString()))
            {
                cn.Open();

                // Posted a form to self
                if (IsPostBack)
                {
                    // Validate data
                    Page.Validate();
                    if (Page.IsValid)
                    {
                        // New category
                        if (pageAction == "new")
                        {
                            // Get form vals
                            int selectedCatID = int.Parse(parent.SelectedItem.Value.ToString());
                            string prodName = productName.Text;
                            bool isLim = limitedStock.Checked;
                            //int prodStockCount = int.Parse(stockCount.ToString());
                            int prodStockCount = 3;
                            bool isForSale = !hidden.Checked;

                            using (SqlCommand cmd = new SqlCommand("INSERT INTO tblProducts (productName, isForSale, categoryID, isLimitedStock, stockCount, description, weightKG, basePrice, dateCreated) VALUES (@p_name, " + isForSale + ", " + selectedCatID + ", " + isLim + ", " + prodStockCount + ", '', 0, 0, getDate())", cn))
                            {
                                cmd.Parameters.Add("@p_name", SqlDbType.VarChar, 255).Value = prodName;
                                cmd.ExecuteNonQuery();
                            }
                        }

                    }

                }
                else
                {
                    // Load the menu structure
                    tree = navigation.loadMenuData(cn, tree, dict, dicIndexes);
                    tree.loadToListBox(dict, dicIndexes, parent);
                }
            }
        }
    }
}

My aspx page:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="productAdd.aspx.cs" Inherits="********.productAdd"
    title="Add a Product"
    MasterPageFile="../MasterPages/AdminMaster.master"
%>

<asp:content id="Content2" contentplaceholderid="headContent" runat="server">
<SCRIPT LANGUAGE="JavaScript">

    function IsNumeric(input) {
        return !isNaN(parseInt(input));
    }
    function validateStock(oSrc, args) {
        // Required
        if (document.getElementById("<%=limitedStock.ClientID  %>").checked == false) {
            args.IsValid = true;
        }
        // Check if numeric
        else if (IsNumeric(args.Value) == true) {
            args.IsValid = !(parseInt(args.Value) < 0);
        } else {
        args.IsValid = false;
        }
    }
    function showHide() {

        var stockTable = document.getElementById("stockOnOff");

        if (document.getElementById("<%=limitedStock.ClientID  %>").checked) {
            stockTable.style.display = "block";
        } else {
            stockTable.style.display = "none";
        }
    }
</SCRIPT>
</asp:content>

<asp:content id="Content1" contentplaceholderid="mainContent" runat="server">

    <form runat="server" action="productCats.aspx?action=new&mid=2">
        <div class="subHead">Basic Details</div>
        <table class="settingTable">
            <tr>
                <td colspan="2"><b>Product Name</b></td>
            </tr>
            <tr>
                <td>
                    <asp:TextBox ID="productName" runat="server" CssClass="tbox"></asp:TextBox>
                    <asp:RequiredFieldValidator runat="server"                         
                              id="ValidatorName"
                              ControlToValidate="productName"
                              ErrorMessage="You need to enter a product name"
                              display="Dynamic" />
                </td>
            </tr>
            <tr>
                <td colspan="2"><b>Category</b></td>
            </tr>
            <tr>
                <td>
                    <asp:ListBox SelectionMode="Single" Rows="8" id="parent" runat="server" CssClass="tbox widebox">
                        <asp:ListItem Selected="True" Text="Top Level" Value="0"></asp:ListItem>
                    </asp:ListBox>
                    <asp:RequiredFieldValidator runat="server"
                              id="RequiredFieldValidator1"
                              ControlToValidate="parent"
                              ErrorMessage="You need to select a parent"
                              display="Dynamic" />
                </td>
            </tr>
        </table>

        <div class="subHead">Stock Options</div>
        <table class="settingTable">
            <tr>
                <td colspan="2"><b>Limited Stock</b></td>
            </tr>
            <tr>
                <td width="50" align="center"><asp:CheckBox ID="limitedStock" runat="server" /></td>
                <td>If checked this product will have a limited stock</td>
            </tr>
        </table>
        <table class="settingTable" id="stockOnOff" style="display:none;">
            <tr>
                <td colspan="2"><b>Stock Count</b></td>
            </tr>
            <tr>
                <td>
                    <asp:TextBox ID="stockCount" runat="server" CssClass="tbox smallBox"></asp:TextBox>
                    <asp:CustomValidator id="stockValidator" runat=server 
                        ControlToValidate = "stockCount"
                        ErrorMessage = "Enter a value of at least 0"
                        ValidateEmptyText="true"
                        ClientValidationFunction="validateStock" >
                    </asp:CustomValidator>
                </td>
            </tr>
        </table>

        <div class="subHead">Other</div>        
        <table class="settingTable">
            <tr>
                <td colspan="2"><b>Hide</b></td>
            </tr>
            <tr>
                <td width="50" align="center"><asp:CheckBox ID="hidden" runat="server" /></td>
                <td>If checked, the product will be hidden for visitors</td>
            </tr>

        </table>

        <asp:Button id="id" text="Add Product" runat="server" />

    </form>



</asp:content>
A: 

Found this link that appears to describe your problem. It says to update .NET.

http://blogs.msdn.com/b/tom/archive/2008/03/14/validation-of-viewstate-mac-failed-error.aspx

LCountee
thanks for link, none of that seems to work though, I am using net 3.5
Tom Gullen
No problem. I'll be interested to see what the fix is.
LCountee
+2  A: 

What you need to do is add a MachineKey to your web.config, you can use this tool to generate the keys

http://aspnetresources.com/tools/machineKey

I get this occasionally, and it was when I configured the application pool to use 2 or more processes. Because each request can come back to any of the processes, it needs the same MachineKey to decode the viewstate information.

Sample

<system.web> 
  <machineKey validationKey="abc" decryptionKey="xyz" validation="SHA1" decryption="AES" />
</system.web>
Jason Jong
Still failing unfortunatly!
Tom Gullen
Are you posting it back to the same page, ie you've specified the action in the form. If your posting to another page, that is why the viewstate will not validate. Add to your productscat.aspx.vb the directive `<%@ Page EnableViewStateMac="false"%>`. This is not secure, but should work
Jason Jong
Yep, posting to another page when looking at your code
Jason Jong