Tag: Dynamic Data

Error: AjaxControlToolkit requires ASP.NET Ajax 4.0 scripts. Ensure the correct version of the scripts are referenced. If you are using an ASP.NET ScriptManager, switch to the ToolkitScriptManager in AjaxControlToolkit.dll.

I got this error message after upgrading my ASP.NET Dynamic Data site to ASP.NET 4.5. The exception was thrown each time an entity with a data annotation referencing a field or filter control was shown. I searched for days to find out what was wrong, including numerous references to replace the ScriptManager control with the ToolkitScriptManager, but that just wasn’t the issue. So, what I finally did was to create a new blank ASP.NET Web Application in Visual Studio 2012. I wanted it somewhat empty, so I could the bits and pieces from the Ajax Control Toolkit sample site, and work out when things went wrong. At first it just didn’t. I had a bare bone application with just the AutoComplete.aspx and the DefaultMaster.master files, as well as the Ajax Control Toolkit installed from NuGet. Worked just fine. Then I started adding the script related bits from my Dynamic Data project, but to no avail. Finally, I went over the Bin folders for a comparison between the two, and after listing the ones that were “extra” in the Dynamic Data project, I double-checked if they were all needed. Turns out the Microsoft.ScriptManager.MSAjax.dll assembly was no longer used by the web application project, so I deleted it. Damned, that did the trick; unbelievable.

Advertisements

Invalid postback or callback argument…

I started getting this error message:

Invalid postback or callback argument. Event validation is enabled using in configuration or in a page. For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them. If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.

I am once again working on my ASP.NET Dynamic Data Entities web application (updated to ASP.NET 4.5 and Unity 3 beta), and after adding localization and applying the MVP pattern to the page and field templates, the above error started occurring. Now, I Bing’ed it, but none of the suggestions I came across did anything to alleviate the problem. I had the issue with the ListDetails.aspx Dynamic Data page template every time I used the pager associated with the GridView control, and I begun by looking at the recent application of the MVP pattern, but that didn’t get me any closer to a solution. I then started looking at how I localized the page template and much to my surprise it was caused by disabling viewstate (ViewStateMode="Disabled") for the UpdatePanel control, in which the GridView was contained.

The solution was to enable viewstate (removing the attribute ViewStateMode="Disabled") for the UpdatePanel control and applying it to the QueryExtender control associated with the GridView, as well as all of the controls in the div element with a class of DD.

UPDATE (March 30th, 2013):

Turns out this causes too much hassle with view state turned off, so I have turned it back on, and added a Response.Redirect in the event handlers for changing languages. It’s an extra roundtrip, but it is so much more elegant, especially seen form the users perspective.

System.ArgumentNullException: Value cannot be null. Parameter name: principal

I am working on my Dynamic Data website, or rather web application, in VS 2012 RC, and after reading Dynamic Data Unleashed, http://www.amazon.com/ASP-NET-Dynamic-Data-Unleashed-Oleg/dp/0672335654/ref=sr_1_1?ie=UTF8&qid=1342425509&sr=8-1&keywords=dynamic+data, I picked up a few nice tricks, including how to secure your data at the entity level. So, I copied some of the sample code across to my solution, and once everything was building nicely, I started testing the new bits. First access to an entity worked just fine, but any other attempt to access the same entity or any other entity for that resulted in this error:

System.ArgumentNullException: Value cannot be null. Parameter name: principal

Rather annoying, since the sample code worked just fine. It turns out that the methods for checking if the current user is allowed to read a specific entity received a principal that was null. Here is the signature of one of the methods:

public override bool CanRead(IPrincipal principal)

The method is called from another method that checks if a column should be scaffolded/shown to the current user.

private bool IsScaffoldable(MetaColumn column)

This method was calling the CanRead method passing HttpContext.Current.User. This works just fine when you use the ASP.NET Development Server when testing inside Visual Studio. However, if you use IIS Express, it does not work; the error described is consistent. So, I tried the full IIS, but the same thing happened.

It turns out that the issue is with the Integrated pipeline mode, which is new to IIS 7 and later. HttpContext.Current isn’t always available, as you can find more evidence of by Bing’ing it. The solution in my case was to use Thread.CurrentPrincipal instead.

Invalid Animation definition for TargetControlID=”…”: The ‘Animations’ start tag on line x position x does not match the end tag of ‘OnHide’. Line x, position x.

