Archive for the ‘ ASP.NET’ Category

Building a Training Calendar Application

I spent some time with the VP of an interesting company recently.

The company is pretty good size (several hundred million dollars in revenue and many hundreds of employees).

The company sells products, services, and training. The training segment of the business represents a very small percentage of the actual corporate revenue but is a key strategy in the company’s brand identity, customer satisfaction strategy and instrumental in the supporting the sales of products and services.

Historically the company has run a successful training operation but not done an optimal job at synergizing the operations.

Lake most companies, they have many disparate systems (AR, CRM, ERP, etc.)

The problem seemed so interesting top me that I thought I’d use it as the basis for a sample application oversize.

Phase #1 will be implementing the basic data handling features for a training company.

  • Each course will be given many times a year.
  • Each course instance can be given at multiple locations.
  • Each location has different facilities.
  • Each course is part of a curriculum and must be organizational by that identity.
  • Each course has prerequisites and requirements.
  • Each course may be given by multiple instructors and instructor identical is an index.
The following is a Viso draft of the schema. (Click to see the full size image.)

As I get ready to begin implementation, please make any comments and feature suggestions below.

Filtering an ASP.NET GridView control with jQuery

 As I’ve been swimming in the great jQuery lake I discovered the jQuery QuickSearch Plugin,

As WebForms developers we often display lots of data using a gridview control.

I though it would be neet to set up using the jQuery QuickSearch plugin with the Gridview.

Here’s how it works.

Ihave a GridView wired to some sample data. For demo simplicity I’m using an XMLDataSource and reading from an XML file in my App_Data directory.

When the user starts to type into the Filter Text Box the rows in the table are filtered, meaning rows that don’t match the character(s) entered are hidden from view.

As the user continues to type, the list is filtered further.

The ASPX Page Markup is as follows.
Read the rest of this entry »

ASP.NET Dropdown Search with jQuery

The Ajax Control Toolkit includes a ListSearch [ see HERE ] control extender that can me used to extend a list or drop down list with a filtering feature by which the control will start to narrow the available options in the list to the ones that include the characters that the user has entered.

So when we use a drop down list for the selection of an item, and we enter (set focus) on the control, then the control expands. 

Then when we start to type, we want the list to hide items that do not contain the character sequence that we have typed.

I’ve implemented this feature using Unobtrusive Fast-filter Dropdown

Implementing this plugin (abbreviated UFD) with an ASP.NET DropDownList is easy.


<%@ Page Title='Home Page' Language='C#' MasterPageFile='~/Site.master'
    AutoEventWireup='true' CodeFile='Default.aspx.cs' Inherits='_Default' %>

<asp:Content ID='HeaderContent' runat='server'
                                ContentPlaceHolderID='HeadContent'>
    <link href='Content/themes/redmond/jquery-ui.css' rel='stylesheet'
                                                      type='text/css' />
    <link href='Styles/udf/ufd-base.css' rel='stylesheet' type='text/css' />
    <link href='Styles/udf/plain/plain.css' rel='stylesheet'
                                            type='text/css' />
    <script src='Scripts/jquery-1.4.4.js' type='text/javascript'></script>
    <script src='Scripts/jquery-ui-1.8.13.js' type='text/javascript'></script>
    <script src='Scripts/jquery.ui.ufd.js' type='text/javascript'></script>
</asp:Content>
<asp:Content ID='BodyContent' runat='server'
                              ContentPlaceHolderID='MainContent'>
    <h2>
        Welcome to ASP.NET!
    </h2>
    <p>
        To learn more about ASP.NET visit
        <a href='http://www.asp.net' title='ASP.NET Website'>www.asp.net</a>.
    </p>
    <p>
        You can also find
        <a href='http://go.microsoft.com/fwlink/?LinkID=152368&clcid=0x409'
            title='MSDN ASP.NET Docs'>documentation on ASP.NET at MSDN</a>.
    </p>
    <hr />

    <label for='SelectCountry'>Choose a country:</label><br /><br />

    <asp:DropDownList id='SelectCountry' name='SelectCountry' runat='server'
                      ClientIDMode='Static'>
        <asp:ListItem Text='Afghanistan' Value='Afghanistan'></asp:ListItem>
        <asp:ListItem Text='Albania' Value='Albania'></asp:ListItem>
        <asp:ListItem Text='Algeria' Value='Algeria'></asp:ListItem>
        <asp:ListItem Text='Bahrain' Value='Bahrain'></asp:ListItem>
        <asp:ListItem Text='Bangladesh' Value='Bangladesh'></asp:ListItem>
        <asp:ListItem Text='Barbados' Value='Barbados'></asp:ListItem>
        <asp:ListItem Text='Cambodia' Value='Cambodia'></asp:ListItem>
        <asp:ListItem Text='Cameroon' Value='Cameroon'></asp:ListItem>
        <asp:ListItem Text='Canada' Value='Canada'></asp:ListItem>
    </asp:DropDownList>

    <br/>

    <script type='text/javascript' >
        $(function () {
            $('#SelectCountry').ufd({ log: true });
        });
    </script>

</asp:Content>

You can garb the working example [ HERE ]


ASP.NET User Input via the jQuery UI Slider

The Ajax Control Toolkit includes a “Slider” and a “MultiHandleSlider” control extender that lets your user fill a textbox with a numeric value by dragging one or more markers along a line or “axis”.

One “slider” means manipulating one value, multiple sliders means manipulating multiple values.

This is another way to add a visual component to data entry, which may be faster, or lead to greater accuracy and convenience when data is being entered.

I’m replacing the Ajax Control Toolkit slider with the jQuery UI Slider.

Here is a screen shot of the working sample.

And here is our page markup :


<%@ Page Title='Home Page' Language='C#' MasterPageFile='~/Site.master'
    AutoEventWireup='true' CodeFile='Default.aspx.cs' Inherits='_Default' %>

<asp:Content ID='HeaderContent' runat='server'
                                ContentPlaceHolderID='HeadContent'>
<link href='Content/themes/base/jquery.ui.all.css' rel='stylesheet'
                                                   type='text/css' />
<script src='Scripts/jquery-1.4.4.js' type='text/javascript'></script>
<script src='Scripts/jquery-ui-1.8.13.js' type='text/javascript'></script>
<style>
    .valueout
    {
        border: 0;
        color:#f6931f;
        font-weight:bold;
    }
</style>
<script type='text/javascript'>
    $(function () {
        // Add one slider to the first target DIV.
	    $('#slider').slider({
	        value: 100,
	        min: 0,
	        max: 500,
	        step: 50,
	        slide: function (event, ui) {
	            $('#amount').val('$' + ui.value);
	        }
	    });
	    $('#amount').val('$' + $('#slider').slider('value'));

	    // Add two sliders to the second target DIV.
	    $('#slider-range').slider({
	        range: true,
	        min: 0,
	        max: 500,
	        values: [75, 300],
	        slide: function (event, ui) {
	            $('#amountrange').val('$' + ui.values[0]
				                          + ' - $' + ui.values[1]);
	        }
	    });
	    $('#amountrange').val('$' + $('#slider-range').slider('values', 0) +
		                   ' - $' + $('#slider-range').slider('values', 1));

	});
</script>

</asp:Content>
<asp:Content ID='BodyContent' runat='server'
                              ContentPlaceHolderID='MainContent'>
    <h2>
        Welcome to ASP.NET!
    </h2>
    <p>
        To learn more about ASP.NET visit
        <a href='http://www.asp.net' title='ASP.NET Website'>www.asp.net</a>.
    </p>
    <hr />

	<label for='amount'>Donation amount ($50 increments):</label><br /><br />
    <asp:TextBox ID='amount' CssClass='valueout' runat='server'
                 ClientIDMode='Static'>
    </asp:TextBox>
    <br /><br />
    <div id='slider' style='width: 300px;'></div><br />

    <hr />
    <asp:Button ID='Button1' runat='server' Text='Submit'
	                                        onclick='Button1_Click' />
    <br /><br />
    <asp:Label ID='LabelTestResult' runat='server' Text=''></asp:Label>
    <hr />

	<label for='amountrange'>Range:</label>
    <asp:TextBox ID='amountrange' CssClass='valueout' runat='server'
                                  ClientIDMode='Static'>
    </asp:TextBox><br /><br />
    <div id='slider-range'  style='width: 300px;'></div>

</asp:Content>

The actual value is a string stored in the textboxes created on lines #58 and #71.

Note the setting of the initial value, min, max, step, and range parameters.

Note also lines #28 and #40 where slider value is used to set our textboxes.

Since those text boxes are ASP.NET Server Side controls we can easily access them in our code-behind.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        LabelTestResult.Text = 'Thanks - ' + amount.Text
		                                   + ' is a lot of money!';
    }
}

You can download a working sample [ HERE ]


Numeric Up Down Input using the jQuery UI Spinner

The AJAX Control Toolkit includes a Numeric Up/Down Control Extender that lets you turn a text box into a numeric Up / Down input control.

There is a slick jQuery UI plugin – the jQuery UI Spinner - that lets us do this without the Ajax Control Toolkit and have pretty detailed control over the way our input works.

Some of the built-in capabilities include:

  • Mouse Wheel Support
  • Control over the Mouse Wheel Increment sensitivity
  • Variable “step” increments
  • Set-able Minimum and Maximum Values

Here is our demo UI.

And here is our code :


<%@ Page Title='Home Page' Language='C#' MasterPageFile='~/Site.master'
         AutoEventWireup='true' CodeFile='Default.aspx.cs'
		 Inherits='_Default' %>

<asp:Content ID='HeaderContent' runat='server'
             ContentPlaceHolderID='HeadContent'>
<link href='Content/themes/base/jquery.ui.all.css' rel='stylesheet'
      type='text/css' />
<link href='Styles/Site.css' rel='stylesheet' type='text/css' />
<link href='Styles/ui.spinner.css' rel='stylesheet' type='text/css' />
<script src='Scripts/jquery-1.4.4.js' type='text/javascript'></script>
<script src='Scripts/jquery-ui-1.8.13.js' type='text/javascript'></script>
<script src='Scripts/ui.spinner.js' type='text/javascript'></script>
<script type='text/javascript'>
jQuery().ready(function ($) {
	$('#updown').spinner({ min: -100, max: 100 });
	$('#updownfast').spinner({ min: -1000, max: 1000, increment: 'fast' });
	$('#updownhide').spinner({ min: 0, max: 100, showOn: 'both' });
	$('#updownnull').spinner({ min: -100, max: 100, allowNull: true });
	$('#updowndisable').spinner({ min: -100, max: 100 });
	$('#updownmaxlen').spinner();

	$('#updownconfig').spinner(
	   { min: -1000, max: 1000, step: 1, increment: 'fast' }
	   );
	$('#updownmax').spinner().change(function ()
	   { $('#updownconfig').spinner('option', 'max',
	                                 parseInt($(this).val())); }
	   );
	$('#updownmin').spinner().change(function ()
	   { $('#updownconfig').spinner('option', 'min',
	                                 parseInt($(this).val())); }
	   );
	$('#updownstep').spinner().change(function ()
	   { $('#updownconfig').spinner('option', 'step',
	                                 parseInt($(this).val())); }
	   );
	$('#updownspeed').change(function ()
	   { $('#updownconfig').spinner('option', 'increment', $(this).val()); }
	   );
	$('#updownmousewheel').change(function ()
	   { $('#updownconfig').spinner('option','mouseWheel',
	                                 $(this).is(':checked')); }
	   );
	$('#enable').click(function ()
	 { $('#updowndisable').spinner('enable'); });
	$('#disable').click(function ()
	 { $('#updowndisable').spinner('disable'); });
	$('#GetValue').click(function ()
	 { alert($('#updown').spinner('value')); });
	$('#destroy').click(function ()
	 { $('#updown').spinner('destroy'); });

});
</script>
</asp:Content>
<asp:Content ID='BodyContent' runat='server'
     ContentPlaceHolderID='MainContent'>
<h2>
    Welcome to ASP.NET!
</h2>
<br />
Up Down :
<asp:TextBox ID='updown' runat='server' ClientIDMode='Static' Text='0'>
</asp:TextBox>
<input type='button' id='GetValue' value='Get Value' />
<input type='button' id='destroy' value='Destroy' />
<br /><br />

Fast Up / Down :
<asp:TextBox ID='updownfast' runat='server' ClientIDMode='Static' Text='0'>
</asp:TextBox>
<br /><br />

Up / Dopwn Hidden:
<asp:TextBox ID='updownhide' runat='server' ClientIDMode='Static' Text='0'>
</asp:TextBox> Except for  When Active !
<br /><br />   

<hr />
<div id='example'>
<table class='grid'>
  <tr>
     <td>Configurable Up/Down:</td>
     <td>
     <asp:TextBox ID='updownconfig' runat='server'
	              ClientIDMode='Static' Text='0'>
     </asp:TextBox>
     </td>
   </tr>
   <tr>
      <td>Maximum:</td>
      <td>
      <asp:TextBox ID='updownmax' runat='server'
	               ClientIDMode='Static' Text='1000'>
      </asp:TextBox>
      </td>
   </tr>
   <tr>
      <td>Minimum:</td>
      <td>
      <asp:TextBox ID='updownmin' runat='server'
	               ClientIDMode='Static' Text='-1000'>
      </asp:TextBox>
      </td>
   </tr>
   <tr>
      <td>Step:</td>
      <td>
      <asp:TextBox ID='updownstep' runat='server'
	               ClientIDMode='Static' Text='1'>
      </asp:TextBox>
      </td>
   </tr>
   <tr>
      <td>Speed:</td>
      <td>
         <select id='updownspeed'>
            <option value='slow'>Slow</option>
            <option selected='selected' value='fast'>Fast</option>
         </select>
      </td>
   </tr>
   <tr>
      <td>Mouse Wheel:</td>
      <td>
         <input type='checkbox' id='updownmousewheel' checked='checked' />
      </td>
   </tr>
</table>
</div>
<hr />
<br />
    <asp:Button ID='ButtonSubmit' runat='server' Text='Submit'
        onclick='ButtonSubmit_Click' /><br /><br />
    <asp:Label ID='LabelResult' runat='server' Text=''></asp:Label>
</asp:Content>

The ui.spinner.css file takes care of positioning the Up / Down buttons next to the text bix that they will apply to.

Note that in the body of the markup the text boxes can be either html input elements with type set equal to text or ASP.NET TextBox controls with the ClientIdMode set to static.

Whichever way you choose you can specify a starting numberic value as a string.

The “magic” happens in the jQuery code that you see above between lines 11 and 44.

I think the code’s functionality is pretty straight forward and looking at the code reveals many of the optional parameters.

Simplifying user input helps reduce data input errors!

You can download a working sample [ HERE ].


Embedding a jQuery HTML Input Editor in an ASP.NET page.

Sometimes we need users to be able to enter fomated input / text.

There are many embedable WYSIWYG HTML inpt boxes available. [ See HERE ]

I chose HTMLBox 4.01 becuase it is easy to style [ DEMO HERE ] but there are many good ones and you should pick the one that best meets your needs.

My implementation looks like this.

When I’ve entered some formatted text I can switch to HTML view and see the markup.

One of the things tat I especially like about HTMLBox is that it exposes events for the appropriate icons like “File Open”

My page markup looks like this:


<%@ Page Title='Home Page' Language='C#' MasterPageFile='~/Site.master'
         AutoEventWireup='true' CodeFile='Default.aspx.cs'
         Inherits='_Default'  %>

<asp:Content ID='HeaderContent' runat='server'
             ContentPlaceHolderID='HeadContent'>
    <script src='Scripts/jquery-1.4.1.js' type='text/javascript'></script>
    <script src='Scripts/com.remiya.jquery.codify.min.js'
	        type='text/javascript'>
    </script>
    <script src='Scripts/htmlbox.colors.js' type='text/javascript'></script>
    <script src='Scripts/htmlbox.styles.js' type='text/javascript'></script>
    <script src='Scripts/htmlbox.syntax.js' type='text/javascript'></script>
    <script src='Scripts/htmlbox.undoredomanager.js' type='text/javascript'>
    </script>
    <script src='Scripts/htmlbox.full.js' type='text/javascript'></script>
    <script type='text/javascript'>
        $(function () {

        });
    </script>
</asp:Content>
<asp:Content ID='BodyContent' runat='server'
             ContentPlaceHolderID='MainContent'>
    <h2>
        Welcome to ASP.NET!
    </h2>
    <p>
        To learn more about ASP.NET visit
        <a href='http://www.asp.net' title='ASP.NET Website'>www.asp.net</a>.
    </p>
<h2>HTML Input</h2>

<asp:TextBox ID='htmlbox' runat='server' TextMode='MultiLine' Rows='20'
             Columns='80' ClientIDMode='Static'></asp:TextBox><br />
<asp:Button ID='SubmitButton' runat='server' Text='Submit'
            onclick='SubmitButton_Click' /><br /><br />

<asp:Label ID='LabelResult' runat='server'></asp:Label>

<script  type='text/javascript'>
var hb_icon_set_blue;
hb_icon_set_blue = $('#htmlbox').css('height', '100')
                                .css('width', '600').htmlbox({
   toolbars: [
	         ['cut', 'copy', 'paste', 'separator_dots', 'bold', 'italic',
              'underline', 'strike', 'sub', 'sup', 'separator_dots', 'undo',
              'redo', 'separator_dots', 'left', 'center', 'right', 'justify',
              'separator_dots', 'ol', 'ul', 'indent', 'outdent',
              'separator_dots', 'link', 'unlink', 'image'],
		      ['code', 'removeformat', 'striptags', 'separator_dots',
			   'quote','paragraph', 'hr', 'separator_dots',
              { icon: 'new.gif', tooltip: 'New', command: function ()
                                { hb_icon_set_blue.set_text('<p></p>'); } },
			 { icon: 'open.gif', tooltip: 'Open', command: function ()
                                { alert('Open') } },
			 { icon: 'save.gif', tooltip: 'Save', command: function ()
                                { alert('Save') } }
		  ]
	],
        icons: 'default',
        skin: 'blue'
    });
</script>

</asp:Content>

But, just adding the jQUery and HTML Box libraries to our page and wiring the jQuery plugin to an ASP.NET Multi Line Textbox will not get us to where we really need to be.

If we do just that muich and run our page we will see this error.



The above is generated by a built in security feature of .NET that prevents the user from submitting markup or anything that might be a security concern.

We’ll need to tell ASP.NET to allow markup to be posted back

WARNING: Doing this means we are explicitly telling ASP.NET that we will be responsable for making sure that whatthe user posts back to the server is SAFE ! – All user input should be considered evil untill we prove otherwise.

In order to permit the markup to be posted back we need to do two things,

1.) We need to add a directive to the system.web section of the web.config file and set the Validation Mode to 2.0


  <system.web>
      <httpRuntime requestValidationMode='2.0' />
  </system.web>

2.) Then, in the page itself we need to add a page directive to tell ASP.NET not to validate the page


<%@ Page Title='Home Page' Language='C#' MasterPageFile='~/Site.master'
         AutoEventWireup='true' CodeFile='Default.aspx.cs'
         Inherits='_Default' ValidateRequest='false' %>

Now the page will submit.

Since we turned validation off, we should insure security before we use whatever the user entered in the WYSIWYG box. (Like storing it in a database or displaying it on a page.

In our button click event handler we simply encode the text box value before we use it.


    protected void SubmitButton_Click(object sender, EventArgs e)
    {
        LabelResult.Text = Server.HtmlEncode(htmlbox.Text);
    }

You can download a working ASP.NET 4 sample [ HERE ]


Replacing the Ajax Control Toolkit DragPanel Control Extender with jQuery

The Ajax Control Toolkit includes a DropPanel Control Extender that lets you drag and drop content thereby moving it around on your web page [ more HERE ]. 

jQuery, or more specifically jQueryUI has Drag-and-Drop built-in.

Yup – like a lot of stuff in this series that means it’s just REALLY easy to get the effect you want using jQuery

Since this series is about showing how to do with jQuery the sort of things you would have previously done with the Ajax Control Toolkit, I’m going to defer catching the “drop” events to a future entry.

Here is the effect we’re looking for.

 

Drag and Drop …..

After including jQuery and jQUeryUI  (script & CSS) here is the code for the page.


<%@ Page Title='Home Page' Language='C#' MasterPageFile='~/Site.master'
         AutoEventWireup='true' CodeFile='Default.aspx.cs'
                        Inherits='_Default' %>

<asp:Content ID='HeaderContent' runat='server'
                                ContentPlaceHolderID='HeadContent'>
    <link href='Styles/jquery-ui-1.8.13.custom.css' rel='stylesheet'
                                                type='text/css' />
</asp:Content>
<asp:Content ID='BodyContent' runat='server'
                              ContentPlaceHolderID='MainContent'>
    <h2>Draggable Panel !</h2>
    <br />
    <div class=demo>
        <div id=draggable class=ui-widget-content>
            <p>
            <br />
            I'm an AJAX Draggable Container.
            <br /><br />
            You could catch drop events and build a configurable UI.

            </p>
        </div>
    </div>

    <div>
        <p>
        Lorem ipsum dolor sit amet, consectetur adipiscing elit.
        Mauris varius ullamcorper lacus, ac pharetra libero commodo eu.
        Aenean auctor imperdiet libero, sit amet scelerisque lorem placerat
        quis. Phasellus pretium, lacus eget euismod cursus, nunc nibh semper
        urna, at blandit elit nisl non dui. Sed blandit dignissim tellus,
        in egestas orci facilisis vel. Curabitur consequat ante vel mauris
        accumsan rutrum. Aliquam lorem est, ornare eget mollis sit amet,
        vestibulum et diam. Phasellus cursus massa sodales metus
        luctus sed blandit quam rhoncus. Proin nunc risus, scelerisque eu
        sagittis in, gravida vitae lectus. Maecenas et ipsum ac mauris
        condimentum accumsan ac et ligula. Phasellus mattis, tortor quis
        rutrum mollis, ante eros dictum leo, ac venenatis augue nisl sit
        amet mauris. Maecenas cursus, arcu nec egestas molestie, leo
        lectus pellentesque sapien, eu sollicitudin urna dolor vitae
        nisl. Proin lobortis, tortor quis congue lacinia, arcu elit
        consequat erat, vestibulum aliquet lorem massa sed leo. Suspendisse
        volutpat odio in mauris cursus aliquam. Nullam sed sapien sit amet mi
        laoreet sagittis. Integer rutrum lacus quis felis venenatis porta.
        </p>
    </div>         

    <script src='Scripts/jquery-1.4.1.js' type='text/javascript'></script>
    <script src='Scripts/jquery-ui-1.8.1.custom.min.js'
	                                     type='text/javascript'>
    </script>

    <style>
    #draggable { width: 150px; height: 150px; padding: 0.5em; }
</style>

    <script type='text/javascript'>
        $(function () {
            $('#draggable').draggable();
        });
    </script>
</asp:Content>

All we’re doing here is specifying a class to apply to the area that we want to be draggable then using a jQuery selector to access any page element that uses that class and calling the jQueryUI dragable() method.

Have fun !


Implementing Collapse Panels with jQuery.

The Ajax Control Toolkit has a Collapse Panel Control Extender [ see HERE ] that allows you to hide or show sections of content in your web page. This ability can be very useful as we evolve our UIs more toward “Single Page” interfaces.

There are many ways to accomplish this using jQuery and I’ve chosen a slick little plugin by Darren Ingram [ get it HERE ]

The UI behavior is simple. We have a set of content in a container (a div in this case)

When the user clicks on the title bar the container collapses leaving only the title bar.

The code is simple becuase the PlugIn does all the work for us.


<%@ Page Title='Home Page' Language='C#' MasterPageFile='~/Site.master'
    AutoEventWireup='true' CodeFile='Default.aspx.cs' Inherits='_Default' %>

<asp:Content ID='HeaderContent' runat='server'
                                ContentPlaceHolderID='HeadContent'>
<link href='Styles/jquery-ui-1.8.13.custom.css' rel='stylesheet'
                                                type='text/css' />
</asp:Content>

<asp:Content ID='BodyContent' runat='server'
                              ContentPlaceHolderID='MainContent'>
    <h2>
        Welcome to ASP.NET!
    </h2>
    <p>
        To learn more about ASP.NET visit
        <a href='http://www.asp.net' title='ASP.NET Website'>www.asp.net</a>.
    </p>
    <div class='collapsibleContainer' title='Example Collapsible Panel'>
	<p>
	Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris
	varius ullamcorper lacus, ac pharetra libero commodo eu. Aenean auctor
	imperdiet libero, sit amet scelerisque lorem placerat quis. Phasellus
	pretium, lacus eget euismod cursus, nunc nibh semper urna, at blandit
	elit nisl non dui. Sed blandit dignissim tellus, in egestas orci
	facilisis vel. Curabitur consequat ante vel mauris accumsan rutrum.
	Aliquam lorem est, ornare eget mollis sit amet, vestibulum et diam.
	Phasellus cursus massa sodales metus luctus sed blandit quam rhoncus.
	Proin nunc risus, scelerisque eu sagittis in, gravida vitae lectus.
	Maecenas et ipsum ac mauris condimentum accumsan ac et ligula.
	Phasellus mattis, tortor quis rutrum mollis, ante eros dictum
	leo, ac venenatis augue nisl sit amet mauris. Maecenas cursus, arcu nec
	egestas molestie, leo lectus pellentesque sapien, eu sollicitudin urna
	dolor vitae nisl. Proin lobortis, tortor quis congue lacinia, arcu elit
	consequat erat, vestibulum aliquet lorem massa sed leo. Suspendisse
	volutpat odio in mauris cursus aliquam. Nullam sed sapien sit amet mi
	laoreet sagittis. Integer rutrum lacus quis felis venenatis porta.
	</p>
    </div>  

    <script src='Scripts/jquery-1.4.1.js' type='text/javascript'></script>
    <script src='Scripts/jquery-ui-1.8.1.custom.min.js'
	             type='text/javascript'>
    </script>
    <script src='Scripts/diQuery-collapsiblePanel.js'
	             type='text/javascript'>
    </script>
    <script type='text/javascript'>
        $(document).ready(function () {
            $('.collapsibleContainer').collapsiblePanel();
        });
    </script>
</asp:Content>

In the example above the collapsable dic contains a text paragraph but try it with ASP.NET controls and you’ll find it works the same way.

Have fun !


Replacing the Animation Control Extender with jQuery Animations

Next up in this series is control animation.  The Ajax Control Toolkit has an Animation Control Extender [ see HERE ].

jQuery has animation built-in to its code [ see HERE ]

Basically, with jQuery animation you can animate any DOM object that you are access pragmatically.

Understand that animation is a huge subject and the variety of effects you can accomplish with jQuery animation is limited only by your imagination. One could write an entire book on jQuery animation and I’m not a “designer”.

I’ll show you a basic animation to get you started.

Here is the animation behavior I want.

Click on the image for a short video that shows the animation.

Here is the entire ASPX page.

Note that the positioning of the Button control is absolute and, for the sake of a simple demo, I’ve just hard-coded the position to work with a 1024×768 resolution. In production I’d have to dynamically determine the correct starting position.


<%@ Page Title='Home Page' Language='C#' MasterPageFile='~/Site.master'
         AutoEventWireup='true' CodeFile='Default.aspx.cs'
		 Inherits='_Default' %>

<asp:Content ID='HeaderContent' runat='server'
             ContentPlaceHolderID='HeadContent'>
    <script src='Scripts/jquery-1.4.1.js' type='text/javascript'></script>
    <style>
    .block  {
        position:absolute;
        background-color:#abc;
        border-top-width: medium;
        left:30px;
        width:90px;
        height:90px;
        margin:5px;
        top: 280px;
        }
    </style>
</asp:Content>

<asp:Content ID='BodyContent' runat='server'
             ContentPlaceHolderID='MainContent'>
    <h2>jQuery has rich Animation.</h2>
    <p>
        <asp:Label ID='ResultLabel' runat='server' Text='&nbsp;'>
		</asp:Label><br />
    </p>

    <button id='left'>"</button> <button id='right'>"</button><br />
    <asp:Button ID='AnimatedButton' class='block' runat='server'
	            Text='ASP Button'
                ClientIDMode='Static' onclick='AnimatedButton_Click' />
    <br /><br /><br /><br />&nbsp;SECRET !
    <script type='text/javascript'>
        $('#right').click(function () {
            $('.block').animate({ 'left': '+=150px' }, 'slow');
        });

        $('#left').click(function () {
            $('.block').animate({ 'left': '-=150px' }, 'slow');
        }); 

    </script> 

</asp:Content>

By now (assuming that you have been following this series) you are starting to get comefortable with jQuery so the code should be pretty understandable. I’m simply using a selector to get the Botton Object by it’s class association (take note of the ClientId setting on the ASP.NET Button control) and calling the .animate method.

You can check out the documentation for all the available options here : http://api.jquery.com/animate/

Since I’m somewhat “creativly challenged”, here are some additional resources to help you get started with animation ideas.

Murach Web Development Books Updated to 4

MurachsADONET4CS  MurachsASPNET4CS

[ Click the books above to see them on Amazon ]

I’ve said for many years that were I ever to teach a university course on web development Murach’s books would be the textbooks that I would use.

Since many folks have emailed me to say that they used these books to learn ASP.NET I thought I’d let folks know that Murach has updated them to the 4 versions of .NET

The folks at Murach were nice enough to send me the latest versions and they are everything that I’ve come to expect from a Murach book.

The ASP.NET book is THE quintessential resource for learning ASP.NET Web Forms Development (yes, WebForms is still the #1 ASP.NET Development model by a significant margin).

It covers details of every aspect of ASP.NET Web Forms development. Two particularly interesting coverage areas are the use of WCF services and details  working with web applications on Windows 7.

The ADO.NET book not only provides tutorial on all the aspects of ADO.NET data access but walks you through building an application. Though there is the expected focus on LINQ, Entity Framework, etc. there is also coverage on other data like XML.

As always, You can’t go wrong.

In the previous post in this Contoso Karate MVC Series we re-factored our LogIn control widget into a PartialView. We did this for a few reasons.

  • Views want to be associated with only one model and we want to reserve that model for one that is more central to the particular page being displayed. (Specifying the Model for the view in the page _Template is generally a bad idea since that model will then be THE model assumed for every page that derives from that template. Partial views are one of the ways that we can solve this problem, a ViewModel is another.)
  • Partial views are very easily reusable.
  • If other considerations don’t preempt their use, Partial Views can make your actual View Markup easier to understand.

In this post I’ll build another Partial View. Please read the previous post to understand why we need partial views in the context of our fairly complex user interface design.

So, lets suppose that we have a requirement for an alert / notice box on our home page. It could contain special data, like for example a notice that classes are canceled due to bad weather.

It might look like this.

In this case our UI Widget is slightly more complex because we will need to retrieve data from a database to display from inside our partial view. We will store all the site notices in the database so that we have a historical record but we’ll only display the most recent one.

So, we’ll need a data table to store our notices. I like to keep the ASP.NET Services data (membership, etc) separate from my domain specific data so I created a new database named CKCMS for Contoso Karate Content Management System.

You probably know the drill. Right-Click in the solution, select Add -> New Item, choose the data items collection and select New SQL Server Database.

In Visual Studio, Switch from the Solution Explorer to the Database Explorer.

Expand the view on the database that was just created and right-click on the tables folder.

Add the fields as shown in the following table view.

When you save the table, name it “Notices”.

Note that the IsLive column will not be used in this demo. I’ve added it for future use. (We may want to be able to display more than one notice at a time in a future version of the application.)

Since we’ll need to access the data, I created an ADO.NET Entity Model.

Right-Click on the Models folder and choose add new item.

Select “Data” to see the data items collection and choose ADO.NET Entity Data Model and specify the name “CKSMSDBModel”  (Contoso Karate Content Management System Database Model.)
Read the rest of this entry »

Refactoring the Contoso Karate MVC LogOn Widget.

Just recently I published this post about creating a “logon widget” for the ASP.NET MVC Contoso Karate application that I’ve started building.

In this post I’m going to re-factor it.

Why, you ask? Well, sometimes it’s easiest to demonstrate techniques in a “simple” way  that is not necessary the most practical way.

Such is the case of our “login widget”.

ASP.NET MVC imposes a LOT of conventions. We could have technoligious discussions ad nauseam about why the MVC way is the best way (or not). I have FAR to many of these conversations but lets just agree that for some developer’s preferences and in certain types of application needs, the impositions of the pattern pay long-term dividends.

The idea of MVC (Model – View – Controller) lets us achieve “Separation of Concerns”. While this is not necessary (I know – sacrilege!) it is normally a beneficial thing. 

But, whenever a pattern or an implementation is meant to support a specific way of doing things it can get in the way.

The problem in this case is that a view (by default) sort of wants to be rendered using a SINGLE model.

take for example the following web site layout from a Joomla theme by RocketTheme

This is a pretty common kind of web user interface and one that will be very difficult to serve using a single data source.

You’ll recall from the previous post that we want the LogOn widget to appear on every page  but we accessed the model for the login data by referencing the LogOnModel that is innate to ASP.NET MVC applications that are created using the default ASP.NET MVC template.

It works fine, but our pages will stop working as soon as we try to reference an additional model in our views as views want a SINGLE model to work with.

No problem. Not only is there a way to do what we want (now that we understand the code that delivers the LogOn behavior that wer want) there is a much better, reusable way.

Enter “Partial Views”

Note that I’m not posting screen shots here because the User Interface will look and work EXACTLY like that you will find in the previous post referenced above.

To create a Partial View you will right-click on the folder where you want that Partial View to be created. Since we want our “LogIn Widget” to be able to be used anywhere, we’ll Right-Click on the \Views\Shared folder, choose “Add and then “View”.

Note the sections indicated in the image above.

I chose a name that begins with an underscore (I don’t want this partial view to ever be rendered directly) and ends with the word “partial” so that I can tell at a glance which of my views are “full” views and which are partial.

In addition I select the check box that instructs the wizard to create a partial view.

Once I complete the wizard my

Views\Shared folder will contain a file named _LoginBoxPartial.cshtml

Next, I need to move two bits of code from my site’s _Layout.cshtml page.

  • The MOdel declaration at the very top.
  • The conditional markup that we put in the _Layout file to create the LogIn or LogOut box, depending on the user’s state of authentication.

 The complete code of our partial view (_LoginBoxPartial.cshtml) loosk like this:



@model ContosoKarateMVC.Models.LogOnModel
@if (!User.Identity.IsAuthenticated)
{
    using (Html.BeginForm('LogOn', 'Account', FormMethod.Post))
    {
        <div class='editor-label'>
            @Html.LabelFor(m => m.UserName)
        </div>
        <div class='editor-field'>
            @Html.TextBoxFor(m => m.UserName)
            @Html.ValidationMessageFor(m => m.UserName)
        </div>
        <div class='editor-label'>
            @Html.LabelFor(m => m.Password)
        </div>
        <div class='editor-field'>
            @Html.PasswordFor(m => m.Password)
            @Html.ValidationMessageFor(m => m.Password)
        </div>
        <div class='editor-label'>
            @Html.CheckBoxFor(m => m.RememberMe)
            @Html.LabelFor(m => m.RememberMe)
        </div>
        <span class='style-button-wrapper'>
            <span class='style-button-l'> </span>
            <span class='style-button-r'> </span>
            <input type='submit' name='Submit' class='style-button'
			       value='Login' />
        </span>
        <hr />
        <ul>
            <li>
		@Html.ActionLink('Create an Account.', 'Register', 'Account')
	    </li>
        </ul>
    }
}
else
{
    using (Html.BeginForm('LogOff', 'Account', FormMethod.Post))
    {
        <span class='style-button-wrapper'>
            <span class='style-button-l'> </span>
            <span class='style-button-r'> </span>
            <input type='submit' name='Submit' class='style-button'
			                     value='Logoff' />
        </span>
    }
}

Then we just need to insert a call to render our partial view in the same location as when the markup was in-line in the Layout file.


@{ Html.RenderPartial('_LoginBoxPartial'); }

Now the Views that derive from our _Layout.cshtml page are free to use whatever model they desire and our LogIn feature will still work.

What’s more, we can reuse the Partial View anywhere in our project.

Note: I’m intentionally not posting a like to the source code (you can easily change the source from the prior post.)

In my NEXT post I’ll illustrate a more complex use of “Widgetry” and I will post the code at that time.


Adding a site wide Log In Features to an ASP.NET MVC Web Site.

Having fitted the theme generated for the Contoso Karate Web Sites (see the previous posts in this series) it’s time to start adding functionality to the template.

If you’re new to ASP.NET MVC, let me take this opportunity to encourage you to stick with it. Much is different and sometimes this makes things especially frustrating because not only do we have to learn new things, but the new things work quite differently than we expect based on our previous experience.

Be tenacious, it’s worth it.

Here is our first feature scenario. My Contoso Karate site will have a “portal” feel to it. The default ASP.NET MVC Internet Application template has a separate page for the user to use to authenticate (Log In) but I want the user to be able to log in from any page in my website.

It’s very common for web sites to have a “Log In” widget in the side bar of their theme, like this:

I want the user to be able to Log In by entering their User Name and Password right here on the Home page, or any page in the site that uses the default page template.

To do this in a functionally complete way I need to provide for several behavioral considerations.

  • The user does not yet have an account on the site and needs to create one.
  • The user submits the form without entering the required User Name and Password.
  • The user fills out the form but the user name and password to not match any in the authentication database.
  • The user entered a valid user name and password and is authenticated when the user clicks the submit button.

In the last case, it doesn’t make sense to continue to show a Log-In feature after the user successfully logs in so we should conditionally display a Log-Out option is the current user is authenticated.

ASP.NET WebForms developers have traditionally been bound by the restriction of a single HTML form to each .ASPX page. (Though technically there are ways around this issue and the server-side execution model for user interface element events made this more or less irrelevant.)

While ASP.NET WebForms abstracts the “nature” of World Wide Web applications, ASP.NET MVC embraces it.

An ASP.NET MVC View can contain any number of html forms and each form’s action attribute can submit to any controller and action (and http method) that we need.

So to create the Log-In feature in the right column of our template (_Layout.cshtml) we will insert an html form object. We will do this using the @Html helper object.


using (Html.BeginForm('LogOn', 'Account', FormMethod.Post))
{
   <div class='editor-label'>
      @Html.LabelFor(m => m.UserName)
   </div>
   <div class='editor-field'>
      @Html.TextBoxFor(m => m.UserName)
      @Html.ValidationMessageFor(m => m.UserName)
   </div>
   <div class='editor-label'>
      @Html.LabelFor(m => m.Password)
   </div>
   <div class='editor-field'>
      @Html.PasswordFor(m => m.Password)
      @Html.ValidationMessageFor(m => m.Password)
   </div>
   <div class='editor-label'>
      @Html.CheckBoxFor(m => m.RememberMe)
      @Html.LabelFor(m => m.RememberMe)
   </div>
   <span class='style-button-wrapper'>
      <span class='style-button-l'> </span>
      <span class='style-button-r'> </span>
      <input type='submit' name='Submit' class='style-button'
         value='Login' />
   </span>
   <hr />
   <ul>
      <li>
    @Html.ActionLink('Create an Account.', 'Register', 'Account')
      </li>
   </ul>
}

Notice that the form labels and fields are referencing a data model (m.UserName). The model is the LogonModel that we get by virtue of starting our project from the default ASP.NET MVC Internet template.
Read the rest of this entry »

Finding Videos, Tutorials, etc. on the ASP.NET Web Site

Many folks have emailed me in recent weeks trying to find some of my old videos or tutorials.

The ASP.NET Web Site has been undergoing a series of incremental improvements and the site management team is working hard to improve the experience and expose all of the available learning resources. While they’re continuing the “findability” work, here is a list of end-points on the ASP.NET Web site that might help you find the training materials that you are looking for.


Videos:



Tutorials:


Pages:


A few more: :


Complete www.ASP.NET Site Map : http://www.asp.net/sitemap

Contoso Karate MVC – Migrating the Theme from WebMatrix

I’ve been a bit slow doing getting all the Contoso Karate Sites that I want to build off the ground.

A couple of weeks ago I started posting about Contoso Karate WebMatrtix [ read HERE ]

To get started with the MVC version, the first thing that I needed to do was to get the theme implemented.

So, I created an ASP.NET MVC site using the default ASP.NET MVC template.

Then I took the markup from the _SiteLayout.cshtml page from my Contoso Karate Web Matrix site and copied it to the _Lyout.cshtlm page

When I first ran (F5) the site in Visual Studio – I get a pleasant surprise :

There was only one change that I needed to make.

Since there is no 1-to-1 relationship between physical endpoints and urls, the can “view” can be requested using different URLs

ie: http://localhost/ & http://localhost/home will result in the same view being rendered.

So I changed resource references (images, etc) in my view to use the magic “HRef” helper.

- @Href(“~/Content/Images”)

You can learn more about the ASP.NET Razor Syntax [ HERE ]

You  can download the Runnable Contoso Karate MVC Theme [ HERE ]

Unobtrusive JavaScript in your ASP.NET pages.

One of the fundamental premises of ASP.NET is the “separation of concerns”. In ASP.NET WebForms Code and Markup go in separate files by default (.aspx / .aspx.cs). In ASP.NET MVC concern isolation is innate to the MVC convention. It therefore only makes sense to apply the same organizational construct to our use of JavaScript, especially as we federate more and more logic to the client side of our applications (meaning the browser.)

I’ve adopted  the practice of “Unobtrusive JavaScript” that appears below. FOr the sake of simplicity I’ve created this without using the standard WebForms template.

Lets suppose I have a page and I want to implement some jQuery / jQuery UI  features. Given this page …

I want to be able to drag & drop ….

And resize it ….

And I wanted to use jQuery UI features like a Pop-Up Calendar Picker.

Read the rest of this entry »

Calling Web Service Page Methods with jQuery

A “Web Service”, according to Wikipedia, is any software that is meant to provide computer to computer communication but is typcally comveyed using HTTP.

Just with the Microsoft Development stack there are lots of ways to expose application logic via HTTP.

  • ASMX
  • WCF
  • CSHTML
  • MVC
  • ASHX (ASP.NET Handler)
  • etc..

As we increase our client side user experience we will certainly be adding cient side behaviors with JavaScript, CSS, and in the future HTML5.

As we add dynamic behavior to our web application user interfaces, we’ll be updating the browser stsate with data retrieved by our client side code.

Often , the server side logic that will delivger this code will have no contextual value outside the “Web Page” that calls it.

Enter ASP.NET Page Methods. “Page Methods” live inside an ASP.NET page. They are callable via JavaScript and therefore require no seperate file, endpoint or infrastructure.

Since I (and many of you) have adopted jQuery as your client side development model, and since Microsoft has officially embraced jQuery, I’ve been moving all my new AJAX code to jQuery.

Since a first stab at calling page methods using jQuery syntax might be a bit tricky, I”ve created this demo.

Joel Carlson blogged a sample using an interesting Page Method Factory and I’m using that method (and code) in this demo.

Starting with the standard ASP.NET Web Forms web site template I’ve addede two page methods, one that is “Read Only” (no parameters) and one that sends data and recieves a return value.
Read the rest of this entry »

ContosoKarate WM – Site Registration

I started building ContosoKarate (WebMatrix) by creating a site using the default WebMatrix Default Site Template.

The default template includes a collection of account related pages.

After modifying the _SiteLayout.cshtml the Register.cshtml looked pretty good.

So there are two things I need to do.

  1. Enable Captcha
  2. Make the formatting pretty.

First, I modified the Login Box markup to include a link to the Register.cshtml page.

<ul>
   <li><a href='#'>Forgot your password?</a></li>
   <li><a href='#'>Forgot your username?</a></li>
   <li><a href='@Href('~/Account/Register.cshtml')' /'>
          Create an account</a></li>
 </ul>

So I did a bit of clean up in the formatting and lined up form fields using a table. I know, I know – but for something this simple a table is perfect and easy.

Next, next enable Re-Captcha. To do this we’ll need to use the WebMatrix Package Manager (which is a front end to NuGet) to download and install some of the basic WebMatrix Razor Helpers.

Before we install he Re-Captcha Helper itself, we’ll need a Re-Captcha Key.

You can get one by going here https://www.google.com/recaptcha/admin/create and following the steps as in the screen shots below.

Save the ReCaptcha keys and start your WebMatrix application then add _Admin to the url in the browser.

ie: http://localhost:9999/_Admin

Read the rest of this entry »

ContosoKarate (WM) – The HTML Theme and ASP.NET Web Pages Integration

Monday I posted that I was starting a series of demo applications [ Read HERE ]

Please keep the suggestions and comments coming.

I’ve been asked about the theme for the site.

Since I have NO artistic ability myself ad I have no budget to hire a designer, I purchased Artisteer (with my own money !)

Artisteer is an interesting tool. Not perfect, but well worth the money for me.

For the “aesthetically challenged” like mem it offer complete theme suggestions and then you can have the tool suggest design changes on a section by section basis.

If you explore the tool you find that you can have a pretty detailed control over the look of your design.

I wanted a pretty standard “portal” style design to start with so I added a custom background and header graphic and settles on this.

Since I’m using a generated theme, in the future I’ll see how hard it will be to try to “plug” in theme variations.

Next, I needed to separate the UI “frame” into a template and the core for the default page into the Default.cshtml page

I’ve done this and formatted the markup. There is still lots to do with the Template but those details will take care of themselves as features get implemented.

The first bit of functionality we need to add is a customized site registration.

I doubt the state of the code would be useful to anyone at this point so I won’t bother to post it but if anyone wants it just email me and I’ll send it to you.

If you are new to WebMatrix of haven’t wrapped your head around PageTemplates yet you can find that and lots of other info [ HERE ]

ASP.NET How-Do-I Video Archive

I’ve been seeing a rise in inbound searches from Google and Bing of people looking for “Joe Stagner Videos”.

The ASP.NET web site team has been doing a lot of reorganizing on the www.asp.net web site and some of the older videos, while still there, are not as easy to find. (They need to make room for the “new” stuff.)

So I’ve started to index my ASP.NET, Microsoft Ajax, and Ajax Control Toolkit Videos here.

You can find them using the Video menu item at the top of my blog or the Videos menu to the right side.

I’ll try to add some every night until I’ve got them all.

Hopefully this will make them easier to find.

Beginning the Contoso Karate WebMatrix Sample App

Today I began work on a new Sample Application called Contoso Karate

My proposed “design” is as follows:

The idea will be to create a production ready web site that represents your kids Karate School.

So, not a big production B2B or B2C Ecommerce site but still something with nice features, community and social functionality.

I intend to build the WebMatrix Version first and then perhaps an ASP.NET MVC 3 version. (Maybe even a MODERN WebForms version if there is interest.)

So, please take a moment to comment below on the features, methods, etc that you would like to see in a learning application with this context.

My goal is that folks will be able to use this to learn Web Site Development with Microsoft WebMatrix or modify the application to host any “club” based web site (Kids Soccer team, bowling league, etc.)

THANKS

jQuery Confirm Buttons and Dialogs for ASP.NET

The ASP.NET Ajax Control Toolkit includes an “Confirm Button” control extender.
In this series I’ve been demonstrating ways to implement the features of the MS Ajax Toolkit with jQuery and in this post I’ll address the “Confirm Button Extender”.
You might think that doing this is so trivial that it wouldn’t warrant a blog post but there is more to it that you might guess at first glance.
In ASP.NET WebForms there is a definite abstraction of the underlying web application mechanics and, for the purposes of this subject there some issues we must consider.
  1. By default, ASP.NET WebForms is a SERVER side programming model and therefore all UI elements (ASP.NET Controls) with user interactions are assumed to have server-side logic.
  2. We are integrating Client AND Server Development Models.
  3. An ASPX (Web Forms) page is assumed to contain only ONE HTML form. (Though we can use advanced manual techniques to bypass this limitation)
  4. Given the above items 1 & 3, all <asp:button> controls render as HTML Submit elements.
So what does that mean ?
HTML actually has three button types :
  • <INPUT TYPE=BUTTON> // A button with a click event.
  • <INPUT TYPE=SUBMIT> // A button whose click posts the html form
  • <INPUT TYPE=RESET> // A button that causes form fields to be reset
So, ASP.NET Buttons all render to HTML SUBMIT buttons.
We can divide button triggered dialogs into two groups:
  • Ones that display something but have no need to SUBMIT The form
  • Ones that take user input and MIGHT submit the form.
Perhaps the most straight forward way to implement both of these categories of button click dialogs is to use input type=”button” for all our buttons and programmatically submit the form when appropriate.
I’ve created a collection on customized buttons with OnClick dialogs:
Each of these will implement different usages of the jQuery.Alert plugin you can find [ HERE ]
The first button is wired to an information only dialog that will display for (in our case) 3 seconds.
Lets look at the markup, the CSS and the page specific JavaScript and then we’ll enumerate the rest of the button behaviors.
The Markup looks like this :

<%@ Page Title='Home Page' Language='C#' MasterPageFile='~/Site.master'
         AutoEventWireup='true' CodeFile='Default.aspx.cs'
		 Inherits='_Default' %>

<asp:Content ID='HeaderContent' runat='server'
             ContentPlaceHolderID='HeadContent'>
<link href='Styles/jqdialog.css' rel='stylesheet' type='text/css' />
</asp:Content>
<asp:Content ID='BodyContent' runat='server'
             ContentPlaceHolderID='MainContent'>
<br />
<button ID='btnotify' type='button' class='CustomButton'>
        Notification Popup
</button><br /><br />
<button ID='btalert' type='button' class='CustomButton'>
        Alert Popup
</button><br /><br />
<button ID='btconfirm' type='button' class='CustomButton'>
        Confim Dialog
</button><br /><br />
<button ID='btprompt' type='button' class='CustomButton'>
        Input Prompt
</button><br /><br />
<button id='btcontent' type='button' class='CustomButton'>
        Any Custom Content
</button><br /><br />

<script src='http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.5.js'
        type='text/javascript'></script>
<script src='Scripts/jqdialog.min.js' type='text/javascript'></script>
<script src='Scripts/jQueryDialogs.js' type='text/javascript'></script>
</asp:Content>

Note that the concise markup does not reflect the rich functionality associated with the buttons.
The CSS class designation [class="CustomButton"] is responsible for the styled appearance of the buttons but not the behavior. Often when using jQuery we will use a data attribute or a class identifier to connect the desired jQuery code to the HTML elements but since button dialogs are likely to be very specific (one dialog for each button), the jQuery behaviors in this demo will be connection via the button element ID.
The CSS is as follows. Note that the Custom Button class is at the bottom and all the rest of the CSS defines the visuals for the various dialogs. In your app you would only include the classes that you use on your pages.

Using jQuery for ASP.NET Styled DropDown

The ASP.NET Ajax Control Toolkit includes an “Styled Dropdown” control extender.
In this series I’ve been demonstrating ways to implement the features of the MS Ajax Toolkit with jQuery.

HTML has the <select> element for drop down lists and ASP.NET has the DropDownList control, but the styling is pretty plain.

Luckily, we can us a jQuery plugin to change the styling of both <select> and <asp:DropDownList>
By default the DropDownList looks like this:

While this works fine we might want to style the DropDown to match our UI of to obviate the context of our dropdown.

You can find the plugin we will use here:
The custom styling will consist of a combination css and the following background image.

The page markup is as follows:

<%@ Page Title='Home Page' Language='C#' MasterPageFile='~/Site.master'
         AutoEventWireup='true' CodeFile='Default.aspx.cs'
		 Inherits='_Default' %>

<asp:Content ID='HeaderContent' runat='server'
             ContentPlaceHolderID='HeadContent'>
    <link href='Styles/Selectbox.css' rel='stylesheet' type='text/css' />
	<script src='http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.5.1.js'
            type='text/javascript' charset='utf-8'></script>
	<script type='text/javascript' src='Scripts/jquery.selectbox-0.5.js'>
	</script>
    <script src='Scripts/PageScript.js' type='text/javascript'></script>
</asp:Content>
<asp:Content ID='BodyContent' runat='server'
             ContentPlaceHolderID='MainContent'>
    <h2>
        Welcome to ASP.NET!
    </h2>
    <p>
        To learn more about ASP.NET visit
        <a href='http://www.asp.net' title='ASP.NET Website'>www.asp.net</a>.
    </p>

    <p>
    <asp:DropDownList runat='server' name='Items' id='Items'
                      class='StyledDD' ClientIDMode='Static'>
      <asp:ListItem>One</asp:ListItem>
      <asp:ListItem>Two</asp:ListItem>
      <asp:ListItem>Three</asp:ListItem>
      <asp:ListItem>Four</asp:ListItem>
    </asp:DropDownList>
    </p>
</asp:Content>

Read the rest of this entry »

Using jQuery for ASP.NET Textbox Autocomplete

The ASP.NET Ajax Control Toolkit includes an “Autocomplete Extender“.

In this series I’ve been demonstrating ways to implement the features of the MS Ajax Toolkit with jQuery.

jQuery UI makes “AutoComplete” very straight forward (Read the plugin spec here.)

Here is the behavior.

After the user enters 2 or more characters, then the UI starts to suggest values for the textbox.

In the case fo the jQuery UI Autocomplete plugin, the data can come from inside the page’s Document Object Model (DOM) or from a JavaScript callable web service.

For small data sets you may want to just send all the possible values to the browser with the rest of the page but AutoSuggest fields are most helpful when the number of possible value choices are too numerous to fit in a page’s dropdown control.

In this case, supplying the values via a service method is your choice and that’s what we’ll do in our example.

After creating a new website using the default ASP.NET Web Site Template, I’ll include a jQuery UI template CSS file and 3 JavaScript files.

  • jQuery
  • jQuery UI
  • a custom JavaScript file that contains my page specific code.

Then I’ll add an ASP.NET TextBox filed and associated label for the user to enter an email address in.

The markup for my default.aspx page is as follows:


<%@ Page Title='Home Page' Language='C#' MasterPageFile='~/Site.master'
         AutoEventWireup='true' CodeFile='Default.aspx.cs'
		                        Inherits='_Default' %>

<asp:Content ID='HeaderContent' runat='server'
             ContentPlaceHolderID='HeadContent'>
<link href='http://ajax.aspnetcdn.com/ajax/jquery.ui/
                   1.8.10/themes/redmond/jquery-ui.css'
      rel='stylesheet' type='text/css'/>

</asp:Content>
<asp:Content ID='BodyContent' runat='server'
                              ContentPlaceHolderID='MainContent'>
    <h2>
        Welcome to ASP.NET!
    </h2>
    <p>
        To learn more about ASP.NET visit
        <a href='http://www.asp.net' title='ASP.NET Website'>www.asp.net</a>.
    </p>
    <hr /><br />

    <div>
            <label for='tbAuto'>Enter Email: </label>
             <asp:TextBox ID='tbAuto' class='autosuggest' runat='server'>
             </asp:TextBox>
    </div>
    <script type='text/javascript'
            src='http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.5.js'>
    </script>
    <script type='text/javascript'
     src='http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.10/jquery-ui.js'>
    </script>
    <script src='Scripts/PageScript.js' type='text/javascript'></script>
</asp:Content>

Next we need a service that will take a few characters of string as in input argument and return a collection of emaill addresses that match the beginning characters that the user entered.

SO, I’ll add an .ASMX service called EmployeeList.asmx

The service codebehind looks like this:



using System.Collections.Generic;
using System.Linq;
using System.Web.Services;
using System.Web.Script.Services;

[WebService(Namespace = &quot;http://tempuri.org/&quot;)]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
public class EmployeeList : System.Web.Services.WebService
{
  [WebMethod]
    public List GetEmailSuggestions(string mail)
    {
    var emp = new Employee();
    var suggestionList = emp.GetEmployeeList()
    .Where(m => m.Email.ToLower().StartsWith(mail.ToLower()));
        return suggestionList.ToList();
    }
}

If you are new to service programming in ASP.NET you will note the [WebMethod] attribute on the GetMailSuggestions method will cause the method to be exposed via HTTP and the class itself is decorated with the [ScriptService] attribute which will make the class callable my JavaScript and provide facilities like JavaScript proxy generation.
Read the rest of this entry »

A jQuery Combo Box for ASP.NET

The ASP.NET Ajax Control Toolkit contains a Combo Box Control.

Since I’m posting a series on replacing Ajax Control Toolkit functions with jQuery, in this post we’ll use a jQuery plugin to DropDown control into a slick ComboBox.

Here is the experience :

You can click on the down arrow and see the entire list. Combo boxes excel in scenarios where there are MANY items in the selection set. (Usually to many to be seen without scrolling.

So  in a Combo Box we can type to filter the selection list based on what is types.

Since this is an ASP.NET control, when we submit the page we can access the selected value in our code-behind.

I’m building this using a jQuery Plugin called Hyjack.

[ Get it HERE ]

As with most jQuery plugins, Hyjack is simple to use.

NOTE: the code below includes all JavaScript code at the TOP of the page, uses in line JavaScript, and statically includes the jQuery library. This is done only for illustrative simplicity and is NOT best practice. Please find a variety of best practices information in the posts HERE.

Here is the complete page markup:



<%@ Page Title='Home Page' Language='C#' MasterPageFile='~/Site.master'
         AutoEventWireup='true' CodeBehind='Default.aspx.cs'
         Inherits='jQueryComboBox._Default' %>

<asp:Content ID='HeaderContent' runat='server'
             ContentPlaceHolderID='HeadContent'>
    <link href='Styles/hyjack.css' rel='stylesheet' type='text/css' />
    <script src='Scripts/jquery-1.4.1-vsdoc.js' type='text/javascript'>
	</script>
    <script src='Scripts/jquery.hyjack.select.js' type='text/javascript'>
	</script>
    <script type='text/javascript'>

		$(function () {

			// Hyjack Onload with all defaults
			$('.hyjack').hyjack_select();

			/* Multiple CLASS with customization

			$('.hyjack').hyjack_select({        // Defaults
			ddImage: 'image/of/arrow.png',      // arrow_down.png
			ddCancel: 'image/of/cancel.png',    // cancel.png
			ddImageClass: 'class_of_arrow',     // hjsel_ddImage
			ddCancelClass: 'class_of_cancel',   // hjsel_ddCancel
			emptyMessage: 'No Items Message',   // No Items to Display
			restrictSearch: false/true,         // false
			offset: 12                          // false
			});

			*/
        });
	</script>

</asp:Content>
<asp:Content ID='BodyContent' runat='server'
             ContentPlaceHolderID='MainContent'>
    <h2>
        Select Your State
    </h2>
    <br /><br />
    <asp:DropDownList ID='DDPickState'  class='hyjack' runat='server'>
        <asp:ListItem Value='AL'>Alabama</asp:ListItem>
        <asp:ListItem Value='AK'>Alaska</asp:ListItem>
        <asp:ListItem Value='AZ'>Arizona</asp:ListItem>
        <asp:ListItem Value='AR'>Arkansas</asp:ListItem>
        <asp:ListItem Value='CA'>California</asp:ListItem>
        <asp:ListItem Value='CO'>Colorado</asp:ListItem>
        <asp:ListItem Value='CT'>Connecticut</asp:ListItem>
        <asp:ListItem Value='DC'>District of Columbia</asp:ListItem>
        <asp:ListItem Value='DE'>Delaware</asp:ListItem>
        <asp:ListItem Value='FL'>Florida</asp:ListItem>
        <asp:ListItem Value='GA'>Georgia</asp:ListItem>
        <asp:ListItem Value='HI'>Hawaii</asp:ListItem>
        <asp:ListItem Value='ID'>Idaho</asp:ListItem>
        <asp:ListItem Value='IL'>Illinois</asp:ListItem>
        <asp:ListItem Value='IN'>Indiana</asp:ListItem>
        <asp:ListItem Value='IA'>Iowa</asp:ListItem>
        <asp:ListItem Value='KS'>Kansas</asp:ListItem>
        <asp:ListItem Value='KY'>Kentucky</asp:ListItem>
        <asp:ListItem Value='LA'>Louisiana</asp:ListItem>
        <asp:ListItem Value='ME'>Maine</asp:ListItem>
        <asp:ListItem Value='MD'>Maryland</asp:ListItem>
        <asp:ListItem Value='MA'>Massachusetts</asp:ListItem>
        <asp:ListItem Value='MI'>Michigan</asp:ListItem>
        <asp:ListItem Value='MN'>Minnesota</asp:ListItem>
        <asp:ListItem Value='MS'>Mississippi</asp:ListItem>
        <asp:ListItem Value='MO'>Missouri</asp:ListItem>
        <asp:ListItem Value='MT'>Montana</asp:ListItem>
        <asp:ListItem Value='NE'>Nebraska</asp:ListItem>
        <asp:ListItem Value='NV'>Nevada</asp:ListItem>
        <asp:ListItem Value='NH'>New Hampshire</asp:ListItem>
        <asp:ListItem Value='NJ'>New Jersey</asp:ListItem>
        <asp:ListItem Value='NM'>New Mexico</asp:ListItem>
        <asp:ListItem Value='NY'>New York</asp:ListItem>
        <asp:ListItem Value='NC'>North Carolina</asp:ListItem>
        <asp:ListItem Value='ND'>North Dakota</asp:ListItem>
        <asp:ListItem Value='OH'>Ohio</asp:ListItem>
        <asp:ListItem Value='OK'>Oklahoma</asp:ListItem>
        <asp:ListItem Value='OR'>Oregon</asp:ListItem>
        <asp:ListItem Value='PA'>Pennsylvania</asp:ListItem>
        <asp:ListItem Value='RI'>Rhode Island</asp:ListItem>
        <asp:ListItem Value='SC'>South Carolina</asp:ListItem>
        <asp:ListItem Value='SD'>South Dakota</asp:ListItem>
        <asp:ListItem Value='TN'>Tennessee</asp:ListItem>
        <asp:ListItem Value='TX'>Texas</asp:ListItem>
        <asp:ListItem Value='UT'>Utah</asp:ListItem>
        <asp:ListItem Value='VT'>Vermont</asp:ListItem>
        <asp:ListItem Value='VA'>Virginia</asp:ListItem>
        <asp:ListItem Value='WA'>Washington</asp:ListItem>
        <asp:ListItem Value='WV'>West Virginia</asp:ListItem>
        <asp:ListItem Value='WI'>Wisconsin</asp:ListItem>
        <asp:ListItem Value='WY'>Wyoming</asp:ListItem>
    </asp:DropDownList>
    <br /><br />
    <asp:Button ID='ButtonSubmit' runat='server' Text='Submit'
        onclick='ButtonSubmit_Click' /><br /><br />
    <asp:Label ID='LabelResult' runat='server' Text=''></asp:Label>
</asp:Content>

And here is the code behind.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace jQueryComboBox
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
        }

        protected void ButtonSubmit_Click(object sender, EventArgs e)
        {
            LabelResult.Text = &quot;The State You Picked is : &quot; +
                                DDPickState.SelectedValue.ToString();
        }
    }
}

I’ve statically defined the list items but since the parrent control is an ASP.NET Drop Down, you could easily bind the items list to a data source of your choosing.

[ You can download the code above HERE ]


Improving the Code – jQuery Modal Dialog in an ASP.NET page.

Last month I did this post on creating a jQuery Modal Dialog in an ASP.NET page.

My friend Jose Guay emailed me to say “hey Joe – nice sample but why not really wire things up the jQuery way ?”

Jose’s right so here it is.

The OLD markup looked like this:


<asp:Content ID='HeaderContent' runat='server'
             ContentPlaceHolderID='HeadContent'>
    <link href='Scripts/fancybox/jquery.fancybox-1.3.4.css'
          rel='stylesheet' type='text/css' />
    <script src='Scripts/fancybox/jquery.fancybox-1.3.4.js'
	        type='text/javascript'>
    </script>
    <script src='Scripts/tos.js' type='text/javascript'></script>
</asp:Content>
<asp:Content ID='BodyContent' runat='server'
             ContentPlaceHolderID='MainContent'>
    <h2>
        Welcome to ASP.NET!
    </h2>
    <p>
        To learn more about ASP.NET visit
        <a href='http://www.asp.net' title='ASP.NET Website'>www.asp.net</a>.
    </p>
    <div id='content'>
	<h1>Join Our Community</h1>
	<hr />
	Lorem ipsum dolor sit amet, consectetur adipiscing elit. <br /><br />
	Etiam quis mi eu elit tempor facilisis id et neque.
	Nulla sit amet sem sapien. Vestibulum imperdiet porta ante ac ornare.
	Nulla et lorem eu nibh adipiscing ultricies nec at lacus. Cras laoreet
	ultricies sem, at blandit mi eleifend aliquam. Nunc enim ipsum,
	vehicula non pretium varius, cursus ac tortor. Vivamus fringilla
	laoreet. Quisque ultrices sodales orci, quis rhoncus justo auctor in.
	Phasellus dui eros, bibendum eu feugiat ornare, faucibus eu mi. Nunc
	aliquet tempus sem, id aliquam diam varius ac.
    <hr />
    <br />
    <!-- Modal Dialog -->
    <a id='tos' href='#serviceterms'
	   title='You must agree with our tems of service.'>
       Click HERE to Agree to our Terms
    </a>
    <div style='display: none;'>
	<div id='serviceterms' style='width:440px;height:250px;overflow:auto;'>
		Lorem ipsum dolor sit amet, consectetur adipiscing elit. <br /><br />
		Etiam quis mi eu elit tempor facilisis id et neque.
		Nulla sit amet sem sapien. Vestibulum imperdiet porta ante ac ornare.
		Nulla et lorem eu nibh adipiscing ultricies nec at lacus. Cras
		ultricies sem, at blandit mi eleifend aliquam. Nunc enim ipsum,
		vehicula non pretium varius, cursus ac tortor. Vivamus fringilla
		laoreet. Quisque ultrices sodales orci, quis rhoncus justo auctor in.
		Phasellus dui eros, bibendum eu feugiat ornare, faucibus eu mi. Nunc
		aliquet tempus sem, id aliquam diam varius ac.
		<br /><br /><hr />
		<input type='button' value='Yes' onclick='ToS_Agree()' />&nbsp;&nbsp;
		<input type='button' value='No' onclick='ToS_NotAgree()' />
	</div>
	</div>
    <br /><br />

    <asp:Button ID='SubmitButton' runat='server' Text='Submit Form'
	            Enabled='False'
                ClientIDMode='Static' onclick='SubmitButton_Click' />
        <br /><br />
    <asp:Label ID='LabelResult' runat='server' Text=''></asp:Label>

</div>
</asp:Content>

And the included JavaScript (tos.js) looked like this:


$(document).ready(function () {

    $('#tos').fancybox({
    	'titlePosition': 'inside',
    	'modal': 'true',
    	'transitionIn': 'none',
    	'transitionOut': 'none'
    });
});

function ToS_Agree() {
    $('#SubmitButton').removeAttr('disabled');
    $.fancybox.close();
}

function ToS_NotAgree() {
    $('#SubmitButton').attr('disabled', 'disabled');
    $.fancybox.close();
}

So, I am sort of mixing metaphor’s here.

Lets look at a better way.

Read the rest of this entry »

Microsoft Application Request Routing (ARR) 2.5 released.

Overview:
Application Request Routing v2.5 improves the performance and the scalability of ARR in its disk caching scenarios.   In addition to fully incorporating the enhancements described in KB 2406763, it includes additional optimizations to balance the use of memory and disk caching.   The use of this release is especially recommended to those who are extensively using the disk caching features in ARR.

Download ARRv2.5 from:
ARRv2.5 is available only via Web Platform Installer (WebPI). Download ARRv2.5 via WebPI here.
The download pages for ARRv2.5 can be found at:

  • Microsoft Application Request Routing Version 2.5 (x86) here.
  • Microsoft Application Request Routing Version 2.5 (x64) here.

Features:
ARRv2.5 is mostly a performance and scalability focused release, so there is little functional difference between ARRv2.1 and ARRv2.5.   However, when it comes to disk caching performance and scalability, including latency improvements, there are significant differences between ARRv2.1 and ARRv2.5.
One functional change that is worth mentioning is the ability to set the client affinity cookie on the main domain name.   This particularly interesting if the site has multiple sub-domains, such as images.contoso.com, members.contoso.com and so on.   On such sites, in order to maintain client affinity across sub-domains, the client affinity can be set on the main domain, .contoso.com.

Support:
ARRv2.5 is a fully release version and therefore the support is provided via Microsoft Support.   In addition, the ARR forum is a great place to connect with the community, including the ARR product team.

A jQuery Color Picker for ASP.NET Apps

There are lots of “ColorPickers” out there.

I liked the way mColorPicker worked, though did make some minor modifications to the source for this demo.

Just picking a color is a bit boring so I’m adding a bit of spice.

  1. After selecting a new color client side I use that color to change the background color of the current page (no postback)
  2. Upon Server PostBack we echo the hex value of the selected color.

Here is the experience.


Note the TextBox which is an ASP.NET TextBox Server Control and the multi-color icon nect to the text box.

Clicking on the color icon displays the ColorPicker.

As you hover over the different colors the hex value of the current color is displayed in the TextBox and the TextBox background color is set to that color as well.

The “Set Color” Button is an HTML input element (Client Side) and when you click it, the background color of the page is set to the newly selected color (as you can see in the image above.)

The “Submit Form” Button is an ASP.NET Server Side Button Control and when you click it the form is posted back to the server.

The new color value is retrieved from the Color Text Box and is inserted into the Label control at the bottom of the page.

Note that after the page is submitted (and therefore redrawn) the page’s background revert to its default color. If you wanted to make the selected color permanent we would need to dynamically load the background color from somewhere and save the updated color whenever the user selected a new one.
Feel free to give that a try on your own if you need such a feature.

To implement this, begin by loading the jQuery and jQueryUI libraries.

I’ll do this in my MasterPage and load them from the Microsoft CDN (which means you’ll have to modify the following code if want to run this on a machine that is not connected to the internet.)


<script type="text/javascript"
        src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.5.js"></script>
<script type="text/javascript"
        src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.10/jquery-ui.js">

The actual page markup look like this.
Read the rest of this entry »

A Collapsible Content Area Using jQuery UI

As I’m going though all of the Ajax Control Toolkit Controls and demonstrating ways to replace the behaviors with client side technology (JavaScript / jQuery) I can’t help but wonder if some of them are too simple to bother with but since I committed to blogging one example for each control in the ACT, I will continue and then move on to more “Ajax and UI Patterns” content.

I did a previous post on implementing an Accordion style Content Container using jQueryUI and thereby replacing the Accordion Control in the Ajax Control Toolkit.

I suppose you could use the Accurdion method that I demonstrated in that post and only use one accordion section but there is an even easier jQueryUI plugin that you can use. Check put the Simple Collapsible Panel plugin HERE.

If you have tried a number of jQuery UI Plugins using the default ASP.NET Web Site Template and ASP.NET Server controls you have probably discovered that it’s possible to discover conflicts.

Lets try it with ths Collapsible Panel Plugin.

We’re going to need jQuery and jQueryUI which I will include as follows.


<asp:Content ID='HeaderContent' runat='server'
             ContentPlaceHolderID='HeadContent'>
<link href='Styles/diQuery-collapsiblePanel.css' rel='stylesheet'
            type='text/css' />
<link href='Styles/jquery-ui-1.8.11.custom.css' rel='stylesheet'
            type='text/css' />
<script src='Scripts/jquery-1.4.1-vsdoc.js' type='text/javascript'>
</script>
<script src='Scripts/ui/jquery-ui-1.8.11.custom.js' type='text/javascript'>
</script>
<script src='Scripts/diQuery-collapsiblePanel.js' type='text/javascript'>
</script>
    <script type='text/javascript'>
            $(document).ready(function() {
                  $('.collapsibleContainer').collapsiblePanel();
              });
    </script>
</asp:Content>

Now, for demo simplicity there are a few things above that you probbaly do not want to do in a production application.

  1. I used the default version of jQuery that is part of the default ASP.NET project template. You should use the LATEST version of jQuery.
  2. You probably want to load jQuery from the Microsoft CDN
  3. You also probbaly want to load jQueryUI from the Microsoft CDN
  4. It’s good practive to put all your JavaScript code in a .js file
  5. Whenever possible you want to reference your JavaScript files from the bottom of your page markup. [ Read HERE ]

Read the rest of this entry »

jQuery Modal Dialog in an ASP.NET page.

Modal dialogs are a cornerstone of modern application user interface design and web applications don’t differ from any other type of application UI in this regard.
I did a JavaScript & jQuery Modal Dialogs Roundup a little while back and though I listed a bunch, readers even added a few more. So, there are lots of options.
People seem to get freaked out about making choices. Personally I like the fact that I have so many options and, in the case of Modal Dialogs for web applications, I can pick one that most closely matches the aesthetics and behaviors that I want for my application.
For this post I’m going to use http://fancybox.net/
Which one YOU choose shouldn’t materially change your implementation strategy since, as I hope is starting to become clear, the tricky part in using these sort of jQuery features is the relationship between client side “stuff (HTML Elements, JavaScript, Data, etc.) and the ASP.NET specific things.
Next lets add the jQuery library to our masterpage.
Normally for demo code I use the static librraies that get added to my site directory by VIsual Studio, but in a prodocution wed site you probbaly want to use the Microsoft CDN.
Like this :

<head runat='server'>
    <title></title>
    <link href='~/Styles/Site.css' rel='stylesheet' type='text/css' />
    <script src='http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.5.1.js'
            type='text/javascript'></script>
    <asp:ContentPlaceHolder ID='HeadContent' runat='server'>
	</asp:ContentPlaceHolder>
</head>

Why use the CDN you say?
  • The CDN has the latest released versions. The Visual Studio template has the version that was current back when Visual Studio 2010 was released.
  • Many ASP.NET sites use jQuery and load from the Microsoft CDN – the files may already be cached for your user.
  • If if the files are not cached it will likely be a bit faster.
  • Take load of YOUR server and reduce your server’s bandwidth.
The page that will display our Modal Dialog pulls in the FancyBox JavaScript and CSS files as well as our own custom JavaScript file that defines the client behavior we desire.
For learning simplicity I’ve previously implemented our custom JavaScript in-line but in practice, it’s better to abstract or JavaScript.
Now that we are getting familiar with the jQuery basics I’ll be trying to use more “best practices” in the demo code as I continue with the jQuery series.

<asp:Content ID='HeaderContent' runat='server'
             ContentPlaceHolderID='HeadContent'>
    <link href='Scripts/fancybox/jquery.fancybox-1.3.4.css'
          rel='stylesheet' type='text/css' />
    <script src='Scripts/fancybox/jquery.fancybox-1.3.4.js'
	        type='text/javascript'>
    </script>
    <script src='Scripts/tos.js' type='text/javascript'></script>
</asp:Content>

Our scenario is that the Modal Popup is a “Terms of Use” dialog.
Here is our page’s markup.


<asp:Content ID='BodyContent' runat='server'
             ContentPlaceHolderID='MainContent'>
    <h2>
        Welcome to ASP.NET!
    </h2>
    <p>
        To learn more about ASP.NET visit
        <a href='http://www.asp.net' title='ASP.NET Website'>www.asp.net</a>.
    </p>
    <div id='content'>
	<h1>Join Our Community</h1>
	<hr />
	Lorem ipsum dolor sit amet, consectetur adipiscing elit. <br /><br />
	Etiam quis mi eu elit tempor facilisis id et neque.
	Nulla sit amet sem sapien. Vestibulum imperdiet porta ante ac ornare.
	Nulla et lorem eu nibh adipiscing ultricies nec at lacus. Cras laoreet
	ultricies sem, at blandit mi eleifend aliquam. Nunc enim ipsum,
	vehicula non pretium varius, cursus ac tortor. Vivamus fringilla congue
	laoreet. Quisque ultrices sodales orci, quis rhoncus justo auctor in.
	Phasellus dui eros, bibendum eu feugiat ornare, faucibus eu mi. Nunc
	aliquet tempus sem, id aliquam diam varius ac.
    <hr />
    <br />
    <!-- Modal Dialog -->
    <a id='tos' href='#serviceterms'
	   title='You must agree with our tems of service.'>
        Click HERE to Agree to our Terms
    </a>
    <div style='display: none;'>
	<div id='serviceterms' style='width:440px;height:250px;overflow:auto;'>
	Lorem ipsum dolor sit amet, consectetur adipiscing elit. <br /><br />
	Etiam quis mi eu elit tempor facilisis id et neque.
	Nulla sit amet sem sapien. Vestibulum imperdiet porta ante ac ornare.
	Nulla et lorem eu nibh adipiscing ultricies nec at lacus. Cras laoreet
	ultricies sem, at blandit mi eleifend aliquam. Nunc enim ipsum,
	vehicula non pretium varius, cursus ac tortor. Vivamus fringilla congue
	laoreet. Quisque ultrices sodales orci, quis rhoncus justo auctor in.
	Phasellus dui eros, bibendum eu feugiat ornare, faucibus eu mi. Nunc
	aliquet tempus sem, id aliquam diam varius ac.
	<br /><br /><hr />
	<input type='button' value='Yes' onclick='ToS_Agree()' />&nbsp;&nbsp;
	<input type='button' value='No' onclick='ToS_NotAgree()' />
	</div>
	    </div>
    <br /><br />

    <asp:Button ID='SubmitButton' runat='server' Text='Submit Form'
	            Enabled='False'
                ClientIDMode='Static' onclick='SubmitButton_Click' />
        <br /><br />
    <asp:Label ID='LabelResult' runat='server' Text=''></asp:Label>

</div>
</asp:Content>

Note the buttons on lines 39 and 40. We want our Modal Dialog to “actionable” in that the user must click YES to accept the terms of service or NO to reject them.
In order to submit the form the user must accept the terms of service. The submit button declared at line 45 is DISABLED by default to the form can’t be submitted.
When the user clicks on the “YES” button inside the Modal Dialog the button will be enabled.
Let’s look at our custom JavaScript.

$(document).ready(function () {

    $('#tos').fancybox({
    	'titlePosition': 'inside',
    	'modal': 'true',
    	'transitionIn': 'none',
    	'transitionOut': 'none'
    });
});

function ToS_Agree() {
    $('#SubmitButton').removeAttr('disabled');
    $.fancybox.close();
}

function ToS_NotAgree() {
    $('#SubmitButton').attr('disabled', 'disabled');
    $.fancybox.close();
}

We also have a bit of C# Code-Behind that does two things.

Using jQuery UI DatePicker in an ASP.NET Application.

The Ajax Control Toolkit contains a Calendar Control.

jQuery UI has an amazing alternative in the DatePicker control.

When it comes to this and all jQueryUI features, do yourself a service and check out the tabs – Overview, Options, Events, Methods, Theming. In the case of the DatePicker control, not only are all the expected events exposed and hookable but the rich Options collection will let you exercise detailed control over the date and UI formatting.

If you’re new to jQuery UI you will note that when you download the jQueryUI you can select one of a collection of preexisting themes.

Let’s begin by walking through the process of getting the jQueryUI library.

Start by hoping over to http://jqueryui.com/

We need to select a theme to use for configuring our jQueryUI download, so click on the “Demos & Documentation” link at the top of the page.

AT the top right corner of the demo area of the page there is drop-down with theme previews. Select a theme to try and then run the demos to see how that particular feature looks using the selected theme.

In our case we’ll select the Redmond Theme.

Now, go to the download page.

Read the rest of this entry »

Podcast- Erik Porter – ASP.NET Pages (WebMatrix) & Razor

Erik Porter is a PM in Microsoft Web Platform and Tools Group and responsible for ASP.NET Web Pages (WebMatrix) and the Razor Syntax.

In this episode, we discuss the success of WebMatrix and Razor, What’s New, and What the team is planning to do going forward.

Resources

Listen

Get Microsoft Silverlight

Subscribe

MP3 WMA M4A Zune iPod

Download

3GP File
3GP
iPod File
iPod
MP4 File
MP4
MP3 File
MP3
M4A File
M4A
M4V File
M4V
PSP File
PSP
WMV File
WMV
ZIP File
Zip
WMA File
WMA
Zune File
Zune

ASP.NET Accordions with jQueryUI

Replacing the Ajax Control Toolkit’s Accordion control with jQueryUI

Accordion style containers are a great way to maximize the use of your browser based screen real estate.

Note the UI and behavior of an Accordion Content Control.

The default display looks like this.

Clicking on the second header bar closes the first content area and opens the second.

Some time ago I did a video on using Accordions with the ASP.NET AJAX Control Toolkit. You can check it out here.

The thing about accordion controls is the the content exists in HTML <div> elements which means we can populate them with static markup, server side controls, of even markup retrieved by way of an AJAX service method call and inserted by our client side JavaScript code.

There are many JavaScript libraries and jQuery Plug-Ins that can assist us in implementing an accordion container. In this case I’ll use one of the most popular, the jQueryUI library.

http://jqueryui.com/

jQueryUI is highly configurable as we’re about to see.

First, click the demos link.

Though we’re specifically interested in the Accordion demo, you should take time to look at the other demos to see some of the other things that can be accomplished with jQueryUI.

Note that after you load the Accordion demo you can try different color “themes” by using the themes selector on the left.

When you’ve decided which theme you are interested in using as a starting place you need to download jQueryUI.

Read the rest of this entry »

A collection of ASP.NET Tutorials Cool How Tos (44)

Learn


Web Development 101 using WebMatrix
Web Development 101: Part 1, Getting Started with WebMatrix
Web Development 101: Part 2, Create your first Web Page
Web Development 101: Part 3, Getting some style
Web Development 101: Part 4, Using Layout
Web Development 101: Part 5, Using Data
Web Development 101: Part 6, Creating an Add Data page
Web Development 101: Part 7, Creating an Edit Data Page
Web Development 101: Part 8, Creating a Delete Data page
Web Development 101: Part 9, Deploying your site
Introduction to CSS
Learn HTML: Part 2
Learn HTML: Part 1
Introduction to JavaScript: Part 3 of 3
Introduction to JavaScript: Part 2 of 3
Introduction to JavaScript, Part 1 of 3


How To


Understanding MySQL Errors when installing Web Apps in WebMatrix
Set Up a Simple Theme for Your Website Using WebMatrix
Using the Windows Live Translator API
Using the Bing Maps API
Using Facebook Helpers on your Website
Quickly add other languages to your site using automatic translation
Create and Sell Merchandise with the Zazzle API on your website
Using the Hulu widgets to add TV to your site
Add driving directions to your site with Bing Maps
Add a photo gallery to your website using Lightbox and JavaScript
Improve Your Website Using the WebMatrix SEO Report
Get Started with SEO using WebMatrix
Using the free Bing Translation APIs
Build a Web Site in twenty minutes using WordPress and WebMatrix
Creating forms for your site using EmailMeForm
Use LightBox for beautiful Images on your web site


Walkthroughs


Installing Umbraco with WebMatrix.
Using BlogEngine.NET with WebMatrix
Installing ScrewTurn Wiki using WebMatrix
Getting started with Joomla and WebMatrix
Set Up a Simple Theme for Your Website Using WebMatrix
WebMatrix and Drupal: Build a site in 15 minutes
Using WebMatrix to build a DotNetNuke Application
Settting Up your NopCommerce website using WebMatrix
Installing, Configuring, and Publishing your Umbraco site with WebMatrix
Installing and Publishing Orchard using WebMatrix
Installing and Publishing a WordPress Blog with WebMatrix
Improve Your Website Using the WebMatrix SEO Report


Dynamic Cascading Selection Lists for ASP.NET WebForms with jQuery.

I’ve blogged previously that I’m on a mission to build samples of implementing all the ASP.NET Ajax Control Toolkit Features WITHOUT the Ajax Control Toolkit.

If you’re ever used the Cascading Drop Down control extender in the Ajax Control Toolkit, then you know that it’s syntactically easy to use but a real pain to debug.

You may have also discovered that any JavaScript code that effects the state of an ASP.NET Drop Down Control has it’s influence lost when you submit your form back to the server.

This is due to a collection of tomfoolery that happens under the covers with the Drop Down control as it pertains to ASP.NET View State.

To side step the ViewState complexities, we’ll do all the Cascading Drop Down UI on the client and only use ASP.NET Server controls the minimal amount necessary to easily post our selected values back to the server.

Here is the UI interaction flow that we want.

This is the way that the page renders.

Then the user selects from the list of car Makes.

Note that at this point, ONLY the Car “Makes” list is populated.

We can’t display the models until we know what “Make” the user is interested in.

As a result, the “Models” and “Colors” controls are not even active yet.

After we select a car “Make”, the “Models” Drop Down has been filled with values as the result of an AJAX call to the server that passes the “Make” value as an argument so that the related “Models” can be returned.

The same happens when we select a “Model”.

The colors that the model is available in now appear in the “Colors” Drop Down.

When the user has selected a value in each of the three text boxes and clicks the Submit Button, the ASP.NET’ page’s Code-Behind Retreives the selected values and displays a result message.

There is, however, a but of trickery necessary to make this happen.

First, the Drop-Dwn lists are NOT ASP.NET Server Controls, they are simple HTML <select> elements.

This first one (Makes) is populated with statically defined values but you could populate them from a service call when the page loads if you felt it neccessary.

New car companies don’t come into existance very often, so I don’t think it’s necessary in this case.


    <div id='SelectionContainer' runat='server'>
    <select id='DDListMake' name='DDListMake' style='width: 200px'>
		<option>Select...</option>
		<option value='Ford'>Ford</option>
		<option value='Cadilac'>Cadilac</option>
		<option value='Toyota'>Toyota</option>
		<option value='Jeep'>Jeep</option>
		<option value='Mazda'>Mazda</option>
	</select>
    <asp:HiddenField ID='TextMake' runat='server' ClientIDMode='Static' />
    <br />
    <select id='DDListModels' style='width: 200px' disabled='true'></select>
    <asp:HiddenField ID='TextModel' runat='server' ClientIDMode='Static' />
    <br />
    <select id='DDListColors' style='width: 200px' disabled='true'></select>
    <asp:HiddenField ID='TextColor' runat='server' ClientIDMode='Static' />
    <br /><br />
    <asp:Button ID='ButtonSend' runat='server' Text='Submit Selections'
                onclick='ButtonSend_Click' />
    </div>
    <asp:Label ID='LabelResult' runat='server' Text=''></asp:Label>

Note that the Drop Down Lists are simple HTML Select Elements.

The Button and the Label are ASP.NET controls.

Take special note of the three “Hidden” ASP.NET contol instances.

We will populate these with the values that the user selects in each Drop Down so that we can retrieve those values in our code-behind.

Implementing the simplest possible web service.

The .NET platform is rife with ways to serve up content via HTTP.

We have ASMX, ASPX, ASHX, WCF, MVC Views, all of which could be used to serve non markup data.

Read the rest of this entry »

TextBox Input Watermark using jQuery

The Microsoft Ajax Control Toolkit (ACT) contains a TextBox Watermark control.

I did a sample and video HERE.

I’ve started to write samples to implement all the ACT features with jQuery (and jQuery plugins), you can read more HERE.

Here is the effect we’re looking for, a hint to the user as to the desired or required input (note this sampe doesn’t do input validation, we’ll do that in a later demo.)

To get this we’re going to use jQuery and the TinyWatermark jQuery plugin.

The effect is completely applied in our markup. There is no server side implementation.

I like this as I prefer to off load as much work as possible to the client machine.


<%@ Page Title='Home Page' Language='C#' MasterPageFile='~/Site.master'
                 AutoEventWireup='true' CodeFile='Default.aspx.cs'
 Inherits='_Default' %>
<asp:Content ID='HeaderContent' runat='server'
             ContentPlaceHolderID='HeadContent'>
    <script src='Scripts/jquery-1.4.1-vsdoc.js' type='text/javascript'>
</script>
    <script src='Scripts/jquery_tinywatermark-3_1_0.js'
        type='text/javascript'>
    </script>
    <style>
        .watermark
        {
        color:#999;
        background-color: #FFD4D4;
        font-style: italic;
        }
    </style>
    <script type='text/JavaScript'>
        jQuery(function ($) {
            $('.watermarked').watermark('watermark');
        });
    </script>
</asp:Content>
<asp:Content ID='BodyContent' runat='server'
             ContentPlaceHolderID='MainContent'>
    <h2>
        Welcome to ASP.NET!
    </h2>
    <p>
        To learn more about ASP.NET visit
        <a href='http://www.asp.net'
		   title='ASP.NET Website'>www.asp.net</a>.
    </p>
    <p>
        Please enter your email address here ......<br />
        <input type='text' class='watermarked' size='50'
                  title='Enter Email Address here...' />
    </p>
</asp:Content>

Note that in the “HeadContent” placeholder I pull in jQuery and the TinyWatermark jQuery Plugin. (I’m using the VSDOC version for the best experience in Visual Studio but you should use the MIN version in production, and consider using the Microsoft CDN

Starting on line 7 I specify a style to be used for the watermark (and names .watermark)

Any texbox that I want to be watermarked I set it’s class=watermark

Note also that the jQuery plugin will use the title attribute as the text to displain in the textbox when the watermark is active as set on line 31.

Then all we have to do is simple apply the JavaScrpt function that begins on line 16.

You can download a runnable sample [ HERE ]


ASP.NET Rounded Coreners AND DropShadow with jQuery.

I’ve started blogging examples of how to replace Microsoft AJAX and the Ajax Control Toolkit usages with jQuery based equivalents.

In this post I showed how to replace the ACT’s Rounded Corner Extender with jQuery and in this one I demonstrated how to replace the Drop Shadow control extender with jQuery.

But lots of folks want to do both at the same time like this.

For this I’m going to use yet another jQuery Plugin – Liquid Canvas.

The code below also demonstrates two different styles of applying the effect. One targets elements with a specific ID and the other targets any element that uses a particular CSS class.



<%@ Page Title='Home Page' Language='C#' MasterPageFile='~/Site.master'
         AutoEventWireup='true' CodeFile='Default.aspx.cs'
		 Inherits='_Default' %>
<asp:Content ID='HeaderContent' runat='server'
             ContentPlaceHolderID='HeadContent'>
    <!--[if IE]>
    <SCRIPT type=text/javascript
    src='Styless/excanvas.js'></SCRIPT>
    <![endif]-->
    <script src='Scripts/excanvas.js' type='text/javascript'></script>
    <script src='Scripts/liquid-canvas.js' type='text/javascript'></script>
    <script src='Scripts/liquid-canvas-plugins.js' type='text/javascript'>
	</script>
    <SCRIPT type=text/javascript>
      $(window).load(function() {
          $('#Panel1').liquidCanvas(
            '[shadow fill] => roundedRect{radius:10}');
          $('.rounded').liquidCanvas(
            '[shadow fill] => roundedRect{radius:10}');
      });
    </SCRIPT>
</asp:Content>
<asp:Content ID='BodyContent' runat='server'
     ContentPlaceHolderID='MainContent'>
    <h2>Welcome to ASP.NET!</h2>
    <br /><br />
    <asp:Panel ID='Panel1' runat='server' ClientIDMode='Static'
	                                      style='width: 400px;'>
      <p>&amp;nbsp;&amp;nbsp;&amp;nbsp;Some Developer Links</p>
	  <ol>
	    <li>
		<a href='http://misfitgeek.com' target='_blank'>Developer Link 1</a>
		</li>
		<li>
		<a href='http://misfitgeek.com' target='_blank'>Developer Link 2</a>
		</li>
		<li>
		<a href='http://misfitgeek.com' target='_blank'>Developer Link 3</a>
		</li>
		<li>
		<a href='http://misfitgeek.com' target='_blank'>Developer Link 4</a>
		</li>
		<li>
		<a href='http://misfitgeek.com' target='_blank'>Developer Link 5</a>
		</li>
      </ol>
    </asp:Panel>
    <br /><br />
    <asp:Panel ID='Panel2' runat='server' ClientIDMode='Static'
	           style='width: 400px;'
               class='rounded'>
      <p>&amp;nbsp;&amp;nbsp;&amp;nbsp;Some Developer Links</p>
	  <ol>
	    <li>
		<a href='http://misfitgeek.com' target='_blank'>Developer Link 1</a>
		</li>
		<li>
		<a href='http://misfitgeek.com' target='_blank'>Developer Link 2</a>
		</li>
		<li>
		<a href='http://misfitgeek.com' target='_blank'>Developer Link 3</a>
		</li>
		<li>
		<a href='http://misfitgeek.com' target='_blank'>Developer Link 4</a>
		</li>
		<li>
		<a href='http://misfitgeek.com' target='_blank'>Developer Link 5</a>
		</li>
      </ol>
    </asp:Panel>
</asp:Content>

The previous posts demonstrate perfectly viable ways to achieve a specific effect, in concert these posts also demonstrate that jQuery has a broad and growing eccosystem and that there are multiple ways to accomplish any given task or effect.

I highly erncourage you to dig deeper into Liquid Canvas as it ofer FAR more functionality than presented in this post.


ASP.NET DropShadow with jQuery.

As I started in this blog post, I’m creating jQuery based samples for all of my origional Ajax and Ajax Control Toolkit guidance. (Find it here.)

In this video I demonstrated adding “DropShadow” visual effects to ASP.NET controls using the DropShadow Control Extender from the ASP.NET Ajax Control Toolkit.

As you might expect, and as you are probably getting used to hearing, “there’s a jQuery Plugin for that”.

You can grab the jQuery “Drop Shadow” plugin HERE.

One of the super powerful things about jQuery is that you can easily select (and apply attributes) via a number of criteria like CSS Class, Element Id, type, etc. For an introductory tutorial on jQuer Selectors read here, for the API documentation read here.

We can add a dropshadow to an ASP.NET container by assigning that container a specific CSS class or ClientId. (Please review ASP.NET 4′s ClientId features HERE.)

It will look like this.

and the code looks like this…..


<%@ Page Title='Home Page' Language='C#' MasterPageFile='~/Site.master'
         AutoEventWireup='true' CodeFile='Default.aspx.cs'
		 Inherits='_Default' %>
<asp:Content ID='HeaderContent' runat='server'
             ContentPlaceHolderID='HeadContent'>
    <script src='Scripts/jquery.dropshadow.js' type='text/javascript'>
	</script>
    <script type='text/javascript'>
            $(document).ready(function () {
                $('.rounded').redrawShadow();
                $('#Panel3').redrawShadow();
            });
    </script>
</asp:Content>
<asp:Content ID='BodyContent' runat='server'
     ContentPlaceHolderID='MainContent'>
    <h2>Welcome to ASP.NET!</h2>
    <br />
    <asp:Panel ID='Panel1' runat='server' ClientIDMode='Static'
               style='background-color:#acc; padding:5px; width: 400px;'>
      <p>&amp;nbsp;Some Developer Links</p>
	  <ol>
	    <li>
		<a href='http://misfitgeek.com' target='_blank'>Developer Link 1</a>
		</li>
		<li>
		<a href='http://misfitgeek.com' target='_blank'>Developer Link 2</a>
		</li>
		<li>
		<a href='http://misfitgeek.com' target='_blank'>Developer Link 3</a>
		</li>
      </ol>
    </asp:Panel>
    <br />
    <asp:Panel ID='Panel2' runat='server' ClientIDMode='Static'
         style='background-color:#acc; padding:5px; width: 400px;'
		 class='rounded'>
      <p>&nbsp;Some Developer Links</p>
	  <ol>
	    <li>
		<a href='http://misfitgeek.com' target='_blank'>Developer Link 1</a>
		</li>
		<li>
		<a href='http://misfitgeek.com' target='_blank'>Developer Link 2</a>
		</li>
		<li>
		<a href='http://misfitgeek.com' target='_blank'>Developer Link 3</a>
		</li>
      </ol>
    </asp:Panel>
    <br />
    <asp:Panel ID='Panel3' runat='server' ClientIDMode='Static'
         style='background-color:#acc; padding:5px; width: 400px;'>
      <p>&amp;nbsp;Some Developer Links</p>
	  <ol>
	    <li>
		<a href='http://misfitgeek.com' target='_blank'>Developer Link 1</a>
		</li>
		<li>
		<a href='http://misfitgeek.com' target='_blank'>Developer Link 2</a>
		</li>
		<li>
		<a href='http://misfitgeek.com' target='_blank'>Developer Link 3</a>
		</li>
      </ol>
    </asp:Panel>
    <br />
</asp:Content>

Note the inclusion of the jQuery.dropshadow.js file in line 4.

And then the 2 calls to redrawShadow()


<script src='Scripts/jquery.dropshadow.js' type='text/javascript'>
</script>
<script type='text/javascript'>
		$(document).ready(function () {
			$('.rounded').redrawShadow();
			$('#Panel3').redrawShadow();
		});
</script>

The first call applies a Drop Shadow to any HTML Element who’s class is set to “rounded” and the second applies a Drop Shadow to any element who’s Id is set to “Panel3″.

You can download a working sample HERE.

If you have a specific usage requirement for Drop Shadows, please email me !

Stay tuned.


ASP.NET Rounded Corners with jQuery

Remember the AJAX Control Toolkit ?

I created a LOT of content on how to use it.

While the Ajax Control Toolkit (ACT) is still around, new development on it (by Microsoft) has stopped as we have adopted a more jQuery centric strategy for client UI development.

Not only does this make sense, but I’m compleatly hooked on jQuery so I though I would start demonstrating all the UI things that you could do with the ACT by migrating them to jQuery.

In this video I demonstrated rounding the edges of markup containers in your ASP.NET UI by using the ACT RoundedCorner control extender.

Rounded corners gives our UI a smooth look and there are MANY ways to do this with images, CSS, JavaScript and jQuery.

I’ll use a jQuery plugin to round the corners of an ASP.NET Panel Control.

The final product looks like this.

ASP.NET Rounded Corners with jQuery

I’ve used the jQuery RoundedCorners PlugIn which you can find HERE

It’s TOO simple.

The default ASP.NET WebForms template includes a reference to the jQuery base by default (though you can use jQuery plugins and this code in ANY ASP.NET application.

At the top of my page that will contain rounded corners I add this markup.


    <script src='Scripts/jquery.corners.min.js' type='text/javascript'>
	</script>
    <script type='text/javascript'></script>

When the page is loaded the corners() method is called to apply the rounded corners to all the elements whose class=”rounded”.


    <asp:Panel ID='jQueryBox' runat='server' ClientIDMode='Static'
	     style='background-color:#acc; padding:5px; width: 400px;'
		 class='rounded'>
      <p>Some Developer Links</p>
	  <ol>
	    <li>
		<a href='http://misfitgeek.com' target='_blank'>Developer Link 1</a>
		</li>
		<li>
		<a href='http://misfitgeek.com' target='_blank'>Developer Link 2</a>
		</li>
		<li>
		<a href='http://misfitgeek.com' target='_blank'>Developer Link 3</a>
		</li>
		<li>
		<a href='http://misfitgeek.com' target='_blank'>Developer Link 4</a>
		</li>
		<li>
		<a href='http://misfitgeek.com' target='_blank'>Developer Link 5</a>
		</li>
      </ol>
    </asp:Panel>

I told you it was TOO easy.

I’ll be doing jQuery alternatives for ALL my Microsoft Ajax and Ajax control toolkit videos.

In the mean time – you can download sample code for the above Rounded Corners demo [HERE].


ASP.NET MVC App Building Videos (61)

Building the ASP.NET MVC Music Store


Part 1: Intro, Tools, and Project Structure
Part 2: Controllers
Part 3: Views and ViewModels


ASP.NET MVC 2


Displaying a Table of Database Data
Creating Model Classes with LINQ to SQL
Creating Unit Tests for ASP.NET MVC Applications
Preventing JavaScript Injection Attacks
An Introduction to URL Routing
Understanding Views, View Data, and HTML Helpers
Understanding Controllers, Controller Actions, and Action Results
Understanding Models, Views, and Controllers
Creating a Tasklist Application with ASP.NET MVC
Understanding Models, Views, and Controllers
ASP.NET MVC Controller Overview
Creating a Movie Database Application in 15 minutes with ASP.NET MVC
How Do I: Return JSON Formatted Data for an AJAX Call in an ASP.NET MVC Web Application?
What is ASP.NET MVC? 80 minute technical video for developers, building NerdDinner
Why ASP.NET MVC? 3 minute overview video for decision makers
ASP.NET MVC: How? 10 minute technical video for developers
How Do I: Work with Data in ASP.NET MVC Partial Views?
How Do I: Create a Custom HTML Helper for an MVC Application?
How Do I: Work with Model Binders in an MVC Application?
How Do I: Use HttpVerbs Attributes in an MVC Application?
MVC 2 HTML Encoding
MVC 2 Strongly Typed Helpers
MVC 2 Model Validation
MVC 2 Template Customization
ASP.NET MVC 2 – Areas
ASP.NET MVC 2 – Render Action


ASP.NET MVC Talks


Creating NerdDinner.com
America’s Next Top MVC Framework
Ninja on Fire Black Belt Tips
ASP.NET MVC 2: Ninja Black Belt Tips


ASP.NET MVC For the Rest of Us

(Building a Contact Form App)


#1: ASP.NET MVC For the Rest of Us: Part 1
#2: ASP.NET MVC For the Rest of Us: Part 2
#3: ASP.NET MVC For the Rest of Us: Part 3
#4: ASP.NET MVC For the Rest of Us: Part 4


ASP.NET MVC Storefront Starter Kit


#1: Architectural Discussion and Overview
#2: The Repository Pattern
#3: Pipes and Filters
#4: Linq To Sql Spike
#5: Globalization
#6: Finishing The Repository, and Initial UI Work
#7: Routing and UI Work
#8: Testing Controllers
#9: The Shopping Cart
#10: Shopping Cart Refactor and Authorization
#11: Hooking Up the Shopping Cart & Using Components
#12: Mocking
#13: Dependency Injection
#14: Rich Client Interaction
#15: Public Code review
#16: Membership Redo With OpenID
#17: Checkout With Jeff Atwood
#18: Creating An Experience
#19: Processing Orders With Windows Workflow
#19a: Windows Workflow Followup
#20: Logging
#21: Order Manager and Personalization
#22: Restructuring, Rerouting, and PayPal
#23: Getting Started With Domain-Driven Design
#24: Finis


ASP.NET 4 ClientId – I’ll do it myself thanks !

In the early days of ASP.NET most developers didn’t write client side code. They just used server side UI controls and any programmatic interface state changes were restricted to post-back processing.

Enter Ajax, RIA, Scriptable Services, Scriptaculous, YUI, jQuery, HTML5, etc.

Now ASP.NET developers, no matter what ASP.NET flavor you are using (YES, including WebForms) need to hold some of the party IN the browser.

To manipulate the Document Object Model (DOM) elements we need to know HOW to address them.

WebForms has a built in feature that pertains to the client identity of HTML elements.

ASP.NET used an algorithm to determine the client side naming of a server side control.

When we didn’t ever need to manipulate the DOM from client side code this was a service because it meant that no matter how our server side controls were nested or contained we would never have naming collision in the browser.

One less this to worry about right?

So if we used an ASP.NET server side textbox control in a container on our form (like a panel) here is what the resulting html textbox declaration would look like.


<input id='ctl00_ContentPlaceHolder1_TextBox1'
   name='ctl00$ContentPlaceHolder1$TextBox1'
   type='text' value='Text' />

Beginning with ASP.NET 4 we have the capability to define how we want ASP.NET to handle the relationship between ASP.NET server side controls and the resultant HTML element Ids.

Introducing the ClientId property.

Note that we are talking about the “ID” attribute which we will use to address the element from JavaScript and NOT the “Name” attribute.

“Name” is how the server will see that element when a form is posted to it. “ID” is how the browser sees the HTML element so that is how JavaScript addresses the element.
We now have three ways that we can instruct ASP.NET to handle client ids.

  • Static
  • Legacy
  • Predictable

And we can set this as the default at the Machine, Project, or Page level (and override it wherever we want.)

One might use legacy (the default) if they are not writing client side code. As you would expect, it works the same was it always has (described above.)

Here is how you set the default ClientId mode for the page to “Static”.


<!--Page Language='C#' AutoEventWireup='true'
      CodeFile='Default.aspx.cs' Inherits='_Default'
      ClientIdMode='Static'-->

I nearly always use static. I specify the ID of the HTML element and that is the one ASP.NET uses – period.

Of course, this means that I need to do my own ame management and make sure that the same name is never used for two controls that will appear in the DOM at any one time.

No problem.

There is one time though when “Predictable” mode is a big help.

Suppose you are using a data bound list that contains controls but since it’s data bound you don’t necessarily know how many items that container will ultimately render. “Predictable” IDs means we can “PREDICT” the Ids and therefore we can still program against the individual HTML elements that resides in the container.

So, why am I telling you this now ?

Well, over the past couple of years I have generated TONS of content on doing things with Microsoft Ajax and the Microsoft Ajax Control Toolkit. Since then we have really pitched our support to jQuery.

So, I’m now going to create new content to demonstrate how to do all those Ajax and Client UI techniques using jQuery and modern ASP.NET HTTP services.

Stay tuned and let me know which ones you want me to provide first !


Free ASP.NET MVC Training Online

The MVFConf sessions are now on-line and available for viewing or download !

del.icio.us Tags: ,,,,

ASP.NET MVC Fundamentals Videos & Tutoruals (39)

MVC Step by Step Tutorials


Build your First ASP.NET MVC 3 Application
Build an ASP.NET MVC Music Store


MVC Sample Saamplications

NerdDinner
ASP.NET MVC Music Store
Microsoft TownHall


ASP.NET MVC Overview


ASP.NET MVC Overview
Understanding Models, Views and Controllers
Understanding the ASP.NET MVC Execution Process
Create Movie DB App
ASP.NET MVC 2 Basics
Create a MVC 3 Application with Razor & Unobtrusive JavaScript


ASP.NET MVC Fundamentals Videos


Creating a Movie Database Application
Preventing JavaScript Injection Attacks
Creating Unit Tests
Creating Custom HTML Helpers
Return JSON Formatted Data for an AJAX Call
ASP.NET MVC Controller Overview
Understanding Models, Views, and Controllers
Understanding Views, View Data, & HTML Helpers
An Introduction to URL Routing


ASP.NET MVC For the Rest of Us Videos


ASP.NET MVC For the Rest of Us: Part 1
ASP.NET MVC For the Rest of Us: Part 2
ASP.NET MVC For the Rest of Us: Part 3
ASP.NET MVC For the Rest of Us: Part 4


ASP.NET MVC Routing


ASP.NET Routing Overview
Creating Custom Routes
Creating a Route Constraint
Creating a Custom Route Contstraint


ASP.NET MVC Controlers


ASP.NET MVC Controller Overview
Creating a Controller
Creating an Action


ASP.NET MVC Views


MVC Views Overview
Creating Custom HTML Helpers
Displaying a Table of DB Data
Using the Tagbuilder Class


ASP.NET MVC Testing


Creating Unit Tests


ASP.NET MVC Navigation


Providing Website Navigation with Sitemaps


ASP.NET MVC Performance


Improving Performance with Output Caching
Adding Dynamic Content to a Cached Page


Contoso Karate Feature Demo Available for Download

In recent weeks I’ve been publishing “Chapter Videos” on building Web Sites with Microsoft WebMatrix ( Watch Them HERE )

There will be 21 in total for this introductory series (they are all done and the last of them are in the production pipeline now.)

For those who are following along you can now download the code base I’ve been building in the videos. This is not a “sample application” per se, but rather a collection of feature demos.

A real sample application is in the works.

[ Download the Contoso Karate Feature Demo HERE ]

List of Microsoft Web Development Walkthroughs

I can’t take credit for building these lists, I think JD Meier assembled them before he moved to the Enterprise Strategy group. Since I’m building a list of existing Web Learning Resources I thought I would save them here for my referece and yours.


Introductory


Topic Description
Introduction: Planning an ASP.NET Web Site Provides an overview of the factors that you should consider when you design a Web site. The topic provides links to topics that provide additional information about individual subjects.
Walkthrough: Creating a New ASP.NET Web Site Provides an introduction to the Web development features of Visual Web Developer and guides you through creating a simple ASP.NET page.
Walkthrough: Code Editing in Web Pages in Visual Web Developer Illustrates various features of the code editor. Some of the features of the code editor depend on what language you are coding in. Therefore, in this walkthrough you create two pages, one that uses Visual Basic and another that uses C#.
Walkthrough: Creating a Basic Web Page with Code Separation in Visual Web Developer Provides an introduction to creating Web pages in Visual Web Developer. It guides you through creating a simple page, illustrating the basic techniques of creating a new page, adding controls, and writing code.
Walkthrough: Creating and Modifying a CSS File Introduces the features of Visual Web Developer for working with cascading style sheets (CSS). It guides you through creating a three-column page layout, illustrating the basic techniques of creating a new Web page and a new style sheet.
Walkthrough: Validating User Input in a Web Forms Page Illustrates how to use ASP.NET validation controls to check user input in a Web page.
Walkthrough: Basic Data Access in Web Pages Shows you how to create a simple data-bound page by using controls that are designed specifically for data access.
Walkthrough: Displaying, Paging, and Sorting Data Using the ListView Web Server Control Illustrates how to work with the ListView control, which enables you to display data in a format that you define by using templates. By working with templates, you can have complete control over the layout and appearance of the data in the control.
Walkthrough: Creating Master/Detail Web Pages in Visual Studio Shows you various ways to work with data in multiple controls and from multiple tables, which includes those that have a master/detail relationship.
Walkthrough: Retrieving, Updating, Inserting, and Deleting Data with the LinqDataSource and DetailsView Controls Shows you how to create a simple database table and a Web page that uses the LinqDataSource control. The Web page enables users to retrieve, update, insert, and delete data from the database table.
Walkthrough: Adding Site Navigation to a Web Site Illustrates how to create site navigation by using various navigation controls, such as the Menu control, the TreeView control, and the SiteMapPath control, which adds a navigation path to Web pages.
Walkthrough: Displaying a Menu on Web Pages Shows you how to add a menu control to a page and use it as a navigation tool.
Walkthrough: Creating a Web Site with Membership and User Login Shows you how to use ASP.NET controls and ASP.NET membership services to create pages that let users log in and work with member-only pages.
Walkthrough: Creating an AJAX-enabled Web Site Shows you how to create a basic ASP.NET Web site that has a Web page that illustrates ASP.NET AJAX features.
Walkthrough: Creating and Using ASP.NET Master Pages in Visual Web Developer Illustrates how to create a master page and several content pages. Master pages let you to create a page layout (a template page). You can then create separate pages that contain content that is merged with the master page at run time.
Walkthrough: Customizing a Web Site Using Themes in Visual Studio Shows how to use themes to apply a consistent look to pages and controls in a Web site.
Walkthrough: Debugging Web Pages in Visual Web Developer Shows you how to use the debugger. You create a Web page that contains a simple calculator that includes a deliberate error, and then use the debugger to examine the page as it is running.
Walkthrough: Copying a Web Site Using the Copy Web Site Tool Shows you how to use the Copy Web Site tool to copy files between your current Web site and another Web site.
Walkthrough: Publishing a Web Site Shows you how to use the Publish Web Site utility to compile a Web site, and then copy the output to an active Web site.

The Publish Web Site utility is not available in Visual Web Developer 2008 Express Edition.

Advanced


Walkthrough Description
Walkthrough: Modifying Data Using the ListView Web Server Control Shows you how to display and update data in the ListView control. This walkthrough uses a SqlDataSource control to retrieve results from the data source and to manage updates. The SqlDataSource control acts as the data source for the ListView control.
Walkthrough: Displaying a Drop-Down List While Editing in the GridView Web Server Control Shows you how to use the ASP.NET GridView control&#39;s advanced functionality to add a drop-down list to the editing display.
Walkthrough: Creating User-Selectable Themes Illustrates how to create an ASP.NET page that lets users select a theme for the page. Although this example uses a single control skin and a basic cascading style sheet (CSS) file, the principles shown apply to more complex themes that include graphics, different layout schemes in the CSS file, and more complex server control skins.
Walkthrough: Creating the Data Access and Business Logic Layers in ASP.NET Shows a simple example of best practices for creating a Web site that accesses a database by isolating the data-access and business-logic layers.
Walkthrough: Creating and Using an ASP.NET Web Service in Visual Web Developer Illustrates how to create and use a Web service.
Walkthrough: Creating an AJAX-Enabled Data Application Illustrates how to create a database application that includes AJAX features to refresh data on the page by using an asynchronous postback.
Walkthrough: Using Nested Master Pages in ASP.NET Shows you how to nest master pages so that the parent master page can provide a consistent layout throughout a Web site, and the child master page can be used as a template for consistent layout within the parent master page.
Walkthrough: Maintaining Web Site User Information with Profile Properties Shows you how to add profile properties to your application and how to use the profile properties to create a personalized experience for visitors to the Web site.
Walkthrough: Using ASP.NET Application Services Shows you how to assign users to roles and how to create rules (permissions) that selectively grant or deny access to pages for different roles. It also shows how to programmatically determine whether a user is in a particular role and which roles the current user is in.
Walkthrough: Managing Web Site Users with Roles Illustrates how to configure an ASP.NET Web site to expose application services for authentication, roles, and profile properties.
Walkthrough: Creating Reusable Elements with ASP.NET User Controls Shows you how to create an ASP.NET user control that acts as a picker control. The picker control has two lists, with a set of choices in one list (the source). Users can select items in the source list and add the items to the target list.
Walkthrough: Using Shared Code in Web Sites in Visual Web Developer Shows you how to create a simple class and then use it in an ASP.NET Web page where Visual Web Developer references the component automatically.
Walkthrough: Using Resources for Localization with ASP.NET Shows you how to create localization resource files and reference them in Web pages by using declarative expressions.
Walkthrough: Using Output Caching to Enhance Web Site Performance Shows you how to use output caching, which uses a pre-processed copy of a page instead of processing the page again for each request.
Walkthrough: Creating an Accessible Web Application Illustrates how to create accessible Web pages that enable you to reach as many customers as possible, such as people with disabilities and users who have slow connections or text-only browsers.
Walkthrough: Creating a Synchronous HTTP Handler Illustrates how to create an HTTP handler, which lets you create custom dynamic output other than Web pages, such as RSS feeds.
Walkthrough: Creating and Registering a Custom HTTP Module Illustrates the basic functionality of a custom HTTP module. An HTTP module is called on every request, and lets you customize how the request or response is processed.
Walkthrough: Developing and Using a Custom Server Control Shows you how to create and compile a custom ASP.NET server control and use it in a page.

Location of the machine.config file

I get this email a lot from beginners……..

Where is the machine.config file ?

As we’ve simplified the we.config file some configuration elements have been moved lower in the chain to the machine.config file.

The machine.config file is located in

[Your System Drive]:\<windows>\Microsoft.NET\Framework\<version>\config\machine.config

On my laptop the real path is :

C:\Windows\Microsoft.NET\Framework\v4.0.30319\Config\machine.config

For more information on the ASP.NET configuration hierarchy [ read HERE ]

Microsoft WebMatrix is NOW LIVE !

I’m super excited that Microsoft WebMatrix is now RTW !

Check out Microsoft WebMatrix [ HERE ]

Read “Web Development 101 With WebMatrix

Stay tuned as I’m working on a collection of videos and tutorials !!!

Orchard 1.0 – We’re ready for production !

OrchardLogoCodeplex

If you’re like me you’ve been waiting with anticipation for this Orchard 1.0  !

Well, we’re LIVE.

The primary differences between 0.8 and 1.0 is bug fixes but the milestone is that we’re production ready so we can starting building sites, modules, and themes with confidence.

Get the RTW version [ HERE ]

… and if you build a Module of Theme, make sure you let me know so I can blog about it !!

Feature Sample for Microsoft WebMatrix with Razor – Beta 3

WeMatrixSampleSS

Last fall I started giving resentations on Microsoft’s cool new Web Development Stack – WebMatrix.

I put together a collection of samples to demonstrate features and common tasks. It’s not really a sample application, per se, but really just a bunch of code/features examples in a single bundle.

I’ve just updated then to work with the latest Beta 3 with is VERY close to RTM.

I hope you will download WebMatrix and the Samples a check them out !

[ Get Microsoft WebMatrix HERE ]

[ Get the code for the samples HERE ]

Podcast #3 – ASP.NET Scott Hunter

In this episode,Joe catches up with the Scott Hunter, Sr. PM Lead of the ASP.NET Team. Listen and hear about what the team is working on, how they plan and decide on new products and features, and more.

RESOURCES  

 Subscribe


   MP3

   WMA

   M4A

   Zune

   iPod

 Download


   MP3

   WMA

   M4A

   Zune

   iPod

Dynamic Page Menus in WebMatrix Templates with CSS and jQuery.

A basic practice in software development of all types is to use mechanisms that allow us to write and maintain code in a single place no matter how many difference places that code is used throughout our entire application.

When we’re building web sites, and more specifically web pages, the reuse of UI code can be especially challenging as the nature of web applications are stateless and in most models there is a 1-to-1 relationship between endpoints and “files”.

In ASP.NET WebForms we have master pages.

In Microsoft WebMatrix we have Layout Templates.

One of the advantages of the general move towards “standards based” web development is that HTML, CSS, and JavaScript can generally be used across different web development platforms and the technique described below can be used no matter which ASP.NET Development model you choose. (WebForms, ASP.NET MVC, WebMatrix)

I’ll use WebMatrix for the example.

Given a WebMatrix site created using the default “Starter” template the following Home Page and About Page can be displayed when the project is run.

Note that only the text inside the white area of the pages is different in the Default.cshtml and About.cshtml pages.

Read the rest of this entry »

Building a Sample WebMatrix Application

Microsoft-WebMatrix-1278498927

Last year I built a sample WebForms application modeled after the original iBuySpy ecommerce application called TailSpin Spyworks.

I thought it would be interesting to build something “real” using Microsoft WebMatrix.

The web site I’ve settled on is a Kids Sports Team Portal. Here are some of the features I’m planning on.

  • Season Game Schedule with front page reminder.
  • Game Results archive with front page “most recent” game results.
  • Practice Schedule.
  • Push updates to parents email list.
  • Parent’s notification (option to advice coaches that a child will be absent.)
  • Restricted access photo gallery with parent’s contributions.
  • Restricted access video gallery with parent’s contribution.
  • Some social networking integration.

I’ll be starting with an open source template.

As I’m starting to plan and build, WHAT FEATURES WOULD YOU RECOMMEND !

Technorati Tags: ,WebMatrics,

Tailspin Spyworks Ecommerce Application and Tutorial Updated on CodePlex !

Just a note to let folks know that I’ve updated both the code and the tutorial for the tailspin Spyworks sample app at http://tailspinspyworks.codeplex.com/.

It includes bug fixes, additional step details in the tutorial as well as complete database schema information.

Enjoy and feel free to send comments and suggestions.

35 Developer Learning Pain Points

A few weeks ago I asked developers to tell me what heir top “learning pain points” were.

I got GREAT input that I intend to use to drive much of the guidance that I will build in 2011.

Below is a list of the top results.

Please feel free to add or comment.

————————————————————

1.) Choosing between Web Forms, MVC, WebMatrix or something else entirely.

2.) Choose Windows Forms, WPF, Silverlight or something else for desktop development. 

3.) Choosing a data access method (ADO.NET, LINQ to Objects, LINQ to SQL, Entity Framework, NHibernate, embedded SQL) and how to use that choice in application architecture. What are the good practices, should I use binding? Etc.?

4.) Choosing between ASMX or WCF (When SHOULD I use WCF)

5.) Determining the right practices and patterns for asp.net development.

6.) Finding examples of non-trivial applications with great documentation and tutorials.

7.) How to build, consume, and manage Reusable Code (Libraries, Frameworks, Controls).

8.) Microsoft guidance focuses on HOW, but not when and why. Proved “Best Practices”.

9.) Moving from WebForms Controls to JavaScript (jQuery) (How, Why, and When to choose which.)

10.) Show me how to do Grids and all other WeForms control functions in jQuery.

11.) Should I choose jQuery or ASP.NET AJAX (and how do I use jQuery to do all the things that I used to do in ASP.NET AJAX and the Ajax Control Toolkit.

12.) Deciding whether to use Silverlight in an ASP.Net app.

13.) Complete guidance on REST with samples of working will all major REST APIs (Twitter, Facebook, etc.)

14.) How to do OO Design & Coding with .NET (I never really had to learn)

15.) Changing our development practices to follow more of a TDD model.

16.) Source code management tool options. VSTS and cheaper solutions (CVN)

17.) How do implement a true and Abstract DAL 

18.) How to build a good BLL with validation (required fields, etc…) in front of an Entity Framework DAL.

19.) I need a complete strategy for SEO. Microsoft has some tools, but no complete story!

20.) How do I design and build for high performance and how to I troubleshoot performance problems.

21.) Understanding stateless application development. WebForms handled “state” for me. MVC and WebMatrix don’t.

22.) Building a business case for management to migrate a Classic ASP (VBScript) (90% of app) to ASP.Net MVC instead of ASP.Net WebForms (10% of app).

23.) Building a business case for migrating Classic ASP to ASP.Net (Choosing MVC or WebForms)

24.) How to understand and get started with ASP.NET MVC. (I’ve been an ASP.NET developer for years and have looked at the MVC samples but it’s too complex and requires advanced OO skills.)

25.) Application deployment is a mess. Which versions of .NET, IIS, SQL ? How to automate deployment? What works side-by-side? How to manage SQL schema updates.

26.) Should I use Stored Procedures or not now that we have LINQ and EF? How do I manage versioning of Stored Procs if I use them.

27.) I need to understand and use the ASP.Net security model, providers, etc.

28.) I need to understand How the .net framework versions work (and don’t work) together.

29.) I need detailed guidance about how to make my (web) application multi lingual. Should I use resource files, a SQL Database?

30.) ASP.NET Membership and Profile management is far too weak. Show my how to take both to the next level and highly customize them.

31.) My team has major confusion over dataset binding in controls versus lists / listview, use of business objects and all the choices. Which controls are best to use for what user interface types and what is the best way to use data with those controls.

32.) Help me learn how to deal with service binding and endpoint configuration headaches in my ASP.NET application; especially when developing on localhost (http) and deploying to a secure environment (https)… resulting in "works on my machine" syndrome.

33.) I need to understand the UpdatePanel (AJAX) and how it affects the page life cycle, security, and interaction between multiple UpdatePanels on same Page. Should I even be using the UpdatePanel? Is it going away? What is Microsoft’s plan for their AJAX stuff which seems to be going away and being replaced by jQuery.

34.) Now that we’re doing more client side coding I need to really understand ViewState. It seems like a black box.

35.) How should I keeping up with new releases? How do I decide when to move to new versions.

 

Technorati Tags: ,,Learvning

ASP.NET & ADO.NET Code Samples Collections

J.D. Meier (my team mate here in Developer Guidance) recently put together these lists of samples.

I’m sharing them here so I can easily refer to them. While your looking, go over and subscribe to J.D.’s blog (where he also published these). He does awesome stuff.

 

ASP.NET Code Samples Collection

Category Items
Sample Applications

ASP.NET MVC

AJAX / jQuery All-in-One Code Framework

Code Gallery

Microsoft Support

Authentication Code Gallery

Customer Support

Authorization Code Gallery

CSS 2
Data Access All-in-One Code Framework

Code Gallery

Exception Management Code Gallery

Microsoft Support

JavaScript / JSON Code Gallery

Logging and Instrumentation patterns & practices

MVC Code Gallery

Navigation Codeplex

Request Processing ASP.NET Developer Center (www.ASP.NET)

State / Session Management Code Gallery

Validation Code Gallery

Visual Studio and ASP.NET Development Code Gallery

Microsoft Support


Category Items
Data Binding MSDN Library

Data Models Code Gallery

Microsoft Support

DataReader MSDN Library

DataSet MSDN Library

DataTable MSDN Library

Entity Framework All-in-One Code Framework

Code Gallery

General All-in-One Code Framework

MSDN Library

LINQ to DataSet MSDN Library

LINQ to Entities MSDN Library

LINQ to Objects All-in-One Code Framework

LINQ to SQL All-in-One Code Framework

Code Gallery

Code Gallery

N-Tier Code Gallery

O/RM Mapping Code Gallery

OData Code Gallery

POCO
Silverlight Code Gallery

SQL Server MSDN Library

Streaming Code Gallery

WCF Data Services All-in-One Code Framework

Code Gallery

A List of Resources to help jumpstart your ASP.NET WebMatrix Development.

WebMatrix Stack

Building ASP.NET Web Pages using the Razor Syntax (PDF Book) :

ASP.NET Web Pages With Razor Syntax – Book -  Beta 2 – PDF

Microsoft on line resources :

WebMatrix on the ASP.NET Community Site

WebMatrix on the IIS.NET Community Site

Full project downloads on the Microsoft Download Center

Using WebMatrix Beta 2

Create an ASP.NET Website from Scratch

How to Choose a Template and Create a New Website Using WebMatrix Beta

Add and Edit ASP.NET Web Pages

Download and Install an ASP.NET Application

Analyze Requests to your Website

Make your Website SEO friendly

Publish a Website

Migrate a Database to SQL Server

Download and Install a PHP Application

Create a Website from a Gallery Application (WordPress)

WebMatrix Beta 2 Release Readme

ASP.NET Web Pages with Razor Syntax Beta 2 (individual tutorials from the book above).

Get the Code Samples Download!

Get the eBook Download!

Getting Started with WebMatrix Beta and ASP.NET Web Pages

Introduction to ASP.NET Web Programming Using the Razor Syntax

Creating a Consistent Look

Working with Forms

Working with Data

Displaying Data in a Grid

Displaying Data in a Chart

Working with Files

Working with Images

Working with Video

Adding Email to Your Web Site

Adding Search to Your Web Site

Adding Social Networking to Your Web Site

Analyzing Traffic

Caching to Improve the Performance of Your Website

Adding Security and Membership

Introduction to Debugging

Customizing Site-Wide Behavior

ASP.NET API Quick Reference

ASP.NET Web Pages Visual Basic

Using IIS Developer Express

IIS Developer Express Overview

Use the Windows System Tray to Manage Websites and Applications

Use the Command Line to Run a WebMatrix Site or Application

Thanks to Wade Pickett for compiling this list !

Taxonomy_v1

In order to map Developer Guidance offerings across the entire breadth of Microsoft’s web development technologies I’m starting to document a broad taxonomy.

I put together this collection of HIGH LEVEL “buckets”.

[ You can see the diagram full size by clicking HERE ]

So friends, two questions.

1.) Did I miss any HIGH level bucket ?

2.) If you’re interested, take one of these buckets enumerate the next nesting level for that topic.

This is a work in process, I’ll update http://misfitgeek.com/taxonomy/ as I expand the taxonomy.

THANKS !

Choosing between ASP.NET–WebForms, MVC, WebMatrix – Choice is a GOOD thing.

Yesterday Microsoft announced new (beta) releases of  a number of forthcoming web development technologies. [ Read HERE ]

A member of one of the mailing lists I’m on was very upset! He complained that TWO choices were two many (WebForms and MVC) and adding a THIRD (WebMatrix) was simply ridiculous.  I know he was serious because he said “seriously” many times.

ScottGu posted an interesting opinion [ About Technical Debates (and ASP.NET Web Forms and ASP.NET MVC debates in particular)  ] on his blog some time ago.

Now that I’m MSJoe and not the MisfitGeek, I’m trying to be more political correct (as demanded by management : ) ), and I don’t mean to call out that specific individual, but the email thread got me to thinking.

If you read the developer blogosphere, there are many thousands of developers out there that are sure they could do a better job guiding Microsoft Developer Platform Strategy than our current leadership, they just choose not to come be part of the solution, but in this instance someone was saying that “choice options” are a bad thing.

Now, no one was saying that THE choice (WebMatrix) was bad, only that having three different options to choose from was bad.

I think people complain about having choices comes from one of three things.

1.) I don’t want to have to MAKE choices, either because I don’t want to (or have the time) to learn about the choices so that I can make the right choice for my needs.

2.) Confidence issues. I don’t want to have to make a choice because I might not make the right one (or be able to defend it.)  If there is only ONE choice then I can’t get blamed for it

3.) I already MADE my choice so no other choices should be needed by anyone, any where ever !

BAD choices can be bad, but have several good choices is just…. well, good.

So, I’ll talk about the three choices (and really there are more than three.)

1.)  ASP.NET WebForms

It’s become fashionable in some circles to say “WebForms sucks”.

Look back a decade to when ASP.NET WebForms first hit the street and reflect on how WebForms was pure genius back then.

People were building “Client / Server” applications with Visual Basic, Borland Delphi, PowerBuilder, etc. and suddenly everyone needed to move business applications to the World Wide Web. ASP.NET WebForms gave developers a way to do that using the exact development paradigm that they had already been using for years in the Client Server world without having to learn much f anything about how the Internet or the World Wide Web actually worked.

It was a brilliant solution to the problem of the day – get developers productively building applications for the web with as little time lag and learning curve as possible !

ASP.NWET WebForms FTW !!!!

Only many years later has the technical abstraction provided by ASP.NET WebForms become a hindrance. (And really, only a hindrance to some developers.)

So if you are a web developer building applications with ASP.NET WebForms should you move to something else ?

Not necessarily.

There are LOTS of GREAT web applications built with ASP.NET WebForms. If it works for you – keep doing it.

Also, there are many different STYLES of development possible with ASP.NET WebForms.

If certain parts of the WebForms layer get in the way, you can probably turn it off, or not use it.

Don’t like ViewState, turn it off (at whatever level of granularity you like).

Don’t like the WebForms Controls, don’t use them (replace them with jQuery UI ! )

1950-PanHead

This 1950 Harley Davidson Pan Head has modern paint and an after market seat but is still an awesome choice !

I still write new applications in ASP.NET WebForms.

2.) ASP.NET MVC

Proponents say MVC is the “Modern” way.

MVC is a “Pattern” that has been in use for more than THIRTY years. ASP.NET MVC is an implementation of that pattern for building .NET Web Applications.

There are good reasons to choose ASP.NET MVC for your new Web Application Development.

  1. Pattern supported separation of concerns. (Though undesirable development practices can break this model.)
  2. Embrace (rather than abstract) the underlying nature of the World Wide Web.
  3. Strong facilities for Unit Testing.
  4. Well suited to “Agile” development practices.

Certainly one can do all those things with ASP.NET WebForms, but ASP.NET MVC was designed and built with these things in mind.

There is a rather steep learning curve to start working with ASP.NET MVC. The implementation relies heavily on development by “convention” which means you need to spend time figuring out where certain things HAVE TO go or what the names of CERTAIN things MUST be.

And, there are choices to be made such as with View Engine to use (Forms, Razor, etc.)

When it comes to UI you’re sort of on your own (which some of us really like) though there is tooling support built in for jQuery coding.

The most important reason for one to choose ASP.NET MVC is simple.

Because it most facilitates they way you WANT to build web software !

If I were building a new application that was going to be built and maintained by a single company I would probably  choose ASP.NET MVC.

3.) ASP.NET WebMatrix

Ahhh, now for the “New Kid on the Block”. 

This is the one the uber-geeks say we don’t need.

I say they’re WRONG.

ASP.NET WebMatrix is not an APPLICATION Centric development methodology (like ASP.NET MVC), it is a PAGE CENTRIC development model.

The first important thing to note in this regard is that MANY Web Developers simply PREFER this model for developing Web Applications.

MANY web applications are built this way without the mandatory implication of a specific pattern, without Unit Testing, without Agile methodologies, etc.

In fact, most of the MOST popular web applications have been built this way.

Classic ASP developers work this way. So do PHP developers.

WebMatrix is perfect for Web SITES – and much of what we use on the web are more “sites” than applications”.

The web “page” model also has a special place in community driven Open Source development.

Projects like WordPress have grown HUGELY successful due to wide spread community involvement. The page centric development model really resonates well because the learning curve for contribution is low enough to offer rapid satisfaction. One doesn’t need to “get” the architecture, etc to start building and sharing things of interest to them.

And, like all the technologies I’ve been talking about here you are free to use the JavaScript strategy of your choice, AJAX, Silverlight, Flash, etc. – whatever you desire. 

So, which to choose ?

Yea, I know we tend to like it when there is a clear winner, or at least when someone declares a clear winner, even if you disagree.

The problem is that there are “hard” criteria but in the end, preference wins.

Some people drive a sports car, others drive trucks. (I bought an SUV with a big v8 engine so I get utility and whiplash whan I stomp on the pedal.)

I can’t TELL YOU when YOU should choose, but I can tell you how I choose.

 

I choose WebForms When ……

I don’t have the issues with WebForms that some folks seem to have developed. I don’t find it that difficult to get under the covers and I don’t mind writing custom controls if I need to. Still, more and more I find that WebForms makes sense to me when I’m building “behind the firewall” applications.

  • An app who’s UI can mostly be limited to the ASP.NET WebForms controls.
  • An application that will be GRID Centric.
  • An app that is mostly Data and the Screens that show / edit them. (Little “business logic” need be added.
  • Rapid Prototypes or Use & retire applications.

 

I choose ASP.NET MVC When …..

  • The app wants to be a “Web 2.0” type thing.
  • The UI will need to be complex and or very interactive.
  • The application will have a great deal of business logic and / or is mission critical.
  • The app needs to have an extended functional lifespan and will experience evolutionary iterations.

I choose WebMatrix when …..

  • The “app” is “Site Centric”.
  • UI is king but data and business logic are minimal.
  • I want the application to be Open Source AND I want it to take on a life of its own.

Still, I continue to work with all three.

ASP.NET Developers–What are your FIVE biggest learning pain points ?

Ok ASP.NET Dudes and Dudettes…..

From a learning perspective, can you share with me your 5 current “Learning Pain Points” ?

Example:

1.) Choosing between ASP.NET MVC, Web Forms, and WebMatrix

2.) Integrating jQuery into my ASP.NET Application ?

3.) Building REUSABLE code libraries ?

4.) Learning how to implement REST based Features in ASP.NET

5.) Deciding whether to use Silverlight in my ASP.NET Application.

I just made those up but you get the idea.

You can post YOUR 5 here or send them to my at this link – http://misfitgeek.com/blog/contact/

THANKS for your input !

HELP WANTED–A few reviewers needed for Tailspin Spyworks Tutorial Update.

I’ve been working on an update to the Tailspin Spyworks Tutorial (http://www.asp.net/web-forms/samples/tailspin-spyworks)

If you have time and interest to load and run the code in Visual Studio and / or walk through the tutorial and build the application and provideo me with feedback about what is wrong or missing….

PLEASE contact me and let me know !!!  I’ll send you the updates !

THANKS

2 New How-Do-I Videos Published

These 2 videos are now live:

· Simple Web Service Authentication

· Creating Inactive Users

Tailspin Spyworks videos 13 and 14 are now live

Tailspin Spyworks – Creating and Using the Popular Products Control

Tailspin Spyworks – Implementing and Using the Also Purchased Control

Exposing Java Implemented Logic – JSP or ASP.NET ?

A developer emailed me this weekend because he had just taken a position in a large software development organization and his first task was to present a discussion top management as to the relative strengths and weakness of developing new web based functionality in ASP.NET versus JSP.

During the .COM boom I did a lot of Java development. While I liked the language very much, there was much I disliked about the experience (at least as it compared with my expectations).

The middleware back in that day was cumbersome and the write once / run anywhere mantra (which I don’t think was ever entirely true) was really exacerbated by the middleware implementations. (Though JBoss happened later and I think JBoss is a super implementation.)

I never grew to like JSP. Working with JSP had little in common with the experience of working with Servlets or EJBs – where I spent my time.

The evolutionary pace of JSP seems to have really slowed and now that Sun has been acquired by Oracle who knows what will happen to Sun’s development technology. (The futures disclaimers that appear across the Sun/Java sites might indicate a cause for concern.)

ASP.NET, PHP, Python, and Ruby / RoR are all modern, evolving web development technologies.

So WHY would a company choose to do new development in JSP?

In a word – immutable Servlets.

If I had a great deal on intellectual property in Java Servlets (more than I could reasonably port out of Java in my required time frame) and I COULD NOT modify the Servlets – then I’d probably choose JSP. JSP is hard wired to talk to Java Servlets.

Of course, if I COULD modify the Servlets, my first architectural preference would be to expose the Servlet functionality through XML Web-Services, or if performance issues demanded it, via Sockets directly.

Java, .NET and PHP all have Sockets APIs.

One advantage that .NET has over PHP for this purpose is that .NET supports a binary component model so one could start building Web based UI to expose the Servlet logic and as new development progressed the Servlet architecture could be slowly migrated to .NET objects.

All in all, the question got me wondering how many folks are dealing with updating and extending existing Java infrastructure.

How are you doing it? What technologies are you choosing ?

Buttons with Mouse-Over Behaviors – Redux

I recently posted some CSS and HTML snippets for a buttons collection I was using for a Menu style UI Scott Koon from www.LazyCoder.com posted a comment with a better way (thanks Scott). This way I don’t have to set the CSS Class for each button. Just contain them in a div. Here is the CSS

CSS
  1. div input:hover
  2. {
  3. background-color: #BFCBD6;
  4. }
  5.  
  6. div input
  7. {
  8. vertical-align: middle;
  9. text-align:center;
  10. width: 150px;
  11. height: 40px;
  12. border: 1;
  13. border-color: Silver;
  14. background-color: #465C71;
  15. color: White;
  16. }

And here is the markup.

ASP.NET Markup
  1. <%@ Page Title="Home Page" Language="C#"
  2. MasterPageFile="~/Site.master"
  3. AutoEventWireup="true"
  4. CodeBehind="Default.aspx.cs"
  5. Inherits="Button_CSSSelector._Default" %>
  6. <asp:Content ID="HeaderContent" runat="server"
  7. ContentPlaceHolderID="HeadContent">
  8. </asp:Content>
  9. <asp:Content ID="BodyContent" runat="server"
  10. ContentPlaceHolderID="MainContent">
  11. <div style="text-align: center;">
  12. <h2>Administration</h2>
  13. </div>
  14. <hr /><br />
  15. <div style="text-align: center;">
  16. <asp:Button ID="btnAdminUsers" runat="server"
  17. Text="List Users"
  18. PostBackUrl="" />
  19. &nbsp;&nbsp;
  20. <asp:Button ID="btnAdminActivate" runat="server"
  21. Text="Inactive Users"
  22. PostBackUrl="" />
  23. &nbsp;&nbsp;
  24. <asp:Button ID="btnAdminEvents" runat="server"
  25. Text="Locked Out Users"
  26. PostBackUrl="" />
  27. &nbsp;&nbsp;
  28. <br /><br />
  29. <asp:Button ID="btnAdminRoles" runat="server"
  30. Text="Roles"
  31. PostBackUrl="" />
  32. &nbsp;&nbsp;
  33. <asp:Button ID="btnAdminAccess" runat="server"
  34. Text="Access Security"
  35. PostBackUrl="" />
  36. &nbsp;&nbsp;
  37. <asp:Button ID="btnAdminSettings" runat="server"
  38. Text="Application Settings"
  39. PostBackUrl="" />
  40. &nbsp;&nbsp;
  41. <asp:Button ID="btnAdminReporting" runat="server"
  42. Text="Reporting"
  43. PostBackUrl="" />
  44. &nbsp;&nbsp;
  45. <asp:Button ID="btnAdminMisc" runat="server"
  46. Text="Misc"
  47. PostBackUrl="" />
  48. &nbsp;&nbsp;
  49. </div>
  50. </asp:Content>

ASP.NET Membership Training – 3 new Videos

Hi folks. Here are three more videos in my collection on Security concepts and working with ASP.NET Membership

· Adding Users to Your Membership System

· Logging Users Into Your Membership System

· Implement the Registration Verification Pattern

You can find them all at the Web Forms Security page: http://www.asp.net/web-forms/security

image

Have you checked out the Tailspin Spyworks sample application ?

[ Start HERE ]

New Video Series – Learning Microsoft WebMatrix.

Have you heard about ASP.NET WebMatrix ?

There is a new dev tool and installer, a new syntax for developing ASP.NET Web Pages, IIS, SQL Compact.

Here are links to the first two videos in a new series for learning WebMatrix Development.

  1. Getting Started with WebMatrix Beta and ASP.NET Web Pages
  2. Introduction to ASP.NET Web Programming Using the Razor Syntax

 

wm-image_0b134c68-94f5-4abd-89f7-702e3fc0b64c

These videos will linked to a multi-chapter written tutorial series you can find at the link below.

[ Written tutorial series. ]

More coming son !

New Videos and Tutorials for this Week.

I have this GREAT Site Manager that manages the release mechanics of my content on the ASP.NET web site (THNAKS TERRI !)

Here is a list of content that went live this week:

Videos

· ASP.NET MVC For the Rest of Us: Part 4 (Monday, July 19)

· Tailspin Spyworks – Adding User Product Reviews (Wednesday, July 21)

· Tailspin Spyworks – Displaying User Reviews (Wednesday, July 21)

Tutorials (Tailspin Spyworks) – Wednesday, July 21

· Part 1: File-> New Project

· Part 2: Data Access Layer

· Part 3: Layout and Category Menu

· Part 4: Listing Products

· Part 5: Business Logic

· Part 6: ASP.NET Membership

· Part 7: Adding Features

· Part 8: Final Pages, Exception Handling, and Conclusion

There is also a shiny new landing page for Tailspin Spyworks: http://www.asp.net/web-forms/samples/tailspin-spyworks

And, there is a videos RSS feed: http://www.asp.net/rss/videos, and a tutorials RSS feed: http://www.asp.net/rss/tutorials

Have fun !

Technorati Tags: ,WebForms,,,,,

I’m building a drop-in page library for administering ASP.NET Application Services (Membership, Roles, etc) on a public web site.

On the default.aspx page in my Admin folder I wanted a

I didn’t want a top menu, a fancy tree view, etc. using ASP.NET buttons. I’m using buttons because the click event can either be a navigation or an event handler in code behind.

Here is the look

image

In my /Admin folder I “cloned” the default Master.page (now /Admin/Admin.Master).

Next – I created an Admin.css file in the/Admin directory.

Code Snippet
  1. .adminButton
  2. {
  3.     vertical-align: middle;
  4.     text-align:center;
  5.     width: 150px;
  6.     height: 40px;
  7.     border: 1;
  8.     border-color: Silver;
  9.     background-color: #465C71;
  10.     color: White;
  11. }
  12.  
  13. .adminButton:hover
  14. {
  15.     background-color: #BFCBD6;
  16. }

 

In the Admin.Master page I added the Admin.css reference to the <head> element.

Code Snippet
  1. <head id=”Head1″ runat=”server”>
  2.     <title></title>
  3.     <link href=”~/Styles/Site.css” rel=”stylesheet” type=”text/css” />
  4.     <link href=”Admin.css” rel=”stylesheet” type=”text/css” />
  5.     <asp:ContentPlaceHolder ID=”HeadContent” runat=”server”>
  6.     </asp:ContentPlaceHolder>
  7. </head>

Then I put the ASP.NET Buttons on my default page like this.

Code Snippet
  1. <asp:Content ID=”Content2″ ContentPlaceHolderID=”MainContent” runat=”server”>
  2.     <div style=”text-align: center;”><h2>Administration</h2></div><hr /><br />
  3.     <div style=”text-align: center;”>  
  4.         &nbsp;&nbsp;  
  5.         <asp:Button ID=”btnAdminUsers” runat=”server” Text=”List Users” PostBackUrl=”" CssClass=”adminButton” />&nbsp;&nbsp;  
  6.         <asp:Button ID=”btnAdminActivate” runat=”server” Text=”Inactive Users” PostBackUrl=”" CssClass=”adminButton” />&nbsp;&nbsp;
  7.         <asp:Button ID=”btnAdminEvents” runat=”server” Text=”Locked Out Users” PostBackUrl=”" CssClass=”adminButton” />&nbsp;&nbsp;                      
  8.         <br /><br />
  9.         &nbsp;&nbsp;   
  10.         <asp:Button ID=”btnAdminRoles” runat=”server” Text=”Roles” PostBackUrl=”" CssClass=”adminButton” />&nbsp;&nbsp;
  11.         <asp:Button ID=”btnAdminAccess” runat=”server” Text=”Access Security” PostBackUrl=”" CssClass=”adminButton” />&nbsp;&nbsp;
  12.         <asp:Button ID=”btnAdminSettings” runat=”server” Text=”Application Settings” PostBackUrl=”" CssClass=”adminButton” />&nbsp;&nbsp;
  13.         <asp:Button ID=”btnAdminReporting” runat=”server” Text=”Reporting” PostBackUrl=”" CssClass=”adminButton” />&nbsp;&nbsp;
  14.         <asp:Button ID=”btnAdminMisc” runat=”server” Text=”Misc” PostBackUrl=”" CssClass=”adminButton” />&nbsp;&nbsp;
  15.     </div>
  16. </asp:Content>

Simple !

Hopefully it will save someone some time.

Technorati Tags: ,,

Taking JetBrains Resharper 5 for a spin.

image

I’ve always found Visual Studio to provide me with all that I need for ASP.NET development, so I’ve never really integrated a significant Add-In to my personal software development process.

But, I keep downloading source code projects that contain ReSharper project files, so I thought I’d give it a try and find out why ReSharper is so popular.

The guys at JetBains hooked me up with the latest version and I was up and running in a few minutes.

In a single statement – ReSharper helps you write better code.

I have to confess, it freaked me out a bit when I first installed it and opened a large existing project.

I got lots of code suggestions like this one.

SNAGHTML5089cd5

I worried that ReSharper would only be good if I were starting from scratch.

I quickly discovered that while I’m learning ReSharper, if it gets in the way at all I can just turn it off while I’m working on a “legacy” project.

SNAGHTML503fdc8

Or, ReSharper makes it easy to implement the suggested changes.

image

Of course you can configure EVERYTHING to suit your taste.

image

From the JetBrains site, here are the highlights of the latest version’s updates.

Compared to previous versions, ReSharper 5 has evolved in four major directions:

  1. Web Development. We have greatly extended the toolset available to ASP.NET developers when they work with markup files and web site infrastructure. ASP.NET MVC developers get a bonus in additional code inspections, syntax highlighting, navigation, and code completion for controllers and actions.
  2. Project Maintenance. ReSharper becomes a valuable assistant not only to individual developers but to teams working with large, complicated projects. It helps them view, change and maintain project structure.
  3. Support for Visual Studio 2010. ReSharper 5 provides support for the new Visual Studio version earlier than ever. Of course, Visual Studio 2005 and 2008 are supported, too.
  4. Code Analysis. This area incorporates several improvements, including “plainly” implementing a substantial pack of new code inspections; the opportunity to get an overview of all code smells in solution; upgrading foreach and for loops to LINQ queries; and letting you track how data values and method calls are passed through your code.
  5. Other enhancements include extended IntelliSense, bookmarking, native NUnit support, and more.

 [ Download a free 30 day trail HERE ]

I’ll update you when I have a couple months of use under my belt.

Technorati Tags: ,,ReSharper,

A simple way to Defend Against Unauthenticated Web Service Access.

Scenario – a developer wants to restrict unauthorized access to a we service in his application.

WARNING: This method is easy but not bulletproof !!!!

The level of security desired is modest and the developer does NOT want to use SSL, WS-* extensions or any other certificate based infrastructure.

A customer emailed be this week with this very question.

They were using the ASP.NET Membership Application Service and Forms based authentication in their application and discovered that the user’s authenticated state in the application was not accessible from his web services.

The problem ?

Web Services (ASMX) and Web Pages (ASPX) can both have session state but they do not SHARE session state.

Here are two quick ways to authenticate calls to Web Service Methods. (There are, of course, many ways.)

First…….

You can pass the UserName and Password to the web service method and manually authenticate.

[ Remember, without SSL the username and password are passed over the web in “clear text” and are theoretically exposed to “man in the middle” interceptions. ]

image

The web service method would look like this….

Code Snippet
  1. [WebMethod]
  2. public string CallWithCredentials(string uname, string pwd)
  3. {
  4.     if (Membership.ValidateUser(uname, pwd))
  5.     {
  6.         return “User IS Authenticated.”;
  7.     }
  8.     else
  9.     {
  10.         return “User NOT Authenticated”;
  11.     }
  12. }

 

And be called like this……

Code Snippet
  1. protected void ButtonCallService_Click(object sender, EventArgs e)
  2. {
  3. MembersOnlyWS.MembersOnly ws = new MembersOnlyWS.MembersOnly();
  4. LabelResults.Text = ws.CallWithCredentials(TextBoxUser.Text, TextBoxPwd.Text);
  5. }

Though this works, it is inelegant because it causes the actual credentials to be passed for each web service method call.

Here is a method that I prefer.

I start by adding a table to my ASPNETDB database, though really you could put it anywhere.

image

Next, I add a LoggedIn event handler to the LoginView control in my site’s MasterPage.

Code Snippet
  1. protected void LoginUser_LoggedIn(object sender, EventArgs e)
  2. {
  3.     Guid newTokenId = new Guid();
  4.     using (ASPNETDBEntities db = new ASPNETDBEntities())
  5.     {
  6.         ServiceToken newToken = new ServiceToken();
  7.         newToken.Token = newTokenId;
  8.         db.AddToServiceTokens(newToken);
  9.         db.SaveChanges();
  10.     }
  11.  
  12.     Session["UserServiceToken"] = newTokenId;
  13. }

 

When the user logs in this code does three things.

1.) Gets a new GUID

2.) Stores that GUID in the ServiceTokens table

3.) Stores the same GUID in a session variable.

Now we re-factor our Web Service method to accept a single parameter (a GUID as a sting) instead of a UserName / Password pair.

Code Snippet
  1. [WebMethod]
  2. public string CallWithToken(string token)
  3. {
  4.     if (token == “” || token == null)
  5.     {
  6.         return “User NOT Authenticated”;
  7.     }
  8.     else
  9.     {
  10.  
  11.         using (ASPNETDBEntities db = new ASPNETDBEntities())
  12.         {
  13.             Guid userGuid = new Guid(token);
  14.             var myToken = (from t in db.ServiceTokens where t.Token == userGuid select t).FirstOrDefault();
  15.             if (myToken != null)
  16.             {
  17.                 return “User IS Authenticated.”;
  18.             }
  19.             else
  20.             {
  21.                 return “User NOT Authenticated”;
  22.             }
  23.         }
  24.     }
  25. }

When the method gets called we take the GUID/Token and see if that GUID exists in the ServiceTokens table.

If the web method does not receive a GUID, or if the GUID received does not exist in the ServiceTokens table, the user is declared as “Not Authenticated”.

How YOUR application handles method calls that fail to provide a valid token will be up to you and will depend on the specifics of your application. IN the case of this demo, we just return an “unauthenticated” message.

Now, in our page code we can call our Web Service Method by retrieving the GUID that we previously stored in a session variable and passing it to the web service method.

Code Snippet
  1. protected void ButtonPreAuthCallService_Click(object sender, EventArgs e)
  2. {
  3.     if (!HttpContext.Current.User.Identity.IsAuthenticated)
  4.     {
  5.         Response.Redirect(“~/Account/Login.aspx”);
  6.     }
  7.  
  8.     MembersOnlyWS.MembersOnly ws = new MembersOnlyWS.MembersOnly();
  9.     if (Session["UserServiceToken"] != null)
  10.     {
  11.         LabelPreAuthResult.Text = ws.CallWithToken(Session["UserServiceToken"].ToString());
  12.     }
  13.     else
  14.     {
  15.         Response.Redirect(“~/Account/Login.aspx”);
  16.     }
  17. }

Notice that if the user is not authenticated or the GUID in the session object is empty, the user gets redirected to the LogIn.aspx page.

In practice this means that our user interface won’t let an unauthenticated user make a web service method call but the web service method itself  could be called directly from outside our application and that’s why we require a valid GUID that is created when a user successfully logs in.

There is one gotcha that we need to address.

Every time a user logs in, a GUID gets added to the ServiceTokens table but those tokens never get removed.

The more the application gets used, the higher the likelihood that a brute force attack could stumble on a valid token and those tokens are valid forever (never deleted from the database.).

To solve this problem we’ll need to delete the tokens from the ServiceTokens table when the user is done with them.

If the user logs out this is easy to do.

We can modify the LogedInTemplate of the LoginView control in our master page to hook an event handler for when the user logs out.

Code Snippet
  1. <LoggedInTemplate>
  2.     Welcome <span class=”bold”><asp:LoginName ID=”HeadLoginName” runat=”server” /></span>!
  3.     [ <asp:LoginStatus ID="HeadLoginStatus" runat="server" LogoutAction="Redirect" LogoutText="Log Out" OnLoggedOut="RemoveServiceToken" LogoutPageUrl="~/"/> ]
  4. </LoggedInTemplate>

 

Then we can implement that “OnLoggedOut” event handler as so…..

Code Snippet
  1. protected void RemoveServiceToken(object sender, EventArgs e)
  2. {
  3.     using (ASPNETDBEntities db = new ASPNETDBEntities())
  4.     {
  5.         Guid userGuid = new Guid(Session["UserServiceToken"].ToString());
  6.         var myToken = (from t in db.ServiceTokens where t.Token == userGuid select t).FirstOrDefault();
  7.         if (myToken != null)
  8.         {
  9.             db.DeleteObject(myToken);
  10.             db.SaveChanges();
  11.         }
  12.     }
  13.     Session["UserServiceToken"] = “”;
  14. }

 

Note that the UserServiceToken is removed from the Session Object and the ServiceTokens table in the database.

This is fine if the user actually logs out, but what if the user does NOT log out?

We still want to clean up the GUIDs even if the user never logs out.

[ NOTE : the following method only works if session management is “InProc” if we are using alternate session management then we would need a different Session_End strategy. ]

When the session expires, we can clean up the GUIDs as well.

In the Global.asax.cs file ….

Code Snippet
  1. void Session_End(object sender, EventArgs e)
  2. {
  3.     // Code that runs when a session ends.
  4.     // Note: The Session_End event is raised only when the sessionstate mode
  5.     // is set to InProc in the Web.config file. If session mode is set to StateServer
  6.     // or SQLServer, the event is not raised.
  7.         if (Session["UserServiceToken"] != null)
  8.         {
  9.             using (ASPNETDBEntities db = new ASPNETDBEntities())
  10.             {
  11.                 Guid userGuid = new Guid(Session["UserServiceToken"].ToString());
  12.                 var myToken = (from t in db.ServiceTokens where t.Token ==  userGuid select t).FirstOrDefault();
  13.                 if (myToken != null)
  14.                    {
  15.                    db.DeleteObject(myToken);
  16.                    db.SaveChanges();
  17.                    }           
  18.             }
  19.             Session["UserServiceToken"] = “”;
  20.         }
  21. }

Note that there is some subtle logic here.

When the session expires, the LogInView control will still show the user as logged in but when we actually TEST the authentication state of the user in our code-behind ….

Code Snippet
  1. if (!HttpContext.Current.User.Identity.IsAuthenticated)
  2. {
  3.     Response.Redirect(“~/Account/Login.aspx”);
  4. }

The result will be false and the user will be asked to re-authenticate by entering their username and password in order to call the web service method.

This makes our web service method unlikely to be successfully invoked by an unauthorized user because in order to do so, a bad guy would need to either need to intercept a valid set of credentials or guess a GUID that exists in the ServiceTokens table and use it while a valid user is logged on.

Hope someone finds this useful :)

[ Click HERE to download an ASP.NET 4 sample. ]

ASP.NET Membership – Handling Authenticated Users that are Not Authorized.

image

When you create an ASP.NET Web Forms project using the default template, the web.config file specifies where users will “Log In” to the site.

Code Snippet
  1. <authentication mode=Forms>
  2.   <forms loginUrl=~/Account/Login.aspx timeout=2880 />
  3. </authentication>

The template also provides the “Account” directory as seen in the Visual Studio Explorer snapshot above.

Note that the “Account” contains it’s own web.config file which contains the following elements.

Code Snippet
  1. <?xml version=1.0?>
  2. <configuration>
  3.  
  4.   <location path=Register.aspx>
  5.     <system.web>
  6.       <authorization>
  7.         <allow users=*/>
  8.       </authorization>
  9.     </system.web>
  10.   </location>
  11.  
  12.   <system.web>
  13.     <authorization>
  14.       <deny users=?/>
  15.     </authorization>
  16.   </system.web>
  17.  
  18. </configuration>

The Login.aspx page is accessible to all users because it is specified as the LoginUrl for user authentication.

The web.config file is evaluated top-to-bottom.

The authorization element explicitly denies access to all UNAUTHENTICATED users by way of the specification <deny users=”?” /> where the question mark means all unauthenticated users.

However, if the user does not have an account on the web site, they will need access to the “Register.aspx” page in order to create one.

This resources specific access is provided via the <location> element which explicitly grants access to the “Register.aspx” page with the <allow users=”*”  /> where the star means all users, authenticated or not.

All this means that whenever a resource (page / directory) is requested but the user lack the necessary privileges for that resource, the user is redirected to the loginUrl specified in the application’s default web.config file.

In the default ASP.NET Web Forms template this works fine because the only authorization criteria is Logged In or NOT Logged In.

But what if our Authorization criteria is more diverse than that.

ASP.NET Membership makes it easy to configure URL based Authorization based on “ASP.NET Roles” or even for a specific user.

In the snapshot above showing solution in the Visual Studio Solution Explorer, please note 2 new directories.

  1. Admin
  2. SuperUser

The “Admin” folder will contain pages that implement administrative features for our web site, so we need to restrict access so that a user must be BOTH logged in AND a member of the “Administrator” Role Group in order to access the folders contained pages.

Our ”Admin” folder contains a web.config file with a defaul authorization critera that denies access to all users and then specifically GRANTS access to administrators with the element “<allow roles=”Administrator” />

Note that I have also granted access for ALL USERS to the page “AccessDenied.aspx”

Code Snippet
  1. <?xml version=1.0?>
  2. <configuration>
  3.     <location path=AccessDenied.aspx>
  4.         <system.web>
  5.             <authorization>
  6.                 <allow users=*/>
  7.             </authorization>
  8.         </system.web>
  9.     </location>
  10.   <system.web>
  11.     <authorization>       
  12.        <allow roles=Administrator/>  
  13.        <deny users=*/>      
  14.     </authorization>
  15.   </system.web>
  16. </configuration>

This creates an additional user experience challenge for us since a user can be logged in but NOT an Administrator. By default, when Authorization fails for any resource the user is redirected to the loginUrl.

This will be confusing for the user since they are already logged in, they just aren’t part of the “Administrator” role.

To improve the user experience, we’ll add some code to the Load Event of the Login.aspx page to determine whether or not we got there because an already logged in user tried to access a resource in the “Admin”  folder.

If this is the case we’ll redirect them to the “Admin/AccessDenied.aspx” file which is accessible to all users on the web site.

Code Snippet
  1. using System;
  2. using System.Web;
  3. using System.Web.Security;
  4.  
  5. namespace NETOOPWF.Account
  6. {
  7.     public partial class Login : System.Web.UI.Page
  8.     {
  9.         protected void Page_Load(object sender, EventArgs e)
  10.         {
  11.             string test = System.Configuration.ConfigurationManager.AppSettings["SuperUser"];
  12.             if (Request.IsAuthenticated)
  13.             {
  14.                 string mp = HttpUtility.UrlEncode(Request.QueryString["ReturnUrl"]);
  15.                 if (mp != null)
  16.                 {
  17.                     mp = mp.ToLower();
  18.                     if (mp.IndexOf(“%2fadmin”) > -1)
  19.                     {
  20.                         Response.Redirect(“~/Admin/AccessDenied.aspx”);
  21.                     }
  22.                 }
  23.             }
  24.             RegisterHyperLink.NavigateUrl = “Register.aspx?ReturnUrl=” + HttpUtility.UrlEncode(Request.QueryString["ReturnUrl"]);
  25.         }
  26.     }
  27. }

Here’s the Pseudo Code for the logic :

  • Check is the user is already logged in. If Yes (Then we probably got here due to an unauthorized access attempt ) ……
  • Get a string that contains the relative path to the page that was requests.
  • Find out if the requested page is in the ”Admin” directory. If Yes ….
  • Send the user to the “/Admin/AccessDenied.aspx” page.

Now, if the user requests a resourse in the Admin folder and the user is anonymous then they will be presented with the Login Page.

If they are already logged in but NOT an Administrator, they will see this page.

SNAGHTML19704c8

Note that we can use the same process when implementing user specific authorization.

Note also the folder named “SuperUser” in the Solution Explorer

image

The web.config file in the ”SuperUser” folder contains looks like this.

Code Snippet
  1. <?xml version=1.0?>
  2. <configuration>
  3.     <location path=AccessDenied.aspx>
  4.         <system.web>
  5.             <authorization>
  6.                 <allow users=*/>
  7.             </authorization>
  8.         </system.web>
  9.     </location>
  10.   <system.web>
  11.     <authorization>      
  12.        <allow users=SuperUser/> 
  13.        <deny users=*/>     
  14.     </authorization>
  15.   </system.web>
  16. </configuration>

 

Note that instead of allowing users based on a role, as we did in the “Admin” folder, we deny access to everyone and then explicitly GRANT access to ONLY a specific user who’s User Name is “SuperUser”.

We also have an AccessDenied.aspx page in the “SuperUser” folder that is accessible to anyone.

Next we modify the “Login.aspx.cs” file as follows.

Code Snippet
  1. using System;
  2. using System.Web;
  3. using System.Web.Security;
  4.  
  5. namespace NETOOPWF.Account
  6. {
  7.     public partial class Login : System.Web.UI.Page
  8.     {
  9.         protected void Page_Load(object sender, EventArgs e)
  10.         {
  11.             string test = System.Configuration.ConfigurationManager.AppSettings["SuperUser"];
  12.             if (Request.IsAuthenticated)
  13.             {
  14.                 string mp = HttpUtility.UrlEncode(Request.QueryString["ReturnUrl"]);
  15.                 if (mp != null)
  16.                 {
  17.                     mp = mp.ToLower();
  18.                     if (mp.IndexOf(“%2fsuperuser”) > -1)
  19.                     {
  20.                         Response.Redirect(“~/SuperUser/AccessDenied.aspx”);
  21.                     }
  22.                     if (mp.IndexOf(“%2fadmin”) > -1)
  23.                     {
  24.                         Response.Redirect(“~/Admin/AccessDenied.aspx”);
  25.                     }
  26.                 }
  27.             }
  28.             RegisterHyperLink.NavigateUrl = “Register.aspx?ReturnUrl=” + HttpUtility.UrlEncode(Request.QueryString["ReturnUrl"]);
  29.         }
  30.     }
  31. }

Since any user who requests a page in the \SuperUser folder and is NOT User Name “SuperUser” will get redirected to the LogIn page we can check to see if the requested resource was in the SuperUser folder.

Since the user named “SuperUser” would have access to all the resources in that folder, we know that the request was directed here because the user was NOT “SuperUser” and therefore is not Authorized.

Then we just redirect the user to the “\SuperUser\AccessDenied.aspx”  page.

SNAGHTML1ad7b9d

Adding ASP.NET Membership to your OWN Database.

ScottGu forwarded me an email from a developer this weekend who wanted to use ASP.NET Membership in an application deployed on a shared hosting account that allows only one SQL Server database.

It’s not all that difficult to add ASP.NET membership (as well as other ASP.NET services) to your existing database.

ASP.NET doesn’t really care where the information repository for it’s built in services live as long as they are complete.

The database that contains the ASP.NET Application Services repository is resolved via a standard connection string in the application’s web.config file.

   1:     <connectionStrings>
   2:      <add name="ApplicationServices"
   3:           connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;                                  

                    AttachDBFilename=|DataDirectory|\aspnetdb.mdf; User Instance=true"
   4:           providerName="System.Data.SqlClient" />
   5:    </connectionStrings>

In the entry above the connection points to the a default database of aspnetdb.mdf in the local application’s App_Data directory.

Note that the default is determined by settings in the machine.config file. If you have run the aspnet_regsql.exe utility on your developer machine to configure a SQL Server database to house the membership / ASP.NET Application Services tables than your machine.config defaults probably point to a SQL Server instance instead of a SQL Express database.

In any event, you can use a connection sting like the one above and simply change the .mdf file name to the one that you need to use in your App_Data folder.

If you are doing this on your shared host that you would specify the connection string to your hosting provider’s database and they would have provided you with the necessary connection information when you signed up for the account.

Once our application can connect to the database we’ve chosen to house out membership information we need to configure our database for use by the Membership Provider.

The ASP.NET installation provides some .SQL script files that we can use to make this process easier.

In Windows Explorer, navigate to your .NET Framework install directory.

On my development machine it was located here.

C:\Windows\Microsoft.NET\Framework\v4.0.30319

Note the highlighted .SQL files in the figure below

ASPSQLServicesCodeFiles

Though all may be useful to you in setting up the various ASP.NET Application Services, for the purposes of this post, we’re only going to set up the ASP.NET Membership service.

We will need the first two .sql files…..

InstallCommon.sql

InstallMembership.sql

Make separate copies of these as we’ll need to edit them before we run them.

Next you need to determine how you will execute T-SQL against your SQL Server instance.

If you are working on your own machine you can simply run SQL Server Management Studio on your machine (or against your SQL Server instance.)

If you’re host does not support direct connections with SQL Server Management Studio then they will likely have provided some web based administration mechanism and you will need to use that to execute the T-SQL.

In my sample application I created an empty SQL Express database named AddedMembershipDemo.mdf

AddedMembershipDemoMDF

First open the copy of InstallCommon.sql  that you made.

You will have to make a couple of edits to the code. You will note several references to the database name “”aspnetdb”……

Here are a few examples:

SET @dbname = N’aspnetdb’

USE [aspnetdb]
GO

You must change all references to “aspnetdb” to the name of the database that you are adding the ASP.NET Application Services to.

Since the database already exists you will want to comment out the code bock that looks like this:

   1: IF (NOT EXISTS (SELECT name

   2:                 FROM master.dbo.sysdatabases

   3:                 WHERE name = @dbname))

   4: BEGIN

   5:   PRINT 'Creating the ' + @dbname + ' database...'

   6:   DECLARE @cmd nvarchar(500)

   7:   SET @cmd = 'CREATE DATABASE [' + @dbname + '] ' + @dboptions

   8:   EXEC(@cmd)

   9: END

  10: GO

Once you have made those changes you should be able to run the resulting script successfully (though you may get a warning about some permission assignments.)

Next open InstallMembership.sql and change the references to aspnetdb to whatever your new database name is and run that script as well.

On success you’re database will contain Tables, Views, Stored Procedures, etc like this.

AddedMembershipDemoMDFTables

If you started your application by creating from the default ASP.NET application template, your web.config file should already have the configuration section for ASP.NET Membership. If not you will need to add it manually as below.

   1: <membership>

   2:   <providers>

   3:     <clear/>

   4:     <add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="ApplicationServices"

   5:          enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false"

   6:          maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10"

   7:          applicationName="/" />

   8:   </providers>

   9: </membership>

Now you should be able to open your site and start adding users to the membership repository.

Code Snippet : Manually Creating a New ASP.NET Membership User in C#

Though ASP.NET controls are great, in many cases I prefer the power and flexibility of doing things in code. 

I wrote the following code this week as part of a demo I’m working on and thoght I would share it. (Why write all these case statements yourself.)

I hope someone finds it useful.

   1:  public partial class NewUser : System.Web.UI.Page
   2:  {
   3:      protected void Page_Load(object sender, EventArgs e)
   4:      {
   5:       Session["ContinueDestinationPageUrl"] = Request.QueryString["ReturnUrl"];
   6:      }
   7:   
   8:      protected void btnAddUser_Click(object sender, EventArgs e)
   9:      {
  10:          if (Page.IsValid)
  11:          {
  12:              MembershipCreateStatus createStatus;
  13:              string sUserName = tbUserName.Text;
  14:              string sPassword = tbPassword.Text;
  15:              string sEmail = tbEmailAddress.Text;
  16:              string sQuestion = tbSecurityQuestion.Text;
  17:              string sAnswer = tbSecurityAnswer.Text;
  18:   
  19:              MembershipUser newUser = Membership.CreateUser(
                                            HttpUtility.HtmlEncode(sUserName.Trim()),
  20:                                       HttpUtility.HtmlEncode(sPassword.Trim()),
  21:                                        HttpUtility.HtmlEncode(sEmail.Trim()),
  22:                                       HttpUtility.HtmlEncode(sQuestion.Trim()),
  23:                                       HttpUtility.HtmlEncode(sAnswer.Trim()),
  24:                                       true,
  25:                                        out createStatus);
  26:              string CreateResultMessage = "";
  27:              switch (createStatus)
  28:              {
  29:                  case MembershipCreateStatus.Success:
  30:                      CreateResultMessage =
                                  "&raquo; The user was successfully created. &laquo;";
  31:                      break;
  32:                  case MembershipCreateStatus.InvalidUserName:
  33:                      CreateResultMessage =
                                   "The user name was not found in the database.";
  34:                      break;
  35:                  case MembershipCreateStatus.InvalidPassword:
  36:                      CreateResultMessage =
                                   "The password is not formatted correctly.";
  37:                      break;
  38:                  case MembershipCreateStatus.InvalidQuestion:
  39:                      CreateResultMessage =
                                   "The password question is not formatted correctly.";
  40:                      break;
  41:                  case MembershipCreateStatus.InvalidAnswer:
  42:                      CreateResultMessage =
                                  "The password answer is not formatted correctly.";
  43:                      break;
  44:                  case MembershipCreateStatus.InvalidEmail:
  45:                      CreateResultMessage =
                                 "The e-mail address is not formatted correctly.";
  46:                      break;
  47:                  case MembershipCreateStatus.DuplicateUserName:
  48:                      CreateResultMessage =
                                  "The user name already exists in the database
                                                  for the application.";
  49:                      break;
  50:                  case MembershipCreateStatus.DuplicateEmail:
  51:                      CreateResultMessage =
                                  "The e-mail address already exists in the database
                                                  for the application.";
  52:                      break;
  53:                  case MembershipCreateStatus.UserRejected:
  54:                      CreateResultMessage =
                                   "The user was not created, for a reason defined
                                              by the provider.";
  55:                      break;
  56:                  case MembershipCreateStatus.InvalidProviderUserKey:
  57:                      CreateResultMessage =
                                   "The provider user key is of an invalid type or
                                              format.";
  58:                      break;
  59:                  case MembershipCreateStatus.DuplicateProviderUserKey:
  60:                      CreateResultMessage =
                                    "The ProviderUserKey already exists in the database
                                              for the application.";
  61:                      break;
  62:                  case MembershipCreateStatus.ProviderError:
  63:                      CreateResultMessage =
                                "The provider returned an error that is not described
                                                  by other ";
  64:                      CreateResultMessage +=
                                    "MembershipCreateStatus enumeration values.";
  65:                      break;
  66:              }
  67:   
  68:              if (createStatus != MembershipCreateStatus.Success)
  69:              {
  70:                  lblCreateResultMessage.CssClass = "ValidationError";
  71:                  lblCreateResultMessage.Text = CreateResultMessage;
  72:                  btnAddUser.Visible = true;
  73:                  divResultMessage.Visible = true;
  74:              }
  75:              else
  76:              {
  77:                  lblCreateResultMessage.CssClass = "bold";
  78:                  btnAddUser.Visible = false;
  79:                  FormsAuthentication.SetAuthCookie(newUser.UserName, false);
  80:   
  81:                  string continueUrl =
                              Session["ContinueDestinationPageUrl"].ToString();
  82:                  if (String.IsNullOrEmpty(continueUrl))
  83:                  {
  84:                      continueUrl