Modify And Save an EF EntityDataSource Bound Entity From Code Behind

If you're using databound controls (e.g. FormView) and binding them to an EntityDataSource you might want to be able to modify (and save) the underlying entity from code. For example, if you have a Question entity bound to a FormView via an EntityDataSource you might want a button to allow the use to vote up or down the question (like StackOverflow for example). To be able to do this without extra trips to the database, the first thing we need to do is get hold of the EF ObjectContext that the EntityDataSource is using.

        // Context that we can use for code-behind operations
        ObjectContext questionObjectContext = null;


        protected void QuestionEntityDataSource_ContextCreated(object sender, EntityDataSourceContextCreatedEventArgs e)
        {
            questionObjectContext = e.Context;
        }

When the QuestionEntityDataSource creates it's context, we take a reference to it in our private field questionObjectContext.

Now in the button click we can up-vote the question:

 

        protected void btnVoteUp_Click(object sender, EventArgs e)
        {
            // force a databind to ensure we have a DataItem in the FormView        
            FormView1.DataBind();

            // Get the actual entity represented by the FormView
            Question questionToUpdate = FormView1.DataItem.WrappedEntity<Question>();

            // Vote-up
            questionToUpdate.VoteScore++;
           
            // using our 'copy' of the EntityDataSource ObjectContext, save the changes
            questionObjectContext.SaveChanges(true);
           
            // Force rebind of FormView to ensure newest data displayed
            FormView1.DataBind();                     
        }

This method feels like a bit of a hack, but ideally you would provide a client-side AJAX version, only if JavaScript is disabled on the client do we use this server-side up-vote.

SHARE:

Accessing Entity Framework Entities In EntityDataSource Data-Bound Controls

If using ASP.NET EntityDataSource and databound controls you may need to access the actual entity object being represented in the control, e.g. a data row in a table or a single entity in a FormView. The actual entity is not readily available however as it is automatically wrapped in a System.Web.UI.WebControls.EntityDataSourceWrapper which is not accessible. The extension method below allows you to gain access to the strongly typed, underlying entity. It is based on the article by Diego Vega which explains the wrapping behaviour in more detail. 

 /// <summary>
/// Gets the actual EF entity object that is being wrapped and databound.
/// </summary>
/// <example>
/// Advert ad = myFormView.DataItem.WrappedEntity<Advert>();
/// (where myFormView is databound to EntityDataSource returning Advert entity)
/// </example>
static class WrappedEFEntityExtensions
{
    public static TEntity WrappedEntity<TEntity>(this object dataItem) where TEntity : class
    {
        var entity = dataItem as TEntity;

        if (entity != null)
            return entity;

        var typeDescriptor = dataItem as ICustomTypeDescriptor;

        if (typeDescriptor != null)
            return (TEntity)typeDescriptor.GetPropertyOwner(null);

        return null;
    }
}

SHARE:

Asp.net AJAX service proxy intellisense in external js

If you have service reference (e.g. to an AJAX Enabled WCF Service) in your ScriptManager (or ToolkitScriptManager):

<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
    <Services>
        <asp:ServiceReference Path="~/MotoService.svc" />
    </Services>
</asp:ToolkitScriptManager>

and your are using an external JavaScript file you can enable JavaScript intellisense by adding the following 2 lines to the top of your .js (replacing ~/MotoService.svc with the path to your own service):

/// <reference name="MicrosoftAjax.js" />
/// <reference path="~/MotoService.svc" />

 

SHARE:

JavaScript Breakpoints Not Working In Visual Studio 2008

This can happen, sometimes fixed by re-installing VS or installing VS 2008 SP1. In this case it seems Javascript breakpoints do not seem to work in Visual Studio 2008 when Silverlight debugging is enabled, if you un-check the Silverlight option in the debuggers section, the JavaScript breakpoint will now be hit. Not sure if it's by design or a bug...

 

SHARE:

Quickly Take Down an ASP.NET Web Site

If you need to temporarily take down an ASP.NET (2.0+) web site you can simply add a file called app_offline.htm to the root of the site. The content of the app_offline.htm could contain a message such as "Site currently undergoing maintenance" or similar.

When you add the file to the root, the server unloads the app domain, when the file is remove (or renamed for example) the next request that comes in will restart the app domain, etc...

SHARE:

Maintaining Basic State With jQuery And CSS

When working on the client, you may have a number of HTML elements that have some form of logical state, e.g. coins (heads/tails), cards (face up/down), importance (high, medium, low), etc.

You could declare a variable for each element (or an array); when the use changes the state you update the variable representing the elements state and perform any UI changes.

An alternative to this which removes the need for additional variables is to represent the state of the element by which CSS classes are currently added to it.

The example below (view live example) shows one way to achieve this using jQuery. It represents a number of simulated coins and if each coin's state is heads or tails.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Maintaining basic state with jQuery and CSS</title>

    <script type="text/javascript" src="jquery-1.3.2.js"></script>

    <script type="text/javascript">
        $(document).ready(function() {
            $("#btnClick").click(function() {
                /* Select every element that has the CSS class coin applied
                   and iterate using the each function */
                $(".coin").each(function() {
                    /* Check the each element to see if it has a tails or heads
                       css class, and 'flip' the class and the text from T->H */
                    if ($(this).hasClass("heads"))
                        $(this).removeClass("heads").addClass("tails").text("T");
                    else if ($(this).hasClass("tails"))
                        $(this).removeClass("tails").addClass("heads").text("H");
                });
            });
        });
    </script>

    <style type="text/css">
        .coin
        {
            background-color: Silver;
            font-size: 24pt;
            font-weight: bold;
            padding: 5px;
        }
        /* We don't have to define .heads and .tails to make use of
        the state maintenance, but they are defined here for visual cues */
        .heads
        {
            color: Black;
        }
        .tails
        {
            color: White;
        }
    </style>