I was adding filters (grabbed from “Dynamic Data Steve’s” website here, http://csharpbits.notaclue.net/2010/11/five-cool-filters-for-dynamic-data-4.html) to my Dynamic Data website and the Autocomplete filter makes use of the AJAX Control Toolkit, http://ajaxcontroltoolkit.codeplex.com/. Steve has done a fantastic job over the years with customizing many aspects of Dynamic Data, so I was a little sad to see that I got this error Invalid Animation definition for TargetControlID=”…”: The ‘Animations’ start tag on line x position x does not match the end tag of ‘OnHide’. Line x, position x., when trying to view a table/entity in the ListDetails view. After quite a thorough investigation, it turned out it was because of the presence of the VisualStudioDesignTime key you can add to your appSettings element in web.config.
<appSettings>
     VisualStudioDesignTime:Enabled" value="true" />
</appSettings>
It is used by the new Page Inspector, which you can find information about here, http://blogs.msdn.com/b/webdevtools/archive/2011/09/22/page-inspector-for-visual-studio-11-developer-preview.aspx. Remove the add element/tag and the error goes away.

—-UPDATE—-

After updating to Visual Studio 2012 RC, I now get the error whether or not the VisualStudioDesignTime:Enabled key is present or not. However, if I remove the 4 comments within the opening and closing ajaxToolkit:AutoCompleteExtender tags, everything works just fine, even with the VisualStudioDesignTime:Enabled key present. 🙂

No key property values were found during an update or delete operation. Check to ensure that key properties specified as binding expressions are available to the data source.

I was working on a Dynamic Data website and everything was working great. Then I decided to add some of the features from a standard ASP.NET Web Application project, including the CSS and Login functionality to the Dynamic Data project. This worked well too. Then I reworked the routing to use the ListDetails.aspx view only, and after a while I started getting this error, No key property values were found during an update or delete operation. Check to ensure that key properties specified as binding expressions are available to the data source., but only for some tables. Obviously, the first thing to check was the Entity Framework model, to see what those tables had in common and what they didn’t have in common with the other tables. I just could not find anything there. I got the error when doing an inline update in the GridView on the ListDetails view, not if I used the FormView for updating, so I scrapped the idea of the data model being at fault. I then also found that the Select functionality in the Gridview control did not update the FormView control with the selected row, which it did previously. Now I was on to something; the view state had been turned off on the ContentPlaceHolder control in the master page. I’m not entirely sure how this caused the error, but once it was turned back on, everything worked as expected.

The Controls collection cannot be modified because the control contains code blocks (i.e. <% … %>).

I am developing a data entry application in Visual Studio 11 Beta, by using the ASP.NET Dynamic Data Entities Web Application project template. I decided to add the ASP.NET Menu control to the Site.master master page, but then I started getting this error, The Controls collection cannot be modified because the control contains code blocks (i.e. <% … %>).

While the error more or less tells you where things go wrong, the stack trace looks like this:

[HttpException (0x80004005): The Controls collection cannot be modified because the control contains code blocks (i.e. <% … %>).]
   System.Web.UI.ControlCollection.Add(Control child) +9719987
   System.Web.UI.WebControls.MenuRendererStandards.AddStyleBlock() +61
   System.Web.UI.WebControls.MenuRendererStandards.PreRender(Boolean registerScript) +89
   System.Web.UI.WebControls.Menu.OnPreRender(EventArgs e) +238
   System.Web.UI.Control.PreRenderRecursiveInternal() +83
   System.Web.UI.Control.PreRenderRecursiveInternal() +155
   System.Web.UI.Control.PreRenderRecursiveInternal() +155
   System.Web.UI.Control.PreRenderRecursiveInternal() +155
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +974

Okay, so the rendering isn’t quite working. I did a quick search for this error and found that a lot of developers have had this issue over the years, so definitely nothing to do with the .NET Framework 4.5 or VS11 Beta. What fixed the issue was to move the script element, <script src="<%: ResolveUrl("~/Scripts/modernizr-2.0.6-development-only.js") %>"></script> out of the head element and into the body element. Very simple fix…

Dynamic Data – First text field focus

The Insert page template that is created for you when you create a new ASP.NET Dynamic Data Entities Web Application project, does not set focus to the first field in the template. By adding the following code (which can be simplified I’m sure) to the partial Insert class, you can achieve just that:

protected void Page_LoadComplete(object sender, EventArgs e)
{
    Text_EditField usrCtl = Utility.FindControl(FormView1.Controls);

    TextBox txtBox = (TextBox) usrCtl.FindControl("TextBox1");

    if (txtBox != null && !txtBox.ReadOnly)
        txtBox.Focus();
}

The static generic FindControl method was found here, http://erikporter.com/Blog/asp-net-findcontrol-recursive-with-generics.

ASP.NET Dynamic Data – Hide/show table or column

I am once again working with a helper project, which I need to have several people add data to a database, used with an upcoming release. Why use Dynamic Data? Well, it is simple and easy to get going, once you have your data model, for which I generally use the Entity Framework. Anyway, I had forgotten a few of the data annotations you can use with the metadata, including how to hide or show a table or column. However, it is really simple, once you look at the System.ComponentModel.DataAnnotations namespace.

The ScaffoldTable and ScaffoldColumn attributes can be used for this purpose, as shown here:

[ScaffoldTable(true)]
[MetadataType(typeof(Culture_Metadata))]
public partial class Culture
{
    internal class Culture_Metadata
    {
        [ScaffoldColumn(false)]
        public bool Id { set; get; }
    }
}

The table Culture is shown whereas the column Id isn’t shown, when using the scaffolding feature of Dynamic Data.

Localizing Filter Controls

I am fully localizing a new ASP.NET 4 Dynamic Data web site, and there’s more than meets the eye to doing so. I found that the Boolean filter User Control would not update correctly, when switching languages; it would keep the items (All, True, and False) in the previously selected culture. So, I had a look at the code, after adding the localization calls (no, I don’t localize the exceptions ;-)):

Protected Sub Page_Init(ByVal sender As Object, ByVal e As EventArgs)
    If Not Column.ColumnType.Equals(GetType(System.Boolean)) Then
        Throw New InvalidOperationException(String.Format("A boolean filter was loaded for column '{0}' but the column has an incompatible type '{1}'.", Column.Name, Column.ColumnType))
    End If

    If Not Page.IsPostBack Then
        DropDownList1.Items.Add(New ListItem(GetGlobalResourceObject("Strings", "AllItems"), String.Empty))

        If Not Column.IsRequired Then
            DropDownList1.Items.Add(New ListItem(GetGlobalResourceObject("Strings", "NotSet"), NullValueString))
        End If

        DropDownList1.Items.Add(New ListItem(GetGlobalResourceObject("Strings", "True"), Boolean.TrueString))
        DropDownList1.Items.Add(New ListItem(GetGlobalResourceObject("Strings", "False"), Boolean.FalseString))
        ' Set the initial value if there is one
        Dim initialValue As String = DefaultValue

        If Not String.IsNullOrEmpty(initialValue) Then
            DropDownList1.SelectedValue = initialValue
        End If
    End If
End Sub

Well, that didn’t take too long to work out; the items are only added to the DropDownList control on the initial page view. Okay, so I modified the code:

Protected Sub Page_Init(ByVal sender As Object, ByVal e As EventArgs)
    If Not Column.ColumnType.Equals(GetType(System.Boolean)) Then
        Throw New InvalidOperationException(String.Format("A boolean filter was loaded for column '{0}' but the column has an incompatible type '{1}'.", Column.Name, Column.ColumnType))
    End If

    DropDownList1.Items.Add(New ListItem(GetGlobalResourceObject("Strings", "AllItems"), String.Empty))

    If Not Column.IsRequired Then
        DropDownList1.Items.Add(New ListItem(GetGlobalResourceObject("Strings", "NotSet"), NullValueString))
    End If

    DropDownList1.Items.Add(New ListItem(GetGlobalResourceObject("Strings", "True"), Boolean.TrueString))
    DropDownList1.Items.Add(New ListItem(GetGlobalResourceObject("Strings", "False"), Boolean.FalseString))

    If Not Page.IsPostBack Then
        ' Set the initial value if there is one
        Dim initialValue As String = DefaultValue

        If Not String.IsNullOrEmpty(initialValue) Then
            DropDownList1.SelectedValue = initialValue
        End If
    End If
End Sub

Now that should work, but it doesn’t… Final thing to fix, is to disable view state for the user Control, so I added EnableViewState=”false” to the Control directive in the markup, like this:

<%@ Control Language="VB" CodeFile="Boolean.ascx.vb" Inherits="BooleanFilter" EnableViewState="false" %> 

That works 🙂

An entry with the same key already exists.

I came across this error message the other day, working on a new ASP.NET 4 Dynamic Data Web site, and I was baffled as to what the problem was. I started troubleshooting and worked out that it happened with the Edit and Insert views. Okay, then I tried editing a row in all of my entities, just to see if any of them would work. I only had 8 tables at the time, so that wasn’t exactly a time consuming exercise. Much to my surprise, I was able to open one of the entities in the Edit view, but why so, when the others failed? I then looked at the number of columns exposed in the view and the entity that, for which the Edit view worked, only had a single column displayed. Then I tried hiding (ScaffoldColumn(False)) all columns but one in the metadata class for one of the partial entity classes, and then that worked. Now that worked, but it seemed a little silly, so I wasn’t going to let that beat me. After a while, I worked out that it happened when more than one column, displayed in the same type of UI control, or rather in this case a TextBox control, was used. So, I checked the associated Field Templates, and it was the validators attached to the TextBox control in the Text_Edit.ascx field control. Then it finally dawned upon me, it had to with the client ID’s of the controls. I looked at my web.config, in which I had this element:

masterPageFile="..." pageBaseType="..." clientIDMode="Static" />

Sure enough, removing the new ASP.NET 4.0 clientIDMode attribute and value fixed it. See Rick Strahl’s excellent article on this property, http://west-wind.com/weblog/posts/54760.aspx.