Archive for the ‘ .NET’ Category

ASP.NET Password Strength Indicator with jQuery Plugin.

Password strength is a key factor in account security for weeb applications. As developers we all have a basic understanding of what a secure password is but the averge consumer of internet applications doesn’t so adding a visual indicator when your user selectes a password is a great feature.

There are many, many plugins that we could select from to implement this feature I’ve selected this one which makes things very easy.

http://plugins.jquery.com/project/password_strength


<%@ 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/jquery.password_strength.js" type="text/javascript">
    </script>
    <style type="text/css"> 
    .password_strength {
	    }
    .password_strength_1 {
	    background-color: #fcb6b1;
	    }
    .password_strength_2 {
	    background-color: #fccab1;
	    }
    .password_strength_3 {
	    background-color: #fcfbb1;
	    }
    .password_strength_4 {
	    background-color: #dafcb1;
	    }
    .password_strength_5 {
	    background-color: #bcfcb1;
	    }
    </style> 
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <h2>Password Strength</h2>

    <table style="border-spacing: 0px; border-style: none">
      <tbody>
      <tr>
        <td style="text-align: right"><label>User Name:</label></td>
        <td>
           <asp:TextBox ID="username" runat="server" Width="200px"></asp:TextBox>
        </td>
      </tr>
      <tr>
        <td style="text-align: right"><label>Password:</label></td>
        <td>
            <asp:TextBox ID="password" class=password runat="server" 
                ClientIDMode="Static" TextMode="Password" Width="200px">
            </asp:TextBox> 
        </td>
      </tr>
      </tbody>
    </table>

  
<script type="text/javascript">
    $('form').attr('autocomplete', 'off');
    $('#password').password_strength();
</script> 

</asp:Content>

In the code above I’ve used in-line CSS and script for the sake of learning simplicity.

The CSS is used by the plugin to set the color that corresponds with the “level” of the password as entered.

The script block starting on line 50 turns autocomplete off for the form (we’re working with a password after all) and applies the password strength functionality to the ASP.NET textbox controll names “password:.

As with all the ASP.NET jQuery work that we’ve been doing, we must set the Client Id Mode to “static” so tha tthe ASP.NET runtime does not modify the client ID of the emitted HTML text box.


You can download a working sample [ HERE]


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.

Podcast – Damian Edwards, Program Manager Web Tools & Platforms

Damain is a Program Manager Microsoft’s ASP.NET team and is responsible for WebForms and the WebForms Developer Experience

In this episode I talk with Damain about the future of WebForms and it’s evolution, the inflewence of DynamicData on WebForms, code generation for ASP.NET WebForms and more.

Resources

Listen

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

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 »

Visual Studio 2010 Web Standards Update

clip_image002Over the last several months the “new wave” of web standards have been  moving at an accelerated pace,

All the popular browsers are pushing the envelope including Microsoft’s own IE9 and the new standard open up exciting new opportunities for developers.

Microsoft at large and the ASP.NET and Visual Studio teams are heavily invested in supporting the new wave of web standards in our tools and platforms.

ASP.NET developers have been asking for HTML5 & CSS3 support and yesterday we announced the public availability of Visual Studio Web Standards Update which brings a ton of HTML5 & CSS3 support to Visual Studio 2010 SP1.  

The VS Web Standards Update is a free extension available for anyone who is using Visual Studio 2010 SP1 and it provides HTML5 & CSS3 support based on current W3C specifications.

clip_image002[4]

Here are some highlights of what’s included !

HTML5

clip_image002[6]

VS Web Standards Update provides you intellisense and validation for most common HTML 5 features like:

Browser APIs

  • Geo-Location – Having location aware websites is growing trend and now you will have full intellisense and validation within Visual Studio for creating websites which are location aware.  For sample view the source for the IE9 test drive demo.
  • Local Storage – IE has been supporting local storage from IE8 onwards, now Visual Studio will provide you with full fidelity intellisense to create sites which can save state within browser.  For sample of try view source on HTML5 Demo Site

CSS3

clip_image002[8]

This update supports intellisense and validation for most of the CSS3 modules including:

Also, if you are trying to make websites which work well on a variety of platforms and browsers you will love the fact that Web Standards Update not only supports IE specific prefixes like –ms; but also other browser prefixes like –webkit and –moz.

Some links :

NOTE:  The Web Standards Update works on both VS 2010 SP1 and VWD Express 2010 SP1.  As this is a Visual Studio Extension,certain CSS3 selector syntax & Browser API intellisense may not be supported in Visual Web Developer Express. .

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 ].


A few reading resources for securing your IIS server.

Resources for securing Internet Information Services

http://support.microsoft.com/kb/282060

Security Guidance for IIS

http://technet.microsoft.com/en-us/library/dd450371(WS.10).aspx

Chapter 16 – Securing Your Web Server

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

Securing Your IIS Log File Folder

http://msdn.microsoft.com/en-us/library/ee810489(v=CS.20).aspx

Chapter 6: Hardening Web Services

http://technet.microsoft.com/en-us/library/cc264459.aspx

IIS 6.0 Technical Reference

http://technet.microsoft.com/en-us/library/cc775635(WS.10).aspx

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.

Find Existing ODATA providers.

· The OData Producers list on the OData.org site.

· On the ODataPrimer wiki site.

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

Silverlight Integration Pack for MS Enterprise Library 5.0

clip_image001[3]

Customer Value


clip_image003[3]For years the Enterprise Library application blocks have helped developers address the typical cross-cutting concerns of enterprise development (such as diagnostic logging, data validation, caching, and exception handing). With over 3.2 million downloads, they take a prominent place in the toolbox of a modern .NET developer.  These cross-cutting concerns are just as important to a Silverlight application as they are to any other type of application. However, implementing them in Silverlight can be quite a different matter.  The Silverlight Integration Pack is focused on Silverlight LOB development and provides guidance and reusable components designed to encapsulate recommended practices which facilitate consistency, ease of use, integration, and extensibility.


What’s in the pack ?

The tube map below depicts the paths through the Silverlight Integration Pack.

clip_image004[3]


Asset

Description

Validation Application Block

The Validation Application Block supports the following scenarios:

§ Executing validation rules across multiple tiers and gathering results.

§ Annotating your business entities with validation attributes.

§ Ensuring validation attributes compatibility with WCF RIA Services.

§ Defining validation rules in configuration.

§ Validating conditionally using rule sets.

§ Implementing self-validation.

§ Defining validation attributes in metadata. Silverlight doesn’t support the MetadataTypeAttribute. In the .NET Framework, this attribute is used to define metadata classes with validation attributes for your generated business entities. The Validation Application Block provides an implementation of the MetadataTypeAttribute for Silverlight.

§ Supporting IDataErrorInfo.

Logging Application Block

Allows you to decouple your logging functionality from your application code. The Logging Application Block routes log entries to various out-of-the-box or custom destinations (locally or through a web service), it supports runtime changes to, for example,  turn existing logging up and down or change logging destinations. Batch logging is supported. The block is shipped with an implementation of a WCF Remote logging service that integrates with the desktop version of the Logging block. Additionally, tracing feature allows you to correlate log entries to a specific activity/workunit scope.

Caching Application Block

A brand new implementation of the Caching application block, which is mimicking the System.Runtime.Caching API from .NET with support for in-memory caching and persistent caching (via isolated storage). It has support for expiration and scavenging policies as well notification of cache purging.

Exception Handling Application Block

A port of the desktop version of the Exception Handling Application Block, which allows you to handle exceptions that might occur in any layer of your application in a consistent manner.

Interception & Policy Injection Application Block

Update to Unity container for Silverlight with support for type and instance interception.

 

Configuration support

The Silverlight Integration Pack offers flexible configuration options, including:

§ XAML-based configuration support

§ Asynchronous configuration loading

§ Interactive configuration console supporting profiles (desktop vs. Silverlight)

§ Translation tool for XAML config (needed to convert conventional XML configuration files) available as a config tool wizard, an MS Build task, or a standalone command-line tool

§ Programmatic configuration support via a fluent interface or attributes

Reference Implementation

Along with the reusable application blocks and tooling, next week we will be releasing a new Developer’s Guide and an accompanying Reference Implementation to illustrate the typical challenges you might encounter when building a Silverlight LOB application. In addition, comments from fictional personas, including an experienced Enterprise Library developer named Ed and an IT Professional named Mark, help you understand the rationale behind certain design decisions.

 


How to get it ?


Both Enterprise Library 5.0 and Enterprise Library 5.0 Silverlight Integration Pack are available as Windows Installer Packages (MSI) via MSDN or as NuGet packages. The configuration tool is also available as a Visual Studio extension package (VSIX) from the Visual Studio Gallery.

Note: If you are new to NuGet, please do not look for Silverlight-specific Enterprise Library packages. NuGet packages are multi-platform. Just get the official EntLib packages (easily recognizable by the orange logo and the author – Microsoft). Depending on the framework your project is targeting, NuGet will install the corresponding bits. The only platform specific packages are source code packages.

For more information, please see this post explaining our NuGet release strategy.


Some Channel 9 Videos


clip_image005

Enterprise Library for Silverlight – Validation demo

clip_image006

Enterprise Library for Silverlight – Data Caching demo

clip_image007

Enterprise Library for Silverlight – Logging demo

clip_image008

Enterprise Library for Silverlight – Cross-tier validation demo

clip_image009

Enterprise Library for Silverlight – Interception demo

clip_image010

Enterprise Library for Silverlight – Remote Logging demo

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.

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

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 »

Get your FREE ASP.NET Razor Templates

Get the [ HERE ] at TemplateMonster.com


Python Tools for Visual Studio

Beta 2 of the Python Tools for Visual Studio has shipped. 

This is primarily a bug fix release with lots of involvement from the user community. 

Release notes & the bits are available at: Beta2: http://pytools.codeplex.com/releases/view/63597

The project lives at : http://pytools.codeplex.com

Visual Studio Async CTP v2

clip_image002

Coinciding with MIX 2011, the VB/C# Languages and TC teams have released the second Visual Studio Async CTP that is compatible with VS2010 SP1 and provides Windows Phone 7 support.

The first CTP had more than 19,000 downloads, more than half a million views of the videos, many blogs and a lot of community excitement.

With this release we are excited about the ease with which developers can now provide responsiveness to their phone applications. We changed the EULA to allow using the CTP “As is” so that phone developers can use it in their Marketplace applications.

Check it out !

http://msdn.microsoft.com/en-us/vstudio/async

RIA Services Technology Released at MIX

Last week at MIX, the RIA Services team is put out two releases:

1. WCF RIA Services V1.0 SP2 Preview (April 2011)

a. As a standalone download; also included with the Silverlight 5 Beta Tools chainer.

b. Preview quality – does not include Go Live support

c. The existing SP1 installation will remain available as well

d. Includes:

     i. Changes to work with SL5  / SL5 tools

    ii. DateTimeOffset is now a supported type

   iii. Client/session id can be added to a server request for per-client trace/tracking

2. WCF RIA Services Toolkit (April 2011)

a. Works with either SP1 or SP2

b. Replaces the December 2010 edition of the Toolkit

i. Note that the May 2010 edition stays online, as it’s based on V1.0 RTM (pre-SP1)

c. Includes:

     i. jQuery Client (RIA/JS)  Requires SP2 Preview

    ii. ViewModel Updates

   iii. T4 CodeGen Updates

NuGet Packages

For MIX, the RIA Services team also introduced NuGet packages for some of our Toolkit components.

The NuGet packages serve as an alternative to the Toolkit MSI, allowing developers to reference specific components directly into a solution, rather than installing the MSI on their machine.

1. RIAServices.WindowsAzure – Includes the Windows Azure Table Storage DomainService

2. RIAServices.ViewModel – Includes the Silverlight ViewModel features

3. RIAServices.T4 – Code Generation using T4

4. RIAServices.Endpoints – References and configures the SOAP and JSON endpoints

5. RIAServices.jQuery – Includes all of the script files for the jQuery client, and enables the “transmitMetadata” option on the JSON endpoint

6. RIAServices.Toolkit.All – Adds all of the above packages to your project

Note, there are a couple of Toolkit components that don’t have NuGet packages:

1. LinqToSql DomainService – because it requires a Registry key to integrate with the Domain Service Wizard

2. ASP.NET DomainDataSource / DomainValidator – coming in the near future.

CodePlex

The JavaScript files used by the jQuery client will be published on http://wcf.codeplex.com.  We also have a sample application entitled Big Shelf that will also be available on CodePlex.

Get all the details at http://bit.ly/wcfjquery.

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 ]


WebMatrix Optional Render Sections – like for page specific script.

I’ve been simultaneously trying to improve the quality of my jQuery code and increasingly seeing WebMatrix as a viable option for many non-trivial web development scenarios.

It occurred to me that the Razor @RenderSection “optional” attribute would make for a clever practice when injecting page specific jQuery.

ASP.NET Web Pages (WebMatrix) templating features include the ability to “pull into” the template, some page specific content.

Note the image below.

The yellow highlighted section comes from the Default.cshtml page and all the rest lives in the _SiteLayout.cshtml file.

In the case above the content comes from the standard site template from the WebMatrix tool (except for the button which I’ve added for this demo.

A JavaScript library that I intended to use on every page could easily be declared in the Layout file, but what about page specific stuff or code that I want to pull in “sometimes” but not always.

Well, ASP.NET Web Pages (Razor) has this clever construct @RenderSection(“footer”) which has a optional parameter as follows.

@RenderSection(“footer”, required: false)

Read the rest of this entry »

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.

Microsoft NuGet Package Manager for Visual Studio & VWD

In this post I demonstrated using the Package Manager (NuGet) to install jQuery into your Website.

It’s a different experience in Visual Studio 2010 / Visual Web Developer Express so I thought I’d provide another post that walks you through it.

Plus, there is a tiny gotcha that might case new developers pause.

First, fire up Visual Studio.

In this case, I’ll be using Microsoft Visual Web Developer Express 2010 (The FREE Version) with Service Pack 1 (SP!) Installed.

If you are JUST getting started, install VWD Express 2010 via the Microsoft Web Platform Installer. You can read full instructions HERE.

After starting the IDE create a new Web Site.

NOTE: if you are using Visual Studio Pro or above you won’t see “New Web Site” as an option on the start-up screen.

It’s OK – just select File->New Web Site

Then select the Default “ASP.NET Web Site” template.

Once VWD has created your new web site, use the Visual Studio Menu to select :

Tools –> Library Package Manager –> Add Library Package Reference

Read the rest of this entry »

Microsoft NuGet Package Manager for WebMatrix

Did you know that the latest version of Microsoft WebMatrix has an administrative user interface that includes a package manager which is browser based front end for NuGet ?

The default WebMatrix site template doesn’t include jQuery and since I’ve been doing a lot of jQuery content lately I thought it would be good to demonstrate the best way to include jQuery (as well as jQueryUI and any number of other libraries and resources you might use).

Start by launching WebMatrix and creating a a new web site using the Starter Site template.

Then run the site that you just created using the “Run” button in the WebMatrix IDE.

When you run the Default.cshtml page will be displayed. Note that the site is running on http://localhost and a dynamically assigned port number.

Replace Default.cshtml with “_Admin” and you will be redirected to this page.

This is a one-time-only security feature. You need to create a password file.

Enter the password of your choice (twice) and click “Create Password”.

On the next page READ the instructions.

They tell you that you need to rename a newly created file in your project.

In App_Data there is a newly created folder named “Admin”. If you don’t see it you may need to refresh the directory tree by right clicking on the root folder name and selecting the refresh option.

Delete the leading underscore from the “_Password.config” file and then go back to the browser that is running your website.

Enter the password you used in the previous step and click “Login”.

Now we can start to work with the package manager.

Read the rest of this entry »

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

Guest Post : Razor, Cascading Select Lists & jQuery Templates – A New Twist

Mike Brind (http://www.mikesdotnetting.com) had an interesting take on Ajax Cascading Drop Downs

I posted on the topic HERE and Mike emailed me his idea. I thought it was a great post and offered to repost it here as a guest post. Keep your eye on his blog.


jQuery Templates enable easy client-side generation of html. When combined with JSON data or other JavaScript objects, jQuery Templates provide a way to create a dynamic data-driven site without any server-side code whatsoever. However, in this article I will look at how they can be used to produce cascading select lists in a Razor Web Pages site.

jQuery Templates are an official jQuery plugin. That means that they are maintained as part of the jQuery Project. They are still in Beta at the moment, but will be included as part of the core jQuery library in the next major release, which will be jQuery 1.5. In much the same way as the WebMatrix WebGrid helper is used to generate html (in this case a

) on the server, jQuery Templates allow you to generate html using client side script. Where they differ from the WebGrid helper is that you can define the html that they generate. You are not restricted to outputting a
. On the other hand, they share a major similarity with the WebGrid helper. As part of the template you define, you can add binding expressions which act as placeholders for data. It’s probably a good idea at this point to have a look at a typical template.

Since I intend to illustrate cascading dropdown lists later, I’m going to re-use the data source I created for my original Cascading Dropdown Lists article from a couple of years ago. The data relates to cars, and each car has a number of properties:

  • Make
  • Model
  • Year
  • Colour
  • Number of Doors
  • Mileage
  • Price

A typical template for displaying cars might look like this:

The template appears in a

VIDEO – WebMatrix – Application State

Video Number 22 – Microsoft WebMatrix – Working with Applicaton State


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

Cascading DropDown with jQuery – WebMatrix Version

In this previous blog post I demonstrated implementing a Cascading Drop Down in ASP.NET WebForms using jQuery.

I had a couple of emails asking about the differences for using this technique in Microsoft WebMatrix so I thought I’d post a WebMatrix Version.

I also got a great email from Elijah Manor (@elijahmanor is an ASP.NET Insider & MVP) with some improvement suggestions.

Every code post on my blog finds someone out in web land who needs to tell me how they could write it better.

Elijah, however, is the Senior Architect at appendTo, THE jQuery company. I know really great developers that went to appendTo to learn jQuery training – hell I want to go take their jQuery Training.

Elijah is not only a really smart guy, he’s a really GOOD guy and emails not to show off but from a true desire to help – THANKS Elijah.

I’ve added some of Elijah’s suggested improvements and on his prompting will soon convert this code to my very first jQuery Plugin.

You’ll recall the Cascading Drop Down UI.


In the page template we’ll include a reference to the jQuery library.


        My ASP.NET Web Page - @Page.Title
        @RenderSection('header')

Note that , as Elijah suggests, I’m referencing the 1.5 (recent) version of the jQuery library via the Microsoft Content Delivery Network (CDN) Our WebMatrix page looks like this.

Read the rest of this entry »

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 »

VIDEO – WebMatrix – Debugging

Video Number 21 – Microsoft WebMatrix – Debugging


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

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 »

Silverlight Essentials Video Training

Creating a XAML Timer
Using Animations in XAML
Understanding Animations in XAML
Using Brushes
Understanding Brushes
Working with Text in XAML
Understanding Text in XAML
Walking Through a Silverlight Application
Using JavaScript Events in XAML
Understanding JavaScript Events in XAML
Using Transforms in XAML
Understanding Transforms in XAML
Clipping in XAML
Working with Paths in XAML
Using Vector Graphics in XAML
Understanding Vector Graphics in XAML
Adding Silverlight to a Web Page
Anatomy of a Silverlight Application
XAML and JavaScript Interaction
Exporting XAML from Adobe Illustrator CS3
Expression Encoder and Silverlight Integration
Expression Encoder Media Functionality
Installing Expression Encoder
Using Expression Blend to Create User Interfaces
Using Expression Blend
Installing Expression Blend
Using Expression Design
Installing Expression Design
Debugging with Visual Studio Pro
Getting Started with Visual Studio Pro
Introduction to Silverlight Tools and XAML
Walking Through the Example Projects
Using Silverlight Pad
Compelling Silverlight Examples
Installing Silverlight on a Mac
Installing Silverlight on a Windows Machine
Understanding the Various Versions
What is Silverlight?
Overview
Using the Exercise Files
Welcome
Connecting Duration and Position Text
Adding a Download Progress Indicator
Organizing XAML Assets
Goodbye
Updating Silverlight
Creating Drag-and-Drop Functionality
Creating Animations in a Timer Loop
Resizing the Application
Introduction to the Gravity Simulator
Adding Full-Screen Video Playback
Implementing Playback Progress Indicators
Implementing Audio Controls
Implementing Basic Playback Controls
Creating a Media Player
Introduction to Media Players
Working with Media and Images in JavaScript
Working with Media and Images in XAML
Understanding Media and Images in XAML
Understanding the XAML Workflow Between Tools
Creating a Button
Mouse Functionality in Silverlight
Understanding Mouse Input
Using Custom Fonts in Silverlight
Packaging in Silverlight
Using a Downloader
Downloading in JavaScript
Using Create from XAML
Understanding Create from XAML


Sorry this poll has closed.


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 ]


VIDEO – WebMatrix – Roles & Membership

Video Number 20 – Microsoft WebMatrix – Roles & Membership


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 WebForms Dynamically Selecting MasterPages

Last week I received an email from a developer in the UK who is building a web site with Microsoft WebMatrix and needed both “full browser” and mobile page experiences.

It’s possible to execute some logic at the beginning of the page load process and dynamicaly select and assign the template you want to apply, so I wrote THIS post.

I have subsequently recieved several email asking how to do the same thing in ASP.NET WebForms.

It’s a bit more difficult to do in WebForms due to the WebForms event lifecycle, but we can do it on a “per page” basis

As in the prior example, lets suppose that I want my page to look like this when the requesting user is running IE9.

And I want my pages to display as follows when the requesting user is running anything BUT Internet Explorer 9.

Note that in this case each MasterPage contains the same markup but refers to a seperate CSS file but you can implement MasterPages that are compleatly different.

To accomplish this we’ll add a OnPreInit event handler in each page that we want to implement this behavior.

To start, our page will not contain a MasterPage references since we’re going to assign one on the fly.


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

<asp:Content ID='HeaderContent' runat='server' 
             ContentPlaceHolderID='HeadContent'>
</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>
</asp:Content>

Then in the page’s code-behind file we simple implement the fololowing OnPreInit() event handler.


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

    protected override void OnPreInit(EventArgs e)
    {
        base.OnPreInit(e);
        string mystr = Request.Browser.Type;
        if (mystr == 'IE9')
        {
            this.MasterPageFile = '~/Normal.master';
        }
        else
        {
            this.MasterPageFile = '~/Antique.master';
        }  
    } 

}

There you go !!


VIDEO – WebMatrix – Improve Performance with Caching

Video Number 19 – Microsoft WebMatrix – Improve Performance with Caching


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

Dynamically Selecting WebMatrix Page Layouts & Styles

I received an email from a developer in the UK this week who is building a web site with Microsoft WebMatrix and needs both “full browser” and mobile page experiences.

It’s possible to execute some logic at the beginning of the page load process and dynamicaly select and assign the template you want to apply.

Lets suppose that I want my page to look like this when the requesting user is running IE9.

And I want my pages to display as follows when the requesting user is running anything BUT Internet Explorer 9.

Note that in this case each template contains the same markup but refers to a seperate CSS file but you can implement templates that are compleatly different.

To accomplish this we’ll create and use a file named _PageStart.cshtml

Though the default website template does not contain a _PageStart.cshtml the runtime will process this file at the brginnign of the page load process if it exists.

After creating a web site from the Stater Site project in WebMatrix I’ve added a _PageStart.cshtml page and coded the following.


@{
    if (Request.Browser.Type == 'IE9')
    {
        Layout = '~/_SiteLayout.cshtml';
    }
    else
    {
        Layout = '~/_OtherLayout.cshtml';
    }
}

This code executes some conditional logic (in this case testing to see if the requesting browser is IE9) and then assigns the correct layout.

In the actual .cshtml pages I modify the code at the top of each page so that it looks like this.


@* ~/_PageStart.cshtml *@
@{
    Page.Title = 'Welcome to my Web Site!';
}
<p>
    ASP.NET Web Pages make it easy to build powerful .NET 
	based applications for the web.
    @Request.Browser.Type
</p>

The “logic” in this demo is just different lawyouts for different browsers.

If we wanted to render al alternate template for Mobile visitors we could change our _PageStart.cshtml to look like this.

@{
    if (Request.Browser.IsMobileDevice) 
    {
        Layout = '~/_SiteLayout.cshtml';
    }
    else
    {
        Layout = '~/_OtherLayout.cshtml';
    }
}

You can download a sample project HERE


WPF Developer Training Videos (108)

  1. Create WPF Master – Detail UI Using Data Sources Window Object DataSource
  2. Layout Techniques for Windows Forms Developers
  3. Grid Control Design-Time Row and Column Manipulation Features
  4. Creating and Consuming Resource Dictionaries in WPF and Silverlight
  5. How Do I: Build My First WPF Application
  6. How Do I: Setting and Clearing Validation Errors in code
  7. How Do I: Build Data-driven WPF Application using the MVVM pattern
  8. How Do I: Use TargetNullValue to Handle Nullable Types in WPF Binding
  9. How Do I: Using StringFormat when Multibinding
  10. How Do I: Use FallbackValue in WPF Binding
  11. Windows 7 Sensor and Location API Part 2 – Accelerometer as a Joystick
  12. How Do I: Implement Windows 7 Taskbar Icon Overlays with WPF 4
  13. How Do I: Use Windows 7 Text-to-Speech from .NET 4 and WPF
  14. How Do I: Change the Appearance of Grouped Data Using Styles
  15. How Do I: Apply Textures to a 3D object
  16. How Do I: WinForms WPF Integration
  17. How Do I: Use Resource Files for Localization both in XAML and Code
  18. How do I: Use Windows 7 Taskbar Progress Reporting from WPF 4
  19. How Do I: Create Custom Pixel Shader Effects for WPF
  20. How Do I: Work with Lighting in WPF 3D
  21. How Do I: Get Started with 3D Elements in WPF
  22. How Do I: Use ASP.NET Membership Provider for WPF Authentication
  23. How Do I: Use a WPF Control in a Windows Form using ElementHost
  24. How Do I: Create a Custom Command in WPF
  25. How Do I: Custom Easing Functions in WPF 4
  26. Introduction to Easing Functions in WPF 4
  27. Introducing the WPF 4 Calendar Control
  28. How Do I: Use Command Binding in WPF
  29. How Do I: Use CollectionViews to Sort and Filter Data
  30. How Do I: Control Item Activation By Data Validation?
  31. How Do I: Animate an Effect in WPF?
  32. Building a Client Profile Deployment for photoSuru
  33. How Do I: Visually Indicate Binding Error Status
  34. How Do I: Create a Custom Binding Validator
  35. How Do I: Associate a Validation Rule with a Binding
  36. How Do I: Add Design Time Data to a Control
  37. How Do I: Detect Designmode in a Usercontrol
  38. How Do I: Use Effects in WPF
  39. Control How Data is Updated Using Binding Direction
  40. Using Alternating Rows in an ItemsControl
  41. Control When Bound Data is Updated
  42. Working With Context Menus in WPF
  43. How Do I: Use the WebBrowser Control in WPF
  44. Adding Annotations to Flow Documents
  45. How Do I: Create a Splash Screen in WPF
  46. How Do I: Create a Simple WPF DataGrid to Edit Tabular Data
  47. How Do I: Create a Master-Detail Data Entry Form in WPF
  48. How to Use Styles in WPF
  49. How to Create a User Control in WPF
  50. How to Create a WPF Application
  51. How to Apply Control Templates in WPF
  52. How to Consume a Data Service in WPF
  53. How to Use Data Templates in WPF
  54. How to Layout a WPF Application
  55. How to Use XAML in WPF
  56. Control Video Playback in WPF
  57. Build a Custom GridLength Animation
  58. How Do I: Create a Dynamic Storyboard in WPF
  59. How Do I: Build an Asynchronous Progress Bar in WPF
  60. How Do I: Use Video in WPF Applications
  61. How Do I: Paint with Video in WPF
  62. How Do I: Hook Up and Display Validation in WPF
  63. How Do I: Create Lookup Combobox in WPF
  64. Responding to Events with SoundPlayerAction
  65. How Do I: Add Sound to a WPF Application
  66. How Do I: Display Data in a List in WPF
  67. How Do I: Create a Simple Data Entry Form in WPF
  68. How Do I: Use ResourceDictionary Elements Exported from Expression Design 2
  69. Extend Control Functionality Using XAML Attached Properties
  70. How Do I: Use Attached Properties to Store Extra Data in WPF
  71. How Do I: Define and Use Namespaces in WPF
  72. How Do I: Customize the Appearance of a ListBox in WPF
  73. How Do I: Customize the Appearance of ListBox ListItems in WPF
  74. How Do I: Create and Use a Converter to Change DataTypes
  75. How Do I: Build a ValueConverter to Format Bound Data in WPF
  76. How Do I: Use PointAnimation to Animate a Path in WPF
  77. How Do I: Retrieve XML Data From the Server in an XBAP Application
  78. How Do I: Using Path Markup Language to Define a Path
  79. Create Dependency Properties in WPF
  80. Use PathGeometries in WPF
  81. Ink Basics in WPF
  82. Confine Animation to a Path
  83. Skinning a WPF Application
  84. Use a Control Template to Define a Desired Look
  85. Create User Controls in WPF
  86. Sharing Styles Among Heterogeneous Elements
  87. Override a Style for a Local Control’s Property Value in WPF
  88. Host a WPF Control in a Win32 Application
  89. Interactivity Through Triggers in WPF Control Templates
  90. Kerning XAML Animations in WPF
  91. Implementing Data Triggers in WPF
  92. Complex Logic Using Triggers in WPF
  93. Basic Animation in WPF Using XAML
  94. Introduction to Themes in WPF
  95. Implementing Property Triggers in WPF
  96. Style Inheritance using BasedOn in WPF
  97. Apply Styles in WPF
  98. Deploying a Standard WPF Application Using ClickOnce and Visual Studio
  99. Create and Browse Loose XAML Files
  100. Use the Page Functions to Retrieve Data and Pass it Back to a Previous Page
  101. Passing Data Between Pages In Navigation Based Applications
  102. WPF Navigation Application
  103. Create Gadget Style Windows in WPF
  104. Accessing Command Line Parameters
  105. How to Use Isolated Storage
  106. Build a Standard WPF Application
  107. Creating Navigation Applications in WPF
  108. Reflections in Visual Studio and Blend

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 !


VIDEO – WebMatrix – Add Traffic Analysis to your site

Video Number 18 – Microsoft WebMatrix – Add Social Networking Features to your Site


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

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 ]

VIDEO – WebMatrix – Add Social Networking Features to a Site

Video Number 17 – Microsoft WebMatrix – Add Social Networking Features to your Site


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

HTML5 versus Silverlight–Is Silverlight Dead?

In a world NO, NO, NO !

I got this email from a developer that I have corresponded with for several years.

I know this guy to be smart and experienced, so this is not a “newbie” question but rather an example of how difficult it is to understand the new technology that is constantly emerging in the software development industry and what they mean for our future work and choices.

From:

Sent: Friday, February 18, 2011 12:00 PM

To: Joe Stagner

Subject: Html 5 causing Silverlight Dev to End?

Joe,

I heard from someone that Html 5 is eliminating the need for Silverlight, such that Silverlight development might stop. Any truth to this???

Phil

In the interest of transparency, I don’t work in in the Silverlight team. I’m not even the Silverlight guy on my team, but I am a technical strategist and have been developing web applications since before Windows even had a TCP/IP stack !

What follows is MY opinion and may not exactly “jive” with Microsoft Official position.

> Note to Tim Heuer, Hey old buddy – I’m sure you’ll email me if I’m WAY off base Smile 

HTML5 is interesting – period.

I’m building developer guidance right now using HTML5, but HTML5 is NOT a Silver Bullet.

Certainly there are some scenarios for which HTML5 feature will displace the need for a RIA type plugin like Silverlight.

In most cases though, I don’t think this is true.

What HTML can “do” – Silverlight can do really well !

In my humble opinion,  I’m not sure that we (Microsoft) have done a great job demonstrating the high end of what can be done with Silverlight. The more advanced the application scenario, the more Silverlight excels.

Late last year there was a lot of noise on the web suggesting that Microsoft was disinvesting in Silverlight.

I know it’s hard to believe, but everything you read on the internet is not necessarily true Smile 

So, what are some of the scenarios that I personally would require Silverlight.

Audio / Video

Yes, I know, you can play video with HTML5, welcome to the 1990s Smile 

I need to do MUCH MORE than just “play” video.

Example: Completely separate from my job at Microsoft I create training and educational video for athletes. I want offer that video on a web site but don’t want that video to be swiped, edited, copied, etc all over the web.

HTML5 does not support DRM or other media related security initiatives so remove most of the media produced by the Movie, Television, and Training Industries from use with HTML5 (as well as mine.)

What’s more, I need to do A LOT MORE then just play video. I want to record usage data, allow user annotations, insert context specific ads, links, etc, and much more which means I WANT a custom player that can make my user’s video experience ROACK.

Performance

Historically, most browser applications are really single tier. All the executable logic runs on the server and the browser just displays the results.

We’re finally starting to catch up and architect web applications with “Federated Logic”.

It only makes sense. Lets run as much code as we safely can in the browser so as to off load the required processing power from our servers to the clients computer.

HTML5’s facility to enable this is present, but inferior.

True, JavaScript execution has been a point of focus in HTML5 compliant browser implementations and HTML5 has “Web Worker” Processes. (It’s acually a seperate spec – http://www.w3.org/TR/workers/)

Web Workers, in particular, are very interesting but require certain restrictions in terms of interacting with the User Interface. This is another example of how HTML with fit well in certain scenarios and not others.

There is also the issue of source code protection which is virtually impossible in JavaScript.

Communications

HTML WebSockets was my favorite feature. Unfortunately it looks like WebSockets won’t make it into the final HTML5 specification. In fact – it’s a whole different spec http://dev.w3.org/html5/websockets/. That means it’s implementation may vary from browser to browser if it gets implemented at all.

Silverlight has a complete network stack today and it works in all the most popular browser currently in use. 

Off Line

HTML5 has Off-Line application considerations.

An offline application cache and local storage will suffice for some applications but if you think about such usage scenarios a little further things start to get more complex.

For example, if our application implements a rich user interface using AJAX techniques, as users today expect, what happen to those interactions when the user is off line. Can you really just “turn them off”, or do you need to provide a set of disconnected logic?

We might be ale to do this, but if our application will be use significantly off line (as well as on) Silverlight offers significant advantages. (If you haven’t toured Silverlight recently Silverlight now has a strong Out-Of-Browser capability (meaning run as a desktop app, no browser involved) .

Touch / Multi Touch Interfaces

User interaction continues to evolve and Computers, Tables, and Dedicated devices often lend themselves to Touch or Multi-Touch User Interfaces. Lets plan ahead, shal we?

WebCam / Microphone

Tack specific applications, social networking, etc. ?????  Cool.

And More.

Work with Ink? call the Operating System’s API ? Silverlight.

And lest we forget. Silverlight is THE applications development model for Windows Phone 7 applications (though if you’re building games you may be using XNA)

Windows Phone 7 is enjoying rapid success and growth. Not only does that alone insure the continued evolution of Silverlight, but the ability to share code between your Phone, Browser and Desktop Applications.

So no Phil….

HTML5 will enjoy enthusiastic adoption but will not eliminate Silverlight. In fact, as HTML5 helps us push the edges of web applications design and architecture, the opposite might be true. We may find ourselves envisioning more and more functionality for which Silverlight is the ideal enabler.

del.icio.us Tags: ,

VIDEO – WebMatrix – Add Search to your Site with Bing

Video Number 16 – Microsoft WebMatrix – Adding Search to your site with Bing


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 AJAX Videos & Tutorials (155)

ASP.NET AJAX Videos


Introduction to ASP.NET Ajax History
Use Script Combining to Improve Performance
Get Started with ASP.NET AJAX
Implement Dynamic Partial-Page Updates with ASP.NET AJAX
Make Client-Side Network Callbacks with ASP.NET AJAX
Add ASP.NET AJAX Features to an Existing App
ASP.NET AJAX Enable an Existing Web Service
Use the ASP.NET AJAX Client Library Controls
Use an ASP.NET AJAX ScriptManagerProxy
Use the RoundedCorners Extender
Use the ASP.NET AJAX Timer Control
Implement the Predictive Fetch Pattern for AJAX
Implement the AJAX Paging Pattern
Implement the Incremental Page Display Pattern
Incremental Page Display Pattern (GET and POST)
Use the UpdateProgress Control
Use the ASP.NET AJAX History Control
Implement the AJAX After Processing Pattern
Update Multiple Regions of a Page with ASP.NET AJAX
Choose Between Methods of AJAX Page Updates
Use Other JavaScript UI Libraries with ASP.NET AJAX
Use the ASP.NET AJAX Profile Services
Debug ASP.NET AJAX Applications Using Visual Studio 2005
Customize Error Handling for the UpdatePanel
Use ASP.NET AJAX Client Templates
Build a Custom ASP.NET AJAX Server Control
Use JavaScript to Refresh an ASP.NET AJAX UpdatePanel
Determine an Asynchronous Postback
Use the Conditional UpdateMode of the UpdatePanel
Persistent Comm Pattern (UpdatePanel)
Localize an ASP.NET AJAX Application
Persistent Comm Pattern (Web Services)
Trigger an UpdatePanel Refresh from a DropDownList
Create an ASP.NET AJAX Extender from Scratch
Custom Server Controls that Work With/Without AJAX
Associate AJAX Client Behavior with a Server Control
Retrieve Values From Server Side AJAX Controls
Techniques for Triggering Updates to Update Panels
Use Cascading Drop Down Control to Access a Database
Implement Infinite Data Patterns in AJAX
Basic ASP.NET Auth in an AJAX Enabled App
Dynamically Change CSS Using the UpdatePanel
Dynamically Add Controls to a Web Page
Set Up Your Development Environment for ASP.NET 3.5
Set Up Your Development Environment for ASP.NET 2.0
Partial Page Updates
UpdatePanel Triggers
Authentication & Profile Application Services
Localization
Web Services
Debugging Capabilities

Read the rest of this entry »

Really Simple AJAX Calls with Microsoft WebMatrix

Modern web pages don’t have to post back to change their presentation to the user.
There are many ways to implement these types of features and ASP.NET Web Pages with Microsoft WebMatrix is no different. 

An AJAX callable service can return results in amy different formats, JSON, POX, Encoded Binary, etc. 

In the case below we’ll implement a “service” in a .CSHTML page and it will return a snippet of HTML markup. 

The calling page looks like this.


@{
Layout = '~/_SiteLayout.cshtml';
Page.Title = 'Welcome to my Web Site!';
}

<br /><br />
<div id='TextDiv'>
    ASP.NET Web Pages make it easy to build powerful .NET 
    based applications for the web.
</div>

<p>
<input id='TextInput' type='text' />
<br /><br />
<button id='mybutton'>Make an AJAX request .... </button>
<script type='text/javascript'>
   function show(indata)
    {
    TextDiv.innerHTML = indata;
    }
</script>
<script type='text/javascript' src='xmlhttp.js'></script>
<script type='text/javascript'>
  document.getElementById('mybutton').onclick = function () {
        var d = document.getElementById('TextInput');
        doHttpRequest('Service.cshtml?' + d.value, show);
  }
</script>
</p>

You’ll note that this is a modified version of the Default.cshtml page from the default WebMatrix Starter Site Template.

Line 21 Includes a JavaScript file which contains the plumbing to make an HTTP request from our client side code.

On line 23 we wire a handler for the HTML button’s click event.

On line 24 we get a reference to the text input field where we will retrieve data to send to our service.

Then line 25 calls a JavaScript function doHttpRequest() wich is defined in xmlhttp.js

doHttpRequest(‘Service.cshtml?’ + d.value, show);

Note the two arguments.

  1. “Service.cshtml” is the endpoint to be called. In this case, a simple WebMatrix page (and a QueryString Argument)
  2. A callback function (in our case defined beginning at line 16)

Lets take a look at xmlhttp.js


function doHttpRequest(url, callback_function, return_xml)
{
  var http_request, response, i;

  var activex_ids = [
    'MSXML2.XMLHTTP.3.0',
    'MSXML2.XMLHTTP',
    'Microsoft.XMLHTTP'
  ];

  if (window.XMLHttpRequest)
  {
    // Internet Explorer 7 or greater, Mozilla, Safari, etc.
    http_request = new XMLHttpRequest();
    if (http_request.overrideMimeType)
       {
       http_request.overrideMimeType('text/xml');
       }
   }
   else if (window.ActiveXObject)
   {
    // IE6 and below
    for (i = 0; i &lt; activex_ids.length; i++)
    {
      try
      {
        http_request = new ActiveXObject(activex_ids[i]);
      }
      catch (e)
      {
      // Add error handling here.
      }
    }
  }

  if (!http_request) {
    alert('Current browser does not support http requests.');
    return false;
  }

  http_request.onreadystatechange = function()
  {
    if (http_request.readyState !== 4)
    {
        // Response not ready.
        return;
    }

    if (http_request.status !== 200)
    {
      // Repsponse ready, but not [200] OK
      alert('The request resulted in an error. 
           (Code: ' + http_request.status + ')');
      return;
    }

    if (return_xml)
    {
      response = http_request.responseXML;
    }
    else
    {
      response = http_request.responseText;
    }
    // Do Callback
    callback_function(response);
  };

  http_request.open('GET', url, true);
  http_request.send(null);
}

The bulk of the code is plumbing and error handling, making sure we can create the XmlHttpRequest object, which requres a dufferent methodology depending on which browser the code is running in.

In future demos I’ll relly on jQuery for AJAX service calls. Among other advantages, jQuery handles browser differences for us.

The service itself is a sample page I’ll name Service.cshtml

It looks like this:



@{
    var MyOutPut = "";
    if(Request.QueryString[0] != "")
    {
        MyOutPut = Request.QueryString[0] + " Data Recieved";
    }

    @MyOutPut
    @:<strong> >>>>>>> &amp;nbsp;  @DateTime.Now   </strong>
}

Note that, unlike the rest of the pages in our site, this one does NOT use a layout inclusion, nor does it specify a doc tgype, etc.

It doesn’t actually return a page at all but rather a simple, but dynamic, bit of HTML markup.

While there are many more complex ways for code in the browser with code on the server, often that complecity isn’t necessary.

This simple method will get you providing dynamic page updates to you ASP.NET WebMatrix Web Pages.

[ Download a working sample HERE ]


ASP.NET Data Access Tutorials & Videos (114)

Data Access Tutorials


Creating a Data Access Layer
Creating a Business Logic Layer
Master Pages and Site Navigation
Displaying Data With the ObjectDataSource
Declarative Parameters
Programmatically Setting the ObjectDataSource’s Parameter Values
Master/Detail Filtering With a DropDownList
Master/Detail Filtering With Two DropDownLists
Master/Detail Filtering Across Two Pages
Master/Detail Using a Selectable Master GridView
Custom Formatting Based Upon Data
Using TemplateFields in the GridView Control
Using TemplateFields in the DetailsView Control
Using the FormView’s Templates
Displaying Summary Information in the GridView’s Footer
An Overview of Inserting, Updating, and Deleting Data
Inserting, Updating, and Deleting Events
Handling BLL- and DAL-Level Exceptions in an ASP.NET Page
Adding Validation Controls to the Interfaces
Customizing the Data Modification Interface
Implementing Optimistic Concurrency
Adding Client-Side Confirmation When Deleting
Limiting Data Modification Per User
Paging and Sorting Report Data
Efficiently Paging Through Large Amounts of Data
Sorting Custom Paged Data
Creating a Customized Sorting User Interface
Adding and Responding to Buttons to a GridView
Displaying Data with the DataList and Repeater Controls
Formatting the DataList and Repeater
Showing Multiple Records per Row with the DataList
Nested Data Web Controls
Master/Detail Filtering With a DropDownList
Master/Detail Filtering Across Two Pages
Master/Detail Using a Bulleted List of Master Records
An Overview of Editing and Deleting Data in the DataList
Performing Batch Updates
Handling BLL- and DAL-Level Exceptions
Adding Validation to the DataList’s Editing Interface
Customizing the DataList’s Editing Interface
Implementing Optimistic Concurrency
Adding Client-Side Confirmation When Deleting
Limiting Data Modification Per User
Paging Report Data in a DataList or Repeater Control
Sorting Data in a DataList or Repeater Control
Custom Buttons in the DataList and Repeater
Querying Data with the SqlDataSource Control
Using Parameterized Queries with the SqlDataSource
Inserting, Updating, & Deleting with the SqlDataSource
Optimistic Concurrency with the SqlDataSource Read the rest of this entry »

VIDEO – WebMatrix – Sending Mail

Video Number 15 – Microsoft WebMatrix – Sending Mail


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

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.

VIDEO – WebMatrix – Working with Video

Video Number 14 – Microsoft WebMatrix – Working with Video.

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 WebForms Related Videos (154)

Tailspin Spyworks – Intro UI and EDM

Tailspin Spyworks – Directory Organization

Tailspin Spyworks – Category Menu

Tailspin Spyworks – Display the Product List

Tailspin Spyworks – Display Per Product Details

Tailspin Spyworks – Adding Items to the Shopping Cart

Tailspin Spyworks – Display Shopping Cart

Tailspin Spyworks – Update the Shopping Cart

Tailspin Spyworks – Migrate the Shopping Cart

Tailspin Spyworks – Final Check Out

Tailspin Spyworks – Adding User Product Reviews

Tailspin Spyworks – Displaying User Reviews

Tailspin Spyworks – Creating and Using the Popular Products Control

Tailspin Spyworks – Implementing and Using the Also Purchased Control

Intro to Visual Web Developer

Intellisense

Intro to Web Forms

Page Layout

Page Lifecycle Events

Intro to ASP.NET Controls

Submit and Postback

Application Level Objects

Session Level Objects

Debugging

CSS

Master Pages

Intro to SOAP Based Web Services

AJAX Style Services

Validation

Login Controls

Creating a Site-Wide Layout Using Master Pages

Multiple ContentPlaceHolders and Default Content

Specifying the Title, Meta Tags, and Other HTML Headers in the Master Page

URLs in Master Pages

Control ID Naming in Content Pages

Interacting with the Master Page from the Content Page

Interacting with the Content Page from the Master Page

Master Pages and ASP.NET AJAX

Specifying the Master Page Programmatically

Nested Master Pages

ASP.NET AJAX Support in Visual Studio 2008

The ListView Control

The DataPager Control

Visual Studio 2008 and Nested Masterpages

New Designer Support in Visual Studio 2008

JavaScript Intellisense Support in Visual Studio 2008

JavaScript Debugging in Visual Studio 2008

Multi Targeting Support in Visual Studio 2008

IntelliSense for Jscript and ASP.NET AJAX

Quick Tour of the Visual Studio 2008 IDE

Creating and Modifying a CSS File

Adding AJAX Functionality to an Existing Page

Creating and Using an AJAX-Enabled Web Service

Create a Master Page in Visual Studio 2008

Create Nested Master Page in Visual Studio 2008

Cascading Style Sheets in Visual Studio 2008

Working with Visual Studio 2008 .NET Framework

Adding Elements to a CSS File and Create New CSS on the Fly

Advance Cascading Style Sheet Features and Management

Converting a .NET 2.0 Windows Forms App to .NET 3.5

Get Started with the Entity Framework

Read the rest of this entry »

The Visual Studio SP1 Razor experience for WebMatrix Pages

Ya, I know. The name is confusing.

WebMatrix is technically the IDE and the”page model” is technically called “ASP.NET Web Pages”.

I call the whole “stack” Microsoft WebMatrix (The IDE, IIS Express, SQL Compact, and ASP.NET Web Pages/Razor)

The WebMatrix stack was an independent, out-of-band release.

Visual Studio 2010 SP1 (in Beta as of this writing) has some really exciting stuff in it (at least for this geek.)

For those of us that are doing HTML5 work, get excited about the enhanced HTML syntax support.

But if you’re doing WebMatrix work as I am, SP1 brings Visual Studio up to speed for us (cshtml and vbhtml support.)

The WebMatrix tool come with a built-in “Open in Visual Studio” button.

If you have Visual Studio installed on your machine clicking this button will open up Visual Studio 2010 and pass your WebMatrix project context to Visual Studio but since Visual Studio 2010 was released before WebMatrix, you couldn’t do much with .cshtml or .vbhtml files.

  

SP1 for VS 2010 makes the Side-By-Side experience ROCK !

Click on the Launch in Visual Studio Button and open a page in VS.

Of course we get the kind of stuff we get in the WebMatrix Tool like Razor Syntax Highlighting.

We also get comfortable and familiar stuff like IntelliSense.

Read the rest of this entry »

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 ]

VIDEO – WebMatrix – Working with Images

Video Number 13 – Microsoft WebMatrix – Working with Images.

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

VIDEO – WebMatrix – Working with Files and File IO

Video Number 12 – Microsoft WebMatrix – Working with Files and File IO.

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

VIDEO – WebMatrix – Data Visualization with the Chart Helper

Video Number 11 – Microsoft WebMatrix – Data Visualization with the Chart Helper.

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

VIDEO – WebMatrix – Charts and the Chart Helper

Video Number 10 – Microsoft WebMatrix – Charts and the Chart Helper.

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

VIDEO – WebMatrix – Data Grids and the WebGrid Helper

Video Number 9 – Microsoft WebMatrix Data Grids and the WebGrid Helper.

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

VIDEO – Microsoft WebMatrix – Database Inserts

Video Number 8 – Inserting Records into a Database with Microsoft WebMatrix  and the Razor Syntax.

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

VIDEO – Microsoft WebMatrix – The IDE DataBase Tools

Video Number 7 – Working with the Microsoft WebMatrix The IDE DataBase Tools.

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
WMV File
WMV

VIDEO – Microsoft WebMatrix – Form Field Validation

In video number 6 in this Microsoft WebMatrix Series implement form field validation in ASP.NET Web Pages.

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
WMV File
WMV

VIDEO – Microsoft WebMatrix – Working with Forms

In video number 5 in this Microsoft WebMatrix Series we start working with forms in ASP.NET Web Pages and the  Razor Syntax.

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

VIDEO – Microsoft WebMatrix – Page Specific Styling

In video number 4 in this Microsoft WebMatrix Series we impliment Page Specific Styling with ASP.NET Web Pages and the  Razor Syntax.

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

BOOK–Murach’s PHP & MySQL

Yep! Another great Murach’s book.

This book is the quintessential learning resource for PHP development.

Like all of Murach’s books, it teaches far more then the nuts and bolts of the technology but also what the right ways to use them are.

The book is up to date with PHP 5.3 and takes you through getting the PHP Stack set up (Windows or Mac)

It quickly covers foundational requirements like HTML, CSS, and HTTP and then jumps into how to write and debug PHP code.

It not only covers the breadth of detail about web programming specifics with PHP, like cookies, images, uploads, etc. but also provides great higher level guidance.

There are sections on often overlooked topics for new PHP developers like Object Oriented Programming and using the MVC pattern in PHP.

As I often say about Murach’s books – if I were teaching a course on PHP development, this is the book I would teach the course from. Not only a great learning / training resource, but once you’ve read it, it becomes a great desk reference.

Calling .NET Framework Classes from WebMatrix

I got an email this afternoon from someone who is coming up to speed with WebMatrix and needed some functionality that they couldn’t find in any of the helpers in the gallery.

It is easy to forget that ALL OF .NET is still there at our disposal when programming with WebMatrix / ASP.NET Web Pages.

Using functionality that exists in the .NET Framework is easy.

All we need to do is pull in a name space just like we would in any other ASP.NET page.

Suppose we want to use the Regular Expression classes from .NET.

First, at the top of a .cshtml page we place a “using” statement and specify the name-space that we want to access.

 @using System.Text.RegularExpressions;
    @{  
        Layout = "~/Shared/_SiteLayout.cshtml";
        Page.Title = "We Look Forward to Hearing from you!";
    }

Then we can create a .NET “Regex” object passing in the expression that we want to validate against and then call the “IsMatch” method 

 var isValidEmail = true;
   var pattern = @"^[a-zA-Z][\w\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*
                                    [a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$";
   var regExp = new Regex(pattern);
   isValidEmail = regExp.IsMatch(contactemail);
   if(isValidEmail == false)
     {
     validationerrors = true;
     @:ERROR : "Contact Email" Is Required - 
                You must enter a VALID Email Address.<br />   
     }

I’ll be building a sample application using WebMatrix and implementing a number of features that use the .NET framework, but this sample should illustrate how easy is is to get under the WebMatrix covers to .NET !

RIAStats.com

Check out this cool site that tracks RIA Plugin Adoption

RIAStats-1-26-2011 8-56-53 AM

VIDEO – Microsoft WebMatrix – Templating Features

In video number 3 in this Microsoft WebMatrix Series we review the features in WebMatrix that  help up with markup reuse to create “templates” for our pages and achieve a consistent look and field.

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

VIDEO – Microsoft WebMatrix – Razor Syntax

In video number 2 in this Microsoft WebMatrix Series we tour the elegant simplicity of the ASP.NET Web Pages Razor Syntax.

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

VIDEO SERIES – Microsoft WebMatrix

By now you MUST have heard about Microsoft new Page Oriented Web Stack !

I’ve been having a blast with it and am launching a video series to help folks get up to speed.

The first 15 or so videos will follow the written chapters [ HERE ].

The first video is a look at WHAT WebMatrix is and where it fits in.

Get the Video (or Audio) file of your choice below.

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

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,

Podcast #1 – Glenn Block on WCF

Due to popular demand I’m beginning podcasting again under the MSJoe.com “brand”.

No intro music, etc. just geek talk.

I’m very pleased to have Glenn Block for my first guest.

Glenn is one of those super smart, exuberant, enthusiastic guys here at Microsoft that takes on tough problems and digs for great useful solutions.

Glenn and I spend some time review his previous work at Microsoft and then focus on the new work he’s doing with WCF, his focus on REST and usage scenarios that modern web developers care about.

RESOURCES  

 Listen

 Subscribe


   MP3

   WMA

   M4A

   Zune

   iPod

 Download


   MP3

   WMA

   M4A

   Zune

   iPod

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.

clip_image002

You’re invited to a special Silverlight event on December 2nd, 2010

Learn about the future of Silverlight from Corporate Vice President, Scott Guthrie and other experts, direct from Microsoft’s HQ.

Hear about our plans for the next version of Silverlight, the latest developments as well as in-depth sessions on building applications with Silverlight.

Registration is free – take part in-person or online.

Find out more and Register online

Getting ready to move to a jQuery / WCF based AJAX model.

Over the past several years I’ve developed lots of guidance for ASP.NET Developers adding AJAX functionality to their web applications. [ See HERE ]

Most of that guidance has been primarily for Web Forms developers using The Microsoft AJAX Library and the AJAX Control Toolkit.

While those tools are still perfectly viable choices, I’ve added ASP.NET MVC and ASP.NET Web Matrix to the web development work that I do and the above choices are Web Forms centric.

Even in my “Web Forms” applications, I’m using fewer Server Controls in favor of client side User Interface implementations (like jQueryUI and YUI).

Though this is a very different approach than using Server Controls and is usually a bit more coding, it offers the advantages of very detailed control over the aesthetics and behaviors of my browser based UI and it allows me to reuse my client code across Web Forms, ASP.NET MVC, and WebMatrix.

In addition to evolving the client side implementation of my AJAX work, I’m going to be moving from ASMX for services to WCF.

[ Note: I’m going to be doing many videos and tutorials using this model over the coming months. ]

ASMX works fine, but there are many advantages to WCF.

I’ll be blogging specifically about the reasons I’m migrating to WCF in a near future blog post but in the meantime I wanted to introduce you to a CodePlex project that I will be using going forward.

The stiff is being built by the .NET Developer Platform Team so the work here will be reflected in the .NET Stack in the future.

Check them out here – http://wcf.codeplex.com/

Application

WCF Support for jQuery 10.10.27WCF Support for jQuery – create WCF web services that are easy to consume from JavaScript clients, in particular jQuery.

Source Code

WEB HTTP Preview 1.zip – WCF HTTP – create HTTP / REST based web services.

And stay tuned……….

 

Technorati Tags: ,,,

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 quick list of resources Developers using IIS

Overview – http://www.iis.net/overview

Feature Training – http://learn.iis.net/ 

IIS 7 Operations Guide – http://technet.microsoft.com/en-us/library/cc732976(WS.10).aspx

Docs – http://technet.microsoft.com/en-us/library/cc753433(WS.10).aspx

Accessing Online Help – http://technet.microsoft.com/en-us/library/cc725788(WS.10).aspx

ASP.Net & PHP Support   http://www.iis.net/overview/ASP.NETandPHPSupport

Building and Running ASP.NET Applications – http://learn.iis.net/page.aspx/23/building-and-running-aspnet-applications/

Planning Your IIS 7 Architecture  http://learn.iis.net/page.aspx/38/planning-your-iis-7-architecture/

IIS7.x configuration reference is here http://www.iis.net/ConfigReference

Achieving High Availability and Scalability – ARR and NLB – http://learn.iis.net/page.aspx/511/achieving-high-availability-and-scalability—arr-and-nlb/

 

Thanks to Zoher Bharmal (Support Engineer IIS/ASP.NET) for this list.

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.

Updating AJAX Patterns How-Do-I Videos.

Below is a list of AJAX Patterns videos that I did some time back.

Implement the Predictive Fetch Pattern for AJAX

25 minutes

Implement the AJAX Paging Pattern

27 minutes

Implement the Incremental Page Display Pattern

12 minutes

Incremental Page Display Pattern (GET and POST)

20 minutes

Implement the AJAX After Processing Pattern

6 minutes

Persistent Comm Pattern (UpdatePanel)

12 minutes

Persistent Comm Pattern (Web Services)

17 minutes

Implement Infinite Data Patterns in AJAX

19 minutes

These videos all rely on Microsoft ASP.NET AJAX and, in some cases the AJAX Control Toolkit

More and more we are moving to a jQuery centric model of development where JavaScript work is concerned and so I think it’s a good idea for me to revisit these patterns with a focus on implementation using jQuery.

Can you list some other AJAX “Patterns” that I should add to the collection ?

THANKS !

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

ASP.NET – WebMatrix chapters 4-6 videos are now live

#4 | Working with Forms – 18 minutes

#5 | Working with Data – 27 minutes

#6 | Working with Files – 22 minutes

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>

Learning Microsoft WebMatrix – Chapter 3 Video Live.

Enjoy !

Video: http://www.asp.net/webmatrix/videos/creating-a-consistent-look

Tutorial: http://www.asp.net/webmatrix/tutorials/3-creating-a-consistent-look

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 = "~/";
  85:                  }
  86:                  Response.Redirect(continueUrl);
  87:              }
  88:   
  89:          }
  90:      }
  91:   
  92:  }

Technorati Tags: ,,,

Sometimes you need to dig in a little to get things to work the way that you want.

I’m working on an events calendar and I need specific behavior for the home page display.

When the page initially renders, I want to display a list of events in the current month.

Then, I want to modify the display based on the user’s interaction.

  • If the user picks a date then I want to display only the events on that day.
  • If the user navigates to a different month I want to display the events for that month, even if they previously choose a specific day.

To do this I need to do the equivalent of a SQL SELECT based on EITHER the Day or the Month depending on the users choices.

7-2-2010 8-40-19 AM

The code for this was easy but figuring out exactly what to do in relation to the controls behavior took a few minutes to straighten out.

The Calendar Control has a SelectedDate property but until a user chooses a specific DAY it’s values is 01/01/0001. (Meaning if you evaluate the properly in the Load Event it has not been set to anything.)

Clicking on the next or previous month links do not change the SelectedDate property. If the user never selected a date it’s still 01/01/0001 and if the user has previously selected a date, changing the current month has no effect on the SelectedData property either.

It’s easy to understand why this is the case if you view the Calendar Control as a “Date Picker”.

My answer came in leveraging the various events thrown by the control.

The Calendar has a VisibleDate property that contains a DateTime object who’s value is set to the first day of the Month being displayed in the calendar control. This property is updated whenever the user changes the month whether they have selected a specific day or not.

Unfortunately, the VisibleDate property is not set by default. (Meaning if you evaluate the properly in the Load Event it has not been set to anything.)

Here is the simple code I’m using to get the date “type” (Month or Day) and the value to use for the SQL Parameter based on the state of the control and the user’s interaction.

Code Snippet
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.Web.UI;
  6. using System.Web.UI.WebControls;
  7.  
  8. namespace CalendarDrivenSelect
  9. {
  10.     public partial class _Default : System.Web.UI.Page
  11.     {
  12.         DateTime usableDate;
  13.  
  14.         protected void Page_Load(object sender, EventArgs e)
  15.         {
  16.             if (!IsPostBack)
  17.             {
  18.                 usableDate = SelectCalendar.TodaysDate;
  19.                 TextBox1.Text = usableDate.Month.ToString();
  20.             }
  21.         }
  22.  
  23.         protected void SelectCalendar_SelectionChanged(object sender, EventArgs e)
  24.         {
  25.             usableDate = SelectCalendar.SelectedDate;
  26.             TextBox1.Text = usableDate.ToString();
  27.         }
  28.  
  29.         protected void SelectCalendar_VisibleMonthChanged(object sender, MonthChangedEventArgs e)
  30.         {
  31.             usableDate = SelectCalendar.VisibleDate;
  32.             TextBox1.Text = usableDate.Month.ToString();
  33.         }
  34.     }
  35. }

 

If the page is not a postback, I use the Control’s TodaysDate value then whenever the user makes a change I take action in the event handler for the “type” of change that they make. If they select a specific date, I extract that date. If they later select a different month to display I extract that Month and that selection overrides the previously selected date.

In the code above I’m just populating a text box but in the application code I will use that value to set the actual Events SELECT criteria.

A simple solution but not immediately obvious.

Hope it helps someone.

Technorati Tags: ,,

Making ASP.NET Buttons Match the default WebSite Template.

6-30-2010 10-42-02 AM

 I’m working on a couple of demo application in ASP.NET Web Forms and I noticed that, like in many themes I encounter, Button objects don’t match the theme and lack mouseover effects.

So here is how you make your ASP.NET Button control instances match other “clickable” objects in the default ASP.NET Web Site template (like the menu tab).

Open the Site.css file in the Styles folder of your solution and add the following 2 CSS classes.

Code Snippet
  1.  
  2. .button {   
  3.    color: White;   
  4.    background-color: #465C71;
  5.    border:1px solid;   
  6.    border-color: Gray;   
  7. }   
  8.  
  9. .buttonhover {   
  10.    color: White;   
  11.    background-color: #BFCBD6;
  12.    border:1px solid;   
  13.    border-color: Gray;   
  14. }

Now when you add an ASP.NET Button Control to your page, set the CssClass to button and add html onmouseover and onmouseout attributes as follows.

 

Code Snippet
  1.  
  2. <asp:Button ID="Button1" runat="server" Text="Button" CssClass="button"
  3.             onmouseover="this.className=’buttonhover’"
  4.                          onmouseout="this.className=’button’"  />
  5.  

 

By default your buttons still look like vanilla buttons but when you want, this method will make your buttons match your site’s theme.

 

Technorati Tags: ,,

5 More Tailspin Spyworks Videos Now Live

6-29-2010 1-18-56 PM

The www.asp.net content team ahs pushed 5 more of my Tailspin Spyworks sample application videos live for your viewing pleasure.

TailSpin SpyWorks – Adding Items to the Shopping Cart

TailSpin SpyWorks – Display Shopping Cart

TailSpin SpyWorks – Update the Shopping Cart

TailSpin SpyWorks – Migrate the Shopping Cart

TailSpin SpyWorks – Final Check Out

Work continues …….

Add your recent Tweets to your web site.

image

Twitter continues to gain in popularity, in part because it offers a rich and easy to use query API.

Just for fun I made an ASP.NET Web Forms User Control to Display some recent Tweets on a web page.

The tweets are displayed in a ListView as follows.

Code Snippet
  1. <%@ Control Language=”C#” AutoEventWireup=”true” CodeBehind=”MyTweets.ascx.cs” Inherits=”NETOOP.Controls.MyTweets” %>
  2. <%@ OutputCache Duration=”3600″ VaryByParam=”None” %>
  3.     <asp:ListView ID=”MyTweetsListView” runat=”server”>
  4.         <LayoutTemplate>
  5.             <table class=”gridview”>
  6.                 <th>My Tweets</th>
  7.                 <tbody>
  8.                     <asp:PlaceHolder ID=”itemPlaceholder” runat=”server” />
  9.                 </tbody>
  10.             </table>
  11.         </LayoutTemplate>
  12.         <ItemTemplate>
  13.             <tr>
  14.                 <td><a href=’<%#Eval(“Url”)%>‘><%#Eval(“Title”) %></a></td>
  15.             </tr>
  16.         </ItemTemplate>
  17.     </asp:ListView>

Note the use of the OutputCache directive so the Twitter API doesn’t need to get called for very single request of any page that contains this control.

Since Microsoft’s .NET is so XML savvy and LINQ to XML is so powerful the C# code to fetch the tweets and bind to the ListView is pretty straight forward.

Code Snippet
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.Web.UI;
  6. using System.Web.UI.WebControls;
  7. using System.Xml.Linq;
  8.  
  9. namespace NETOOP.Controls
  10. {
  11.     public partial class MyTweets : System.Web.UI.UserControl
  12.     {
  13.         protected void Page_Load(object sender, EventArgs e)
  14.         {
  15.             XNamespace slashNamespace = “http://purl.org/rss/1.0/modules/slash/”;
  16.  
  17.             XDocument rssFeed = XDocument.Load(“http://www.twitter.com/statuses/user_timeline/misfitgeek.rss” + “?count=5″);
  18.  
  19.             var posts = from item in rssFeed.Descendants(“item”)
  20.                         select new
  21.                         {
  22.                             Title = item.Element(“title”).Value,
  23.                             Url = item.Element(“link”).Value,
  24.                         };
  25.  
  26.             MyTweetsListView.DataSource = posts;
  27.             MyTweetsListView.DataBind();
  28.         }
  29.     }
  30. }

 

Notice that he URL in the XDocument.Load specifies “misfitgeek.rss” to pull my personal tweets (which you can include on your web site if you like). You could change the portion of the URL to reflect your own Twitter name.

Technorati Tags: ,,

Alachisoft’s new version of NCache announced at TechEd !

Before coming to Microsoft I owned a consulting company that specialized in solving performance and scalability problems in web applications.

It always amazed me how many seeming huge problems could be solved with a little strategic caching implementation.

Alachisoft’s NCache is a PREMIER provider of advanced caching technology for ASP.NET.

Though ASP.NET has caching functionality built in, NCache can help you take caching in your application to the next level.

Here are some of the NEW features.

  • Dashboard Style Monitoring Tool: With this tool, you can now monitor all aspects of your cache and application live. You get a dashboard which can be customized according to your monitoring needs.
  • LINQ Support: NCache now provides LINQ integration with IQueryable interface that makes cached items searchable.
  • Entity Framework (EF) Caching: Now you can do seamless integration with EF caching. Plug in at the ADO level and use NCache caching without any code changes.
  • .NET Cache Provider 4.0: Integration with .NET Cache provider 4.0 – with Change Monitors (file based, key based, database dependency) for managing cache dependencies.
  • Streaming API: With streaming support in the API, now you can read and write binary data stream in the cache.
  • Multiple Providers for ReadThru/WriteThru: Develop multiple ReadThru/WriteThru providers and register with NCache. You can use a specific provider from each of your application..
  • Dynamic ReadThru/WriteThru Deployment: Use NCache Manager to deploy your ReadThru/WriteThru handlers even at runtime. Your assemblies are automatically copied to all the cache servers.
  • Runtime Compact Serialization (no programming needed): Use a faster and more compact serialization than regular .NET serialization and without writing any custom code for it. NCache generated serialization code at runtime and even lets you serialize objects that are otherwise not serializable.
  • ViewState Caching: Cache ViewState at your web server and reduce the payload being returned to the browser and speed up response time.
  • Merge & Minify Javascript/CSS: Minify and merge multiple JavaScript files. This reduces the payload sent to the browser and also the number of HTTP calls the browser makes to the web server. The results is faster response time.
  • Protocol-level Backward Compatibility for Clients: NCache 3.8 offers protocol-level backward compatibility from now on. This means any future upgrades would be 100% backward compatible at protocol-level.
  • Remote Client Management from NCache Manager: Configure Remote Clients from NCache Manager and easily change individual client settings all from a single point.

One of the especially cool things about NCache is the FREE Express version (Limited to 2-server clusters with local clients) – this lets you prove your strategy before spending anything but time :)

You can get started by going to http://www.alachisoft.com/

Can not Load Type – Starting the ASP.NET Web Site Admin Tool

SNAGHTMLd7e063

A beginner emailed me last night and I had forgotten about this little ditty !

When you create a NEW project and immediately try to run the Web Site Administration Tool you will get this error.

The solution is easy – BUILD FIRST !

I remember being very confused the first time I got this :)

First 3 Videos – Building Tailspin Spyworks

image

I’ve published the first three videos on a follow-a-long series on building the Tailspin  Spyworks demo application.

More Every Week !

http://www.asp.net/web-forms/samples/tailspin-spyworks

 

Technorati Tags: ,WebForms,,

Embedding the Silverlight version of the Open Media Player

image

I’m working on a Video Portal Application and have selected the Open Video Player for embedded viewing of videos.

There are many video players out there but I selected this one becuase there are SilverLight and Flash versions in the project.

Embedding is EASY !

Code Snippet
  1. <%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
  2.     CodeBehind="Default.aspx.cs" Inherits="OpenPlayerSample._Default" %>
  3.  
  4. <asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
  5. </asp:Content>
  6. <asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
  7.     <h2>
  8.         Welcome to ASP.NET!
  9.     </h2>
  10.     <p>
  11.         To learn more about ASP.NET visit <a href="http://www.asp.net" title="ASP.NET Website">www.asp.net</a>.
  12.     </p>
  13.     <p>
  14.         <object data="data:application/x-silverlight-2," type="application/x-silverlight-2" width="100%" height="600px" id="slp" >
  15.             <param name="source" value="./Player/SL/OVP.xap"/>
  16.             <param name="minRuntimeVersion" value="2.0.30923.0" />
  17.             <param name="onerror" value="onSilverlightError" />
  18.             <param name="background" value="black" />
  19.             <param name="MaxFrameRate" value="30" />
  20.             <a href="http://go.microsoft.com/fwlink/?LinkID=124807" style="text-decoration: none;">
  21.             <img src="http://go.microsoft.com/fwlink/?LinkId=108181" alt="Get Microsoft Silverlight" style="border-style: none"/></a>
  22.             <param name="initparams" value=’showstatistics=true,
  23.                                             autoplay=false,
  24.                                             muted=false,
  25.                                             playlistoverlay=false,
  26.                                             theme=/Player/Themes/ShinyBlue.xaml,
  27.                                             stretchmode=Fit,
  28.                                             stretchmodefullscreen=Fit,
  29.                                             mediasource=http://misfitgeek.com/not_a_real_video.wmv’ />
  30.         </object>
  31.     </p>
  32. </asp:Content>

 

Stay tuned to my blog for more usage context in the near future.

 

Archiving your contact form data.

image

I get TONS of email from customer.

Over time, this email helps me to determine what areas in our product collection are opportunities for enhancement or improvement.

I store the email that comes from my blog contact form in folders and then search through them looking for trends periodically.

It occurred to me that, while I need to get the emails because many of them are actionable, it would be great if I could use reporting and analysis tools against the collection.

So I whipped together a sample in ASP.NET MVC

I set up a simple SQL Express database and use Visual Studio to generate an EntityDataModel for it.

I implemented the view above and an ActionResult for HttpPost events from the ContactUs view.

Code Snippet
  1. [HttpPost]
  2. public ActionResult ContactUs(Message msg)
  3. {
  4.     if (ModelState.IsValid)
  5.     {
  6.         // Same the Message in the Massages Table.
  7.         try
  8.         {
  9.            using(ContactMailEntities db = new ContactMailEntities())
  10.            {
  11.                db.AddToMessages(msg);
  12.                db.SaveChanges();                  
  13.            }
  14.         }
  15.         catch
  16.         {
  17.             // Store Failed.
  18.             return View(msg);
  19.         }
  20.  
  21.         // Send the Message in email.
  22.         if (!SendMailMessage(msg))
  23.         {
  24.             // Send Failed.
  25.             return View(msg);
  26.         }
  27.     }
  28.     else
  29.     {
  30.         return View(msg);
  31.     }
  32.  
  33.     // Success
  34.    return View("MessageSent");
  35. }

Since my view uses that model, on post back my ActioResult can just create an instance of the model and call the generated “AddToMessages” (to insert to the Messages Table)  method and pass in the Message instance from the View.

Wow – easy and elegant.

BTW the SendMailMessage method looks like this.

Code Snippet
  1. public bool SendMailMessage(Message msg)
  2. {
  3.     try
  4.     {
  5.         MailMessage mailMsg = new MailMessage();
  6.         mailMsg.To.Add("Joe@Stagner.net");
  7.         MailAddress mailAddress = new MailAddress(msg.FromEmail, msg.FromName);
  8.         mailMsg.From = mailAddress;
  9.         mailMsg.Subject = msg.Subject;
  10.         mailMsg.Body = msg.ContactMessage;
  11.  
  12.         SmtpClient smtpClient = new SmtpClient("mail.stagner.net", 2525);
  13.         System.Net.NetworkCredential credentials = new System.Net.NetworkCredential("Joe@Stagner.net", "bingo117");
  14.         smtpClient.Credentials = credentials;
  15.  
  16.         smtpClient.Send(mailMsg);
  17.         return true;
  18.     }
  19.     catch (Exception ex)
  20.     {
  21.         return (false);
  22.     }
  23.  
  24. }

Hope someone finds it useful.

[ Full project HERE ]

 

 

 

Introducing – TailspinSpyworks – WebForms Sample Application

Tailspin-Spyworks-Thumb

iBuySpy was a very popular sample application, but a lot has changed in Web Forms development since then.

ScottGu suggested that I rewrite the old iBuySpy application – so I did.

It’s ASP.NET 4 with CSS based layout, data access via Entity Framework, etc.

The www.asp.net landing page is here http://www.asp.net/web-forms/samples/tailspin-spyworks/

I’ll be adding features over time and doing videos to explain some of the cool stuff.

You can download the code from CodePlex at http://tailspinspyworks.codeplex.com/

For you MVC folks, my team mate (Jon Galloway) has built a sample MVC Store application which you can find here : http://www.asp.net/mvc/samples/mvc-music-store/

 

Technorati Tags: ,,WebForms,

First 3 ASP.NET MVC for the Rest of Us Videos

Folks have been asking me for some time to do some ASP.NET MVC videos 

Here are the first three. They start from the beginning and frequently compare ASP.NET MVC with concepts that you may already be familiar with from WebForms programming.

Enjoy! More to come.

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

37 minutes

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

31 minutes

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

16 minutes

http://www.asp.net/mvc/fundamentals/

 

Technorati Tags: ,

Join me on MSDN Radio next Monday – Mark your calendar.

Announcement:

MSDN Radio: The ASP.NET Developer Evolved with Joe Stagner

Event ID: 1032448575

 

Date: Monday, April 12, 2010 9:00 AM Pacific Time (US & Canada) 30 Minutes

 

Event Overview

You may know him as Mr. How Do I with Microsoft ASP.NET. For the last few years Joe has been busy working with the ASP.NET product team to simplify and educate developers on what’s possible with the latest web tools. We talk with Joe about how the web developer is able to learn about and leverage new tools and techniques for building great solutions.
MSDN Radio is a weekly Developer talk-show that helps answer your questions about the latest Microsoft news, solutions, and technologies. We dive into the challenges of deciphering today’s technology stack. Register today and have a chance to call-in and talk with the experts on the air, or just tune in to the show.
Caller space is limited, dial-in information will be given out during the show.

Presenters: Mike Benkovich, Senior Developer Evangelist, Microsoft Corporation and Joe Stagner, Senior Program Manager, Microsoft Corporation

Mike Benkovich delivers technical presentations around the U.S. as a developer tools evangelist on the MSDN team at Microsoft. He has worked in a variety of professional roles, including architect, project manager, developer, and technical writer. Mike is also a published author with WROX Press and APress, exploring how developers get the most from their SQL databases. Since appearing in the 1994 Microsoft DevCast, Mike has presented technical information at seminars, conferences, and corporate boardrooms across America.

Joe Stagner works at Microsoft with the Developer Tools and Platforms team and as spent almost ten years at Microsoft working with the developer community. With three decades of software development experience, Joe is well versed in the needs of all types of software developers and in recent years has focused on all aspects of web development technology and the use of the world wide web for business and social interaction. In addition to Microsoft’s ASP.NET technology Joe focuses on integrating .NET with third part technology like PHP, Java, etc. You can read his blog at www.misfitgeek.com.

View other sessions from: MSDN Radio

If you have questions or feedback, contact us.

Registration Options

Event ID:
1032448575

Registration page for MDSN Radio on 4/12 is here -  http://tinyurl.com/msdnradio-4

Non-Embedded Content for your Popup Control’s Target Container

Yesterday I posted about client side predicates for Popup controls. Thanks for all the Tweets and Emails.

The Popup control is very powerful and Popups are now an expected construct in many web user interfaces.

I received a number of questions about using content in Popups that is not embedded in the containing page.

Probably the easiest is to use in iFrame inside the Panel container for the Popup.

In code it looks like this.

Code Snippet
  1. <h1>Modal iFrame</h1>
  2. <asp:Button ID="ButtonIFrame" runat="server" Text="Button" /><br /><br />
  3. <div>
  4.     <asp:Panel ID="PaneliFrame" runat="server" CssClass="modalPopup"
  5.                                 Style="display: none" Width="450px" Height="250px">
  6.     <iframe name="f1" src="Popup.aspx"  frameborder="0" scrolling="no" width="100%" height="200px">
  7.     </iframe>
  8.     <br />
  9.        <div align="center">
  10.           <asp:Button ID="OkButton" runat="server" Text="OK" />
  11.           <asp:Button ID="CancelButton" runat="server" Text="Cancel" />
  12.        </div>
  13.     </asp:Panel>
  14.     <br />
  15.    <ajaxToolkit:ModalPopupExtender ID="ModalPopupExtenderIF" runat="server"
  16.              TargetControlID="ButtonIFrame"
  17.              PopupControlID="PaneliFrame"
  18.              BackgroundCssClass="modalBackground"
  19.              DropShadow="true"
  20.              OkControlID="OkButton"
  21.              OnOkScript="onOk()"
  22.              CancelControlID="CancelButton" />
  23. </div>

There is an advantage when using the iFrame in that you can reference a complete HTML or ASPX page since the iFrame expects this.

IN the example above I set the href attribute of the iFrame to a .aspx page (Popup.aspx) in the same solution but you need not do this. The href attribute can be set to any url that you like, even on a different domain.

This avoids an issue that we will need to consider when using the other three methods that I will discuss below.

HTML and ASP.NET both have requirements that define “well formedness”. HTML, for example, declares that a page may only have one <head> section. ASP.NET declares that a page may only have <form> tag with a “runat=server” attribute.

We need to consider this when “inserting” content into our page elements (such as the container that is displayed whern a Popup is shown.

Next lets look at using an ASP.NET User Control in a Popup.

Code Snippet
  1. <h1>Modal Control</h1>
  2. <asp:Button ID="ButtonControl" runat="server" Text="Button" /><br /><br />
  3. <div>
  4.     <asp:Panel ID="PanelControl" runat="server" CssClass="modalPopup"
  5.                                  Style="display: none" Width="450px" Height="250px">
  6.    <uc1:ControlForPopup ID="ControlForPopup1" runat="server" />
  7.  
  8.        <br />
  9.        <div align="center">
  10.           <asp:Button ID="ButtonOkControl" runat="server" Text="OK" />
  11.           <asp:Button ID="ButtonCancelControl" runat="server" Text="Cancel" />
  12.        </div>
  13.     </asp:Panel>
  14.     <br />
  15.    <ajaxToolkit:ModalPopupExtender ID="ModalPopupExtenderControl" runat="server"
  16.              TargetControlID="ButtonControl"
  17.              PopupControlID="PanelControl"
  18.              BackgroundCssClass="modalBackground"
  19.              DropShadow="true"
  20.              OkControlID="ButtonOkControl"
  21.              OnOkScript="onOk()"
  22.              CancelControlID="ButtonCancelControl" />
  23. </div>

This method works pretty much as you would expect with the use of any User Control, and you need to be careful with things like code based rendering (Response.Write), just like any other User Control

Or, we could use the #include directive as below..

Code Snippet
  1. <h1>Modal Include</h1>
  2. <asp:Button ID="ButtonInc" runat="server" Text="Button" /><br /><br />
  3. <div>
  4.      <asp:Panel ID="PanelInc" runat="server" CssClass="modalPopup"
  5.                               Style="display: none" Width="450px" Height="250px">
  6.         <!–#include file="inc_popup.aspx"–>
  7.  
  8.        <br />
  9.        <div align="center">
  10.           <asp:Button ID="ButtonOK_Inc" runat="server" Text="OK" />
  11.           <asp:Button ID="ButtonCancel_Inc" runat="server" Text="Cancel" />
  12.        </div>
  13.     </asp:Panel>
  14.     <br />
  15.    <ajaxToolkit:ModalPopupExtender ID="ModalPopupExtenderInclude" runat="server"
  16.              TargetControlID="ButtonInc"
  17.              PopupControlID="PanelInc"
  18.              BackgroundCssClass="modalBackground"
  19.              DropShadow="true"
  20.              OkControlID="ButtonOK_Inc"
  21.              OnOkScript="onOk()"
  22.              CancelControlID="ButtonCancel_Inc" />
  23. </div>

I’m including a file with a .aspx extension but it is not (nor can it be) a complete ASP.NET page for the reasons stated above.

Lastly, you could fetch the content to be displayed in the Popup on demand via a JavaScript callable services method as shown in this video -

AJAX Content Fetch from JavaScript

Grab a working sample here http://misfitgeek.com/downloads/code/ModalPopup-ExternalSource.zip 

Have fun !

Technorati Tags: ,

ASP.NET AJAX Modal Popup on Mouse Over

Today’s customer question concerns client side predicates for showing a Modal Popup control.

I’m happy to be getting these kind of questions because it shows how ASP.NET developers are continuing to evolve their web development perspective and separate server logic execution and client logic execution.

Though the Modal Popup Extender is a Server Side control extender it HAS client side events and methods. This exposes the Modal Popup to any JavaScript coding that we want.

Example – mouseover !

Code Snippet
  1. <a href="" onmouseover="myMouseOver();">
  2. <img runat="server" id="rollover" alt="" src="image.jpg" border="0" name="rollover" /></a>
  3. <ajaxToolkit:ModalPopupExtender ID="ModalPopupExtender1" runat="server"
  4.           TargetControlID="rollover"
  5.           PopupControlID="Panel1"
  6.           BackgroundCssClass="modalBackground"
  7.           DropShadow="true"
  8.           OkControlID="OkButton"
  9.           OnOkScript="onOk()"
  10.           CancelControlID="CancelButton" />

Note that the TargetControlID is the Image of the anchor tag and the onmousover event handler calls my custom JaqvaScript function myMouseOver() which displays the Modal Popup as follows:

Code Snippet
  1.     <script type="text/javascript">
  2.     var MakeChoice;
  3.     function onOk() {
  4.     // Do stuff Here.
  5.     }
  6.     
  7.     function myMouseOver() {
  8.         $find("ModalPopupExtender1").show();
  9.     }
  10.  
  11. </script>

Click OK or Cancel closes the Modal Popul as you would expect.

Viola !

Bur don’t stop there – use more client side logic to customize the user experience. For example, you could automatically display the Pop Up on Mouse Over and start a timer to count down and hide it again ( $find(“ModalPopupExtender1”).hide(); ) after a certain number of seconds.

Keep making your UIs ROCK !

You can download a runnable sample [ HERE ]

Technorati Tags: ,

Podlogger – Half Baked Code, but yours for free.

image

Some time ago I started building a demo application that would have been posted on www.asp.net.

It is a Podcast Publishing application and completing “basic” functionality we decided that it was a bit too complex for the intended introductory material.

Though not finished (Meaning NOT FINISHED, INCOMPLETE, IMPERFECT, ETC) I thought I’d share it in case anyone finds it useful.

Some of the stuff that is in there :

  • Basic Post Publication with Rich Editor
  • File Upload
  • Comments Submission
  • RSS Feed Publication
  • Integrated Silverlight Audio Player
  • Basic Admin

This code is NOT supported and NOT offered as best practice.

It’s simply a prototype that I’m sharing in case anyone finds it useful.

If you use it anywhere, please let me know what you grow it in to.

[ Click HERE to get the code. ]

Dynamic User Specific CSS Selection at Run Time

I had a cool question while I was at MIX.

A developer needed the ability to have his site render pages using a CSS file selected based on some user specific criteria.

ASP.NET 4 controls generate CSS friendly output and more and more we web developers are using CSS for layout etc.

Using multiple CSS files in our site wide templates we can not only provide different aesthetic experiences but we can charge the style based on the device type (Printer or Phone) or the special needs of the end user (Color Blind of Vision Impaired).

It’s really easy.

I set the Theme Directory yin the Session Start Event Handler.

Though I’, simply setting to a static value here, this is were you would make some decisions in code. You could check for a cookie or the device type.

If you want to make the CSS user selectable you might use a default CSS file until the user logs in and then set this Session Object in the Log In event handler.

protected void Session_Start(object sender, EventArgs e)
{
Session["Theme"] = "Default";
}

Make sure your login never fails to set this value. If you’re depending on a Profile setting or Cookie Value, make sure you have a default setting do that it’s never empty.

Then you can just reference it dynamically in the Style Sheet inclusion of your Mast Page file like this.

 

<link href="/Styles/<%= Session["Theme"] %>/Site.css" rel="stylesheet" type="text/css" />

Simple, but useful.

Did you miss the IIS7 FastCGI Update ?

In case you did, there are some interesting improvements like….

  • Monitor changes to a file. The module can be configured to listen for file change notifications on a specific file and when that file changes, the module will recycle FastCGI processes for the process pool. This feature can be used to recycle PHP processes when changes to php.ini file occur. To enable this feature use the monitorChangesTo setting in the <fastCgi> configuration element.
  • Real-time tuning of MaxInstances setting. This MaxInstances setting dictates the maximum number of FastCGI processes which can be launched for each application pool. Set it to 0 to let FastCGI module automatically adjust the number of instances up or down based on the system load and number of requests waiting in the queue.
  • STDERR stream handling. There are several options of how the module can handle text sent by FastCGI application on STDERR. The module can send the error data as a failure response to the HTTP client or it can ignore the error and send whatever was received on STDOUT as a response with 200 status code. This behavior is controlled by the stderrMode setting.
  • Sending a termination signal to FastCGI processes. The module can be configured to send a termination signal to FastCGI process before terminating it. This enables FastCGI processes to do a clean shutdown before getting killed. The signalBeforeTerminateSeconds setting can be used to specify how long the module will wait before it forcefully shuts down the FastCGI process that does not respond to the termination signal. This feature is disabled by default.
  • _FCGI_X_PIPE_ environment variable. This variable is set by FastCGI module and it contains the name of the named pipe that is used for communication between the module and FastCGI process.
  • Relaxed enforcement of response headers syntax. The FastCGI module now has less strict enforcements for the correctness of the response headers.
  • Using UTF-8 encoding for server variable values. By default FastCGI uses ASCII encoding when setting server variables. If a FastCGI application requires UTF-8 encoded values for certain server variables, the module can be configured to use UTF-8 only for required server variables. Follow these instructions to enable this functionality.

 

Get the update with the “Web Platform Installer” here – http://www.iis.net/webpi

Session Time Out Tricks

I recently received an email from a developer who needed to implement a behavior around a user’s session timeout behavior.

As you probably know, we can configure our application to “expire” a user’s session at any interval that we wish.

Example:

<system.web>
<sessionState timeout="10" />
........
</system.web>

We can add a specification to our application’s web.config file to change the default session expiration time from 20 minutes to a time span of our own choosing. (10 minutes in the example above.)

The session timeout value is a sliding value; on each request the timeout period is set to the current time plus the timeout value.

This means that if a user submits a request after the timeout period expires, the session will have been terminated and the user will no longer be authenticated. If the user’s “post-back” is requesting a secured resource, they will be redirected to the “login” page since the application sees this request as from an anonymous user. (When a session expires the user is de-authenticated.)

The problem in this cast is that the application requirements required that the user be AUTOMATICALLY redirected when the session times out.

This is a sound security practice in certain applications.

For example, lets suppose the application’s user has displayed the results of a query of “sensitive” information. If the user then walks away from their PC, that sensitive data will stay displayed indefinably.

The application that I was contacted about needed the user’s browser to be automatically be redirected when the session timed out.

The problem, of course, is that browser based applications are innately stateless sine they run on HTTP ( a stateless protocol). The browser (client) and the sever only communicate when the CLIENT specifically makes a request of the server.

To meet the applications requirements we can add a timer in JavaScript to be run in the browser.

In our master page (so that the JavaScript will be included in, and executed by every page in our application) we can include the following client side script:

   1:  <head runat="server">
   2:      <title></title>
   3:      <link href="~/Styles/Site.css" rel="stylesheet" type="text/css" />
   4:      <script type="text/javascript" language="javascript">
   5:      <!--
   6:              var secs
   7:              var timerID = null
   8:              var timerRunning = false
   9:              var delay = 1000
  10:   
  11:              function InitializeTimer() 
  12:              {
  13:                  if (typeof HeadLoginName != 'undefined') {
  14:                  // Set the length of the timer, in seconds
  15:                  secs = 630
  16:                  StopTheClock()
  17:                  StartTheTimer()    
  18:                  }
  19:              }
  20:   
  21:              function StopTheClock() 
  22:              {
  23:                  if (timerRunning)
  24:                      clearTimeout(timerID)
  25:                  timerRunning = false
  26:              }
  27:   
  28:              function StartTheTimer()
  29:              {
  30:                  if (secs == 0) 
  31:                  {
  32:                      StopTheClock()
  33:                      window.location = "default.aspx"
  34:                  }
  35:                  else 
  36:                  {
  37:                      self.status = secs
  38:                      secs = secs - 1
  39:                      timerRunning = true
  40:                      timerID = self.setTimeout("StartTheTimer()", delay)
  41:                  }
  42:              }
  43:      //-->
  44:      </script>
  45:   
  46:      <asp:ContentPlaceHolder ID="HeadContent" runat="server">
  47:      </asp:ContentPlaceHolder>
  48:  </head>

Then we add an “onload” to our html body tag as so:

<body onload="InitializeTimer()">

Note that the client side timer is set to 10 minutes and 30 seconds. This is a plus 30 second complement to the server side setting of 10 minutes so that we should be sure that when the client code “times out” the session on the server will have already expired.

When the client side timer counts down to zero this line of JavaScript code:

  33:                      window.location = "default.aspx"

causes the browser to request the application’s default page.

We could, of course, just post back to the “current” page and let the application’s authentication configuration redirect the user to the application’s login page.

Note that this method is a loose synchronization of the applications session. If we absolutely needed an exact synchronization we could implement an AJAX service method and query the server as to whether or not the REAL .NET session has expired, but we’re not going to do that here since it creates some unnecessary (for most applications)  http traffic.

We could of course do other things form our client side code and do things like black the browser window and pop up a dialog (like a screen saver) or really whatever we want. jQuery is great for this kind of powerful client side work.

Here is a quick bit of sample code that shows the technique – [ DOWNLOAD HERE ].

 

Technorati Tags: ASP.NET Sessions Tips & Tricks

DiscountASP.NET Adds & Enhanced Microsoft IIS Database Manager Support

Historically, working with databases on shared hosting accounts has been problematic.

DiscountASP.net has implemented the IIS Database manager with some additions. Now you can manage your own databases and do things like Backup & Restore yourself.

[ For more information about the IIS Database Manager, and other cool IIS Extensions – Click HERE ]

[ For more info about DiscountASP.NET’s DB Manager Integration -  Read HERE ]

Postback Text Processing with the AJAX Modal Dialog

image

I’ve started blogging simple tips when I get a question from a developer that’s a bit tricky.

This is one of those. Simple to do, but not always simple to find the answer.

In this case the developer wanted to use an AJAX Editor Control inside a ModalPopup control.

This isn’t a problem but, the user needed to clicking the OK button to cause a post-back so that he could execute some server –side logic.

The ”Ok” Button is an ASP.NET control but adding a Click Event Handler for the button didn’t solve the problem because it didn’t get executed when the use Clicked on the “Ok” button.

Normally the ModalPopupExtender would be used like this.

<ajaxToolkit:ModalPopupExtender ID="ModalPopupExtender1" runat="server"
TargetControlID="LinkButton1"
PopupControlID="Panel1"
BackgroundCssClass="modalBackground"
DropShadow="true"
1.)         OkControlID="OkButton"
2.)         OnOkScript="onOk()"
CancelControlID="CancelButton" />

Line number 1 tells the control to catch the click event for the Ok Button Control instance and line 2 specifies when CLIENT SIDE JavaScript code to execute when the control specifies in line 1 is clicked.

The post-back doesn’t happen (even if the ASP.NET Button control hasd a click event handler defined in code behind because the control doesn’t propagate it.

So Just delete those two lines !

It turns out that they are optional and if you delete them the click event is not trapped and the code behind will execute as expected.

So just nake it look like this:

<ajaxToolkit:ModalPopupExtender ID="ModalPopupExtender1" runat="server"
TargetControlID="LinkButton1"
PopupControlID="Panel1"
BackgroundCssClass="modalBackground"
DropShadow="true"
CancelControlID="CancelButton" />

Simple !

[ Download working C# Code HERE ]

Technorati Tags: ASP.NET AJAX Tips & Tricks

Site Authentication Required, Except Default.aspx

What happens when you need to protect your whole site so that only Authenticated users can access our site.

Since I received this question twice this week I thought I’d share a tip.

To allow ONLY authenticated access to your site using Forms authentication you can add a section like this on e to your application’s web.config file.

<authentication mode="Forms">
<forms loginUrl="Login.aspx" name="Login" protection="All"/>
</authentication>
<authorization>
<deny users="?"/>
</authorization>

 

The problem is that it seems lots of folks don’t want users to automatically redirect to the Login.aspx page when they navigate to their site home page.

To require authentication for all the pages in your web application EXCEPT the home page (Default.aspx)) 

Also add a location section to your web.config file that explicitly allows anonymous users to access JUST the default.aspx page.

<location path="default.aspx">
<system.web>
<authorization>
<allow users="*"/>
</authorization>
</system.web>
</location>

You can use the web.config location element to specify folders as well as pages which makes it a very powerful construct.

 

Technorati Tags: Microsoft ASP.NET Security Tips & Tricks

Trapping Intentional Cross Site Scripting (XSS) Attempts in ASP.NET

So I’m building an ASP.NET application to host Podcasts and in the post submission logic I want folks to be able to submit markup, but not JavaScript.

image

ASP.NET automatically traps suspicious posts to the server, but the results have to unfortunate defines.

First is the ugly resulting page. We’ve all seen them.

image

And the second is that I may want to be able to add some SPECIFIC logic to handling that Security exception because it probably means someone is intentionally trying to hack my web site.

It turns out that this is another that ASP.NET makes easy to solve.

First, add a Global.asax file to your solution and code the global Application_Error event handler as follows.

   1:  protected void Application_Error(object sender, EventArgs e)
   2:  {
   3:      Exception objErr = Server.GetLastError().GetBaseException();
   4:      string err = objErr.Message.ToString();
   5:   
   6:      string secError = "A potentially dangerous Request.Form value was detected";
   7:      string baseUrl = Request.Url.Scheme + "://" + Request.Url.Authority +
                                          Request.ApplicationPath.TrimEnd('/') + '/';
   8:      Server.ClearError();
   9:   
  10:      if (err.IndexOf(secError) != -1)
  11:      {
  12:          Response.Redirect(baseUrl + "SecurityError.aspx");
  13:      }
  14:      else
  15:      {
  16:   
  17:          Response.Redirect(baseUrl + "Error.aspx");
  18:      }
  19:  }

When the specific form validation error is encountered we redirect to a specific web page. (SecurityError.aspx)

The user gets a much better experience.

image 

This solves the second problem with the default handling. Even without additional work on my part the IIS Server Logs will be able to tell me how many times this happens along with information about the requests that generate them.

If I want to get more specific I can forward the originals HTTP request and exception info to SecurityError.aspx and take some action.

If the form can only be submitted by a user who is logged in to my application, even better. I can count how many times then cause this eror to happen and then based on that data I can warn them, log them off or ban them from my site completely

Do you add security specific error handling to your site ? If so, let me know.

Technorati Tags: ASP.NET Security Tips & Tricks

I get many (MANY) email from customers who are struggle to answer specific technical problems. As time permits I’m going to start answering them here,

I recently received an email from a developer building an application using the Ajax Control Toolkit and he needed his page to contain an Accordion Control in which all Panes were CLOSED when the page was initially loaded.

Like this ……

image

The Accordion Control in the earliest versions of the Ajax Control Toolkit lacked this ability but now it’s pretty easy.

By default, the Accordion Control requires one of it’s contained Panes must be open at all times.

So, there are two things we need to do in our Accordion Control configuration.

  1. Configure the control so that it does NOT require at least one open Pane.
  2. Set the default Pane index to one that does not exist so that NO Pane will be open when the page loads.

Luckily, the Control exposes the properties that we need.

Here is the control syntax.

<ajaxToolkit:Accordion ID="MyAccordion" runat="server"                        

HeaderCssClass="accordionHeader" ContentCssClass="accordionContent" 

FadeTransitions="true" FramesPerSecond="40" TransitionDuration="250" 

AutoSize="None" RequireOpenedPane="false" SelectedIndex="-1">

 

The bottom two attributes are the ones that interest us.

RequireOpenPane=”false” – Tells the Accordion control that it’s OK for all the contained Panes to be closed. 

SelectedIndex=”-1” – Tells the Accordion control to set as Active the Panel whose index is –1 (which doesn’t exist”.

These two settings combine to offer the startup effect that you see in th epicture above.

[ Click HERE to download a sample project of this technique. ]

Technorati Tags: Microsoft ASP.NET AJAX Controls Accordion Tips & Tricks

Test your ASP.NET knowledge on an Android phone !

android_dda_lab_3

A free Android application for testing your ASP.NET Development Knowledge.

[ Check it out here. ]

Unwinding the page lifecycle events

Since I spent some time today working with control extenders and exactly where in the page lifecycle to do what, I thought I’d share the whole list.

If (!IsPostBack)

  1. Begin PreInit
  2. End PreInit
  3. Begin Init
  4. End Init
  5. Begin InitComplete
  6. End InitComplete
  7. Begin PreLoad
  8. End PreLoad
  9. Begin Load
  10. End Load
  11. Begin LoadComplete
  12. End LoadComplete
  13. Begin PreRender
  14. End PreRender
  15. Begin PreRenderComplete
  16. End PreRenderComplete
  17. Begin SaveState
  18. End SaveState
  19. Begin SaveStateComplete
  20. End SaveStateComplete
  21. Begin Render
  22. End Render

If(IsPostBack)

  1. Begin PreInit
  2. End PreInit
  3. Begin Init
  4. End Init
  5. Begin InitComplete
  6. End InitComplete
  7. Begin LoadState
  8. End LoadState
  9. Begin ProcessPostData
  10. End ProcessPostData
  11. Begin PreLoad
  12. End PreLoad
  13. Begin Load
  14. End Load
  15. Begin ProcessPostData (Again)
  16. End ProcessPostData (Again)
  17. Begin Raise ChangedEvents
  18. End Raise ChangedEvents
  19. Begin Raise PostBackEvent
  20. End Raise PostBackEvent
  21. Begin LoadComplete
  22. End LoadComplete
  23. Begin PreRender
  24. End PreRender
  25. Begin PreRenderComplete
  26. End PreRenderComplete
  27. Begin SaveState
  28. End SaveState
  29. Begin SaveStateComplete
  30. End SaveStateComplete
  31. Begin Render
  32. End Render

Implementing a jQuery Modal Window in ASP.NET

I’ve recently had several questions about attempts to use the Ajax Control Toolkit’s Modal Dialog, or more accurately, to misuse it, as a window.

It’s a “dialog” and therefore not well suited to being used for receiving data from the user.

Controls like the Modal Dialog Extender Control are convenient when they do when we want them to do but when they don’t there is no reason not to “roll our own” functionality.

In this case I’ve built a sample using jQuery to display a Semi-Modal Window to allow the user to edit a field on the page.

I say “semi” Modal because clicking outside the Window causes the edits to be aborted, the Window to be closed, and the page to be visually restored.

The page normally looks like this…….

jqModal

Then Clicking on the “Edit Photo Caption” link causes this to happen.

jqModal-EditMode

In this dialog one can edit the caption that appears below the photo.

The interesting thing here is that, though I’m using jQuery to display the Window, the rest is plain ASP.NET server controls and code behind.

The “Save” button is an ASP.NET button control which means that there is a Server-Side event handler where I can process they newly entered Photo Caption.

In the case of this demo I just update the page display but we could also use that Click event handler to persist the changed data to a database since it runs server side. (No “services” required.)

The Code…

I start with generating a default ASP.NET 4 Web Forms Application with Visual Studio 2010

Then we pull jQuery via a reference in the master page.

<script type="text/javascript"
     src="http://code.jquery.com/jquery-latest.pack.js"></script>

Note that the new Web Forms project template in Visual Studio 2010 includes versions of jQuery and even one that has IntelliSense support but I’ve opten to dynamically bull the latest version directly from the jQuery code repository.

Next, we have some styles added to the generated Style.css file to handle making the page opaque when we show the Window as well as styles for the Window itself.

   1: #mask

   2: {

   3:   position:absolute;

   4:   left:0;

   5:   top:0;

   6:   z-index:9000;

   7:   background-color:grey;

   8:   display:none;

   9: }

  10:

  11: #boxes .window {

  12:   position:absolute;

  13:   left:0;

  14:   top:0;

  15:   width:440px;

  16:   height:200px;

  17:   display:none;

  18:   z-index:9999;

  19:   padding:20px;

  20: }

  21: 

  22: #boxes #modalwindow {

  23:   width:375px;

  24:   height:203px;

  25:   padding:10px;

  26:   background-color:#ffffff;

  27: }

  28: 

  29: .stylecenter

  30: {

  31:     text-align: center;

  32: }

 Next we have the code for displaying the Window. Note that this jQuery code is bound ONLY to a DOM <A> Element named “modal”.

Lets look at the code and then I’ll call out a detail or two.

   1:      <script type="text/javascript">
   2:          $(document).ready(function () {
   3:   
   4:              // Set up for displaying modal dialogs
   5:              $('a[name=modal]').click(function (e)
   6:              {
   7:            // Prevent the default link behavior of navigation so we can
                    use the link to show the Window
   8:                  e.preventDefault();
   9:   
  10:                  // Determine which href was clicked if it was in fact an href
(though this demo as only one.) 
  11:                  var id = $(this).attr('href');
  12:   
  13:                  // Determine browser windows dimensions. 
  14:                  var maskHeight = $(document).height();
  15:                  var maskWidth = $(window).width();
  16:   
  17:                  // Set dimensions for the mask to opaque the screen when 
                        the modal window is displayed.
  18:                  $('#mask').css({ 'width': maskWidth, 'height': maskHeight });
  19:   
  20:                  // Make the Window Opaque        
  21:                  $('#mask').fadeIn("fast");
  22:                  $('#mask').fadeTo("slow", 0.8);
  23:   
  24:                  //Get the window height and width
  25:                  var winH = $(window).height();
  26:                  var winW = $(window).width();
  27:   
  28:                  // Set the Modal Window's dimensions to center in the 
                          browser window.
  29:                  $(id).css('top', winH / 2 - $(id).height() / 2);
  30:                  $(id).css('left', winW / 2 - $(id).width() / 2);
  31:   
  32:                  // Show the Modal Window
  33:                  $(id).fadeIn("fast");
  34:   
  35:              });
  36:   
  37:              // Handle Close Button Click Event
  38:              $('.window .close').click(function (e) {
  39:                  // Cancel the link behavior
  40:                  e.preventDefault();
  41:   
  42:                  $('#mask').hide();
  43:                  $('.window').hide();
  44:              });
  45:   
  46:              // The user clicks OUTSIDE the Modal Window and the window will be 
                      closed without save.
  47:              $('#mask').click(function () {
  48:                  $(this).hide();
  49:                  $('.window').hide();
  50:              });
  51:   
  52:          });
  53:  </script>

We should also note the HTML for the like and the Window to be shown when that like is clicked.

<a href="#modalwindow" name="modal">Edit Photo Caption</a>
</div>
<div id="boxes">
<div id="modalwindow" class="window">
<center>Enter New Caption</center><br />
<asp:TextBox ID="ClientDataTextBox" runat="server" ClientIDMode="Static"
    TextMode="MultiLine" Height="120" Width="370"></asp:TextBox><br />
<asp:Button ID="ModalButton" runat="server" Text="Save" onclick="ModalButton_Click" />
</div>
<!-- Mask to cover the whole screen -->
<div id="mask"></div>
</div>

 Note the line …..

$('a[name=modal]').click(function (e)

“modal” is the name of the <A> object that for opening the Window.

 
Note that the href= is set to the same name as the id of the <DIV> to be displayed when the <A> is clicked and it is that relationship that causes the related Window to be displayed.
 
The cool thing about this is (to me anyway) how I can intermingle ASP.NET and jQuery JavaScript. The fields in the Modal Window get processed in my Code-Behind so I don’t need to write extra JavaScript to fetch and handle the new Photo Caption and I don’t need to write Ajax service Methods to handle Server Side processing of that new data,
 
For me it is this sort of change in style that is indicative of the “new” ASP.NET Web Forms developer.
 
You can grad a zip file of the ASP.NET 4 project [ HERE ]
 
Have Fun !
 
PS: I adapted code from this post http://www.queness.com/post/77/simple-jquery-modal-window-tutorial  to ASP.NET and Failed to give attribution to the original author.  My apologies to Queness.
 
Technorati Tags: ASP.NET 4 jQuery Modal Window Code

Building an Awesome Community Web Site

Some time ago I started playing with the idea of organizing an Open Source project to build a CMS.

It generated a lot of interest, but the “expectations” seemed overwhelming to me. NETOOP is not dead, I still plan to build it but I intend to build version one myself (On MVC) and release it as FREE source.

In the mean time, I’m planning what content to build for 2010 and have decided to do a collection of projects based on building a great community site.

I’m going to write the code and record videos detailing the implementation or the parts.

I hope YOU will suggest and discuss features with me here on my blog! I will release the code as FREE/MSPL at different milestones.

The “design” that I’m starting with is live at www.MMARingside.org

MMSRS_001

It’s currently deployed on .NET 3.5 on Web Forms.

  • I’ll be updating to ASP.NET 4 very soon.
  • I will be doing a MVC version.
  • As much code as possible will be modular and transportable.

The first features I’ll be working on are…….

  • Add ASP.NET Membership System
  • Add Roles
  • Add CUSTOM Profile System
  • Add Daily Notice Admin Editor (Admin Only, Rich Text Editor)

Please share your thoughts and feature ideas and don’t worry if MMA is not your thing.

I just chose a sports application so we could have fun with rich media features !!!!!

 

Technorati Tags: Microsoft ASP.NET CMS MMA UFC How-Do-I

BOOK – ASP.NET 4.0 by Joydip Kanjilal

0071604103

ASP.NET 4 is almost here and the new stuff is great but it’s hard to make the time to stay current and keep up to date on all the new stuff.

Joydip has done the heavy lifting for us and encapsulated core concepts in his new book ASP.NET 4.0 Programming.

As you can read in my comment on the inside cover, this book is more than a quick feature tour of the new stuff. It’s a concise guide to building ASP.NET 4 application using the new “paradigm.”

Read it as a primer to the technologies that you;ll see at this years MIX and TechEd and my upcoming ASP.NET 4 video series.

[ Get it HERE ]

Technorati Tags: Book ASP.NET 4

30 “Quick Hit” Videos for folks that couldn’t join us at PDC

Hi folks! I’m posting this from the PDC09 keynote where I’m listening to Don Box show off Azure !

For web developers, I prepared 30 “Quick Hit” videos on stuff that’s new in the latest wave for ASP.NET Develoeprs.

It’s far from a complete list, and they are not meant to be real tutorials (They are NOT How-Do-I videos).

Think of them as “feature previews” with more learning based material coming in the near fututr.

Here is a partial list.

Have fun

www.asp.net/learn

ASP.NET 4

ASP.NET 4 "Quick Hit" – New Rendering Option for Check Box Lists and Radio Button Lists

ASP.NET 4 "Quick Hit" – Persistent GridView Row Selection

ASP.NET 4 "Quick Hit" – Table Free Templated Controls

ASP.NET 4 "Quick Hit" – Easy State Compression

ASP.NET 4 "Quick Hit" – Tableless Menu Control

ASP.NET 4 "Quick Hit" – Imperative JavaScript Syntax for Microsoft Client Side Controls

ASP.NET 4 "Quick Hit" – The ScriptLoader

ASP.NET 4 "Quick Hit" – jQuery Syntax for Microsoft Ajax

ASP.NET 4 "Quick Hit" – AJAX Data Templates

ASP.NET 4 "Quick Hit" – Hidden Field Divs

ASP.NET 4 "Quick Hit" – Disabled Control Styling

ASP.NET 4 "Quick Hit" – Declarative WebForms Routing

ASP.NET 4 "Quick Hit" – Outbound WebForms Routing

ASP.NET 4 "Quick Hit" – Auto Start

ASP.NET 4 "Quick Hit" – Clean Web.Config Files

ASP.NET 4 "Quick Hit" – Predictable Client IDs

ASP.NET 4 "Quick Hit" – Selective View State

ASP.NET 4 "Quick Hit" – The HtmlEncoder Utility Method

 

VS2010

Visual Studio 2010 "Quick Hit" – Code Search View Hierarchy

Visual Studio 2010 "Quick Hit" – IntelliSense Smart Lists

Visual Studio 2010 "Quick Hit" – Multi-Monitor Support

Visual Studio 2010 "Quick Hit" – New Web Project Template

Visual Studio 2010 "Quick Hit" – New Multi-Targeting

Visual Studio 2010 "Quick Hit" – Websites Instead of Web Projects

Visual Studio 2010 "Quick Hit" – Snippets IntelliSense

Free ASP.NET 4 and VS 2010 Beta Hosting to help you get up to FOUR !

MaximumASP

MaximumASP is offering a free hosting account so you can get started with ASP.NET 4 and Visual Studio 2010.

On this account you can test ASP.NET 4 applications in a hosting environment and try out the new publishing features with Visual Studio 2010 and the Microsoft Web Deployment Tool.

  • Windows Server 2008 R2 / IIS 7.5
  • .NET Framework 4 Beta 2
  • 1GB disk space
  • 50 MB SQL Server 2008 database
  • MS Deploy Access
  • FTP over SSL Access

The environment on which your apps will be running is a slimmed down version of our robust MaxESP platform. Experience some of the platform’s features such as instant scaling, application aware load-balancing, and the IIS Remote Manager. If you like what you see during the ASP.NET 4 beta, sign up for a full account. We would love to have you.

http://aspnet4beta.maximumasp.com/

 

Technorati Tags: Microsoft ASP.NET Beta Hosting

ASP.NET 4 / VS 2010 “Quick Hit” Videos

Now that the “Dev 2010” wave of products is in beta and we’re getting closer5 and closer to release, I‘ve started publishing “Quick Hit” videos on the new features.

These are not really tutorials (Not like the How-Do-I videos) but rather just “quick” peeks to show you the new stuff.

I’ll start working on more detailed training  after PDC.

The first 5 videos are now live:

http://www.asp.net/learn/aspnet-4-quick-hit-videos/

http://www.asp.net/learn/vs2010-quick-hit-videos/

 

Technorati Tags: Microsoft ASP.NET Visual Studio

eBook 51 Tips, Tricks and Recipes with jQuery and ASP.NET Controls

51jQueryTips

 I found this cool eBook and wanted to share it with you all since jQuery is. more and more, become a common part of the ASP.NET Development experience.

The book includes…

· 51 Tips, Tricks and Recipes with jQuery and ASP.NET Controls eBook (PDF)

· Entire Source Code of the eBook

· Cross Browser Scripts – tested on IE 7, IE 8, Firefox 3, Chrome 2, Safari 4

· Common code that runs on ASP.NET Pages, Master Pages, and in most cases, HTML pages too.

You can read the table of contents [ HERE ]

YOU can buy the ebook [ HERE ]

ASP.NET 4 Beta 2 – New Version, New Docs, New MSDN Site !

We’ve been BUSY !

ASP.NET 4.0 and Visual Studio 2010 Beta 2 was released to MSDN Subscribers earlier this week.

General availability is scheduled for tomorrow !

Read the announcement [ HERE ] with an overview about the new SKUs and features or go straight to the download [ HERE ].

Check out the new look !!!!

image_thumb_7407CD79

You’ll find the documentation at the MSN web site [ HERE ] and when you do, you’ll see that the Server & Tools On Line team has been busy improving the MSDN site experience.

WebDevDocs

 

There is a TON of new stuff and I’ve built a list of potential topics for new content that I’m building. I though it might be useful if I shared that list here so …..

DIG IN !!!

Core Services   

    Web.config File Minification   
    Extensible Output Caching   
    Auto-Start Web Applications   
    Permanently Redirecting a Page   
    The Incredible Shrinking Session State   
    Expanding the Range of Allowable URLs   
    Extensible Request Validation
    Object Caching and Object Ca