</head>
<body>
    <h1>Maintaining basic state with jQuery and CSS</h1>
    <span class="coin heads">H</span>
    <span class="coin heads">H</span>
    <span class="coin tails">T</span>
    <span class="coin heads">H</span>
    <span class="coin tails">T</span>
    <h4>H = heads, T = Tails</h4>
    
    <form action="#">
    <input type="button" id="btnClick" value="Flip Coins" />
    </form>
    <h4>from: <a href="http://www.dontcodetired.com" title="Don't Code Tired" >Don't Code Tired</a></h4>
</body>
</html>

SHARE:

A Simple Menu Roll-over using jQuery and CSS

The following ASP.NET page shows a simple example of a menu created using a combination of CSS and jQuery.

The menu is defined as an unordered list (which makes semantic sense) and styled with CSS (a real web site would of course have its CSS defined in external file(s)). When the user moves the mouse over a menu item, a CSS class is dynamically added; then removed when the mouse leaves. In addition a simple "infobox" span is defined whose text is changed to that of the title attribute of the <a> element.

There are lots of examples of image based roll-overs, this one is really cool and based on a simple idea.

 

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">

    <script type="text/javascript" src="jquery-1.3.2.js"></script>

    <title>Simple jQuery Menu Example</title>

    <script type="text/javascript">

        var menuPrompt = "Please select a page to view."; // simple prompt for user
       
        $(document).ready(function() {

            // initialise the infobox prompt
            $("#infobox").text(menuPrompt);
       
            $(".nav_menu_list li a")
            .mouseover(function() {
                // add the mouseover style
                $(this).addClass("nav_menu_item_mouseover");
                // set the text of the infobox span to the anchor title attribute
                $("#infobox").text("Go to " + $(this).attr("title"));
            })
            .mouseout(function() {
                //remove the mouseover style
            $(this).removeClass("nav_menu_item_mouseover");
                // reset the text of the infobox span to user prompt
                $("#infobox").text(menuPrompt);
            })
        })
   
    </script>

    <style type="text/css">
        .nav_menu_list
        {
            list-style-type: none;
            margin: 0 0 0 21px;
            padding: 0;
        }
        .nav_menu_list li
        {
            float: left;
            text-align: left;
        }
        .nav_menu_list li a
        {
            display: block;
            padding: 0 10px 0 5px;
            text-decoration: none;
            font-size: 36pt;
        }
        .nav_menu_item_notmouseover
        {
            color: #0000FF;
            background-color: White;
        }
        .nav_menu_item_mouseover
        {
            color: White;
            background-color: #ec1c24;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <ul class="nav_menu_list">
            <li><a title="Page 1" href="#" class="nav_menu_item_notmouseover">Page 1</a> </li>
            <li><a title="Page 2" href="#" class="nav_menu_item_notmouseover">Page 2</a> </li>
            <li><a title="Page 3" href="#" class="nav_menu_item_notmouseover">Page 3</a> </li>
        </ul>
        <div style="clear: both;">
            <span id="infobox"></span>
        </div>
    </div>
    </form>
</body>
</html> 

SHARE:

Changing background image on <body> element with jQuery when using ASP.NET master pages

If you have an ASP.NET master page defined as below which specifies a css class for the body element to generate a background image for the whole page, you might want to override the default background on specific pages.

One way to accomplish this is to use jQuery to replace the css class that is being applied to the <body> element.

The master page below declares 2 ContentPlaceHolder controls; the first (ID="head") exisist within the <head> element, the second (ID="MainContentPlaceHolder") exists within the main body of the page.


<%@ Master Language="C#" AutoEventWireup="true" CodeFile="MasterPage.master.cs" Inherits="MasterPage" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">
   
    <script type="text/javascript" src="jquery-1.3.2.js" ></script>
   
    <asp:ContentPlaceHolder ID="head" runat="server">
    </asp:ContentPlaceHolder>
   
</head>

<body class="defaultbodybackground">
    <form id="form1" runat="server">  
        <asp:ContentPlaceHolder ID="MainContentPlaceHolder" runat="server" />
    </form>
</body>

</html>

 

 
In one of our child pages we could add the following:


<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">
 
    <script type="text/javascript">

           $(document).ready(function() {
               $("body").removeClass("defaultbodybackground");
               $("body").addClass("newbodybackground");
           })
        
        </script>
</asp:Content>


When the page is loaded, the above jQuery JavaScript runs and replaces the class "defaultbodybackground" with the page specific "newbodybackground".

A cool thing about jQuery is that you can have multiple $(document).ready() defined - for example you could also have some jQuery defined in the master page.

SHARE:

Throttle Your ASP.NET Connection Speed

As a tool to test responsiveness on slow connections Firefox Throttle is handy Firefox add-in. There is also an IE version. You can add a localhost throttle if you are using Visual Studios local web server. For example, setting the download speed to 56K dialup, you can check any Silverlight media buffering UI animations are working as expected.

SHARE: