Archives

Archives / 2005 / October
  • Visual Studio 2005 Profiles and a Few Tweaks I like to Make

    One of the new features in VS 2005 is the support for “profiles” in the IDE.  Profiles provide the ability to define pre-set defaults for options, menus, key-bindings, and command-bars across the tool-set.  VS 2005 ships with several built-in profiles out of the box including: VB, C#, C++, Web, Test, and a General Development Settings similar to 2003.  When VS launches the very first time it prompts a user to pick which of these profiles to use by default (note that you can build all app types and even use all languages regardless of which profile you pick).

     

    If you ever want to change or reset your profile, you can select the Tools->Import and Export Settings menu option.  It will then walk-you through a wizard where you can export or import settings to/from others (these are saved as XML files that you can ship around to work colleagues or friends).  If you select the “reset all settings” radio button in this dialog, it will let you nuke and re-pick your default profile from scratch (for example: to re-pick the C#, VB or Web one by default).

     

    There is bound to be lots of debate as to which profile is best, and why different options are set differently in whichever profile.  The good news is that once you pick a profile, you can tweak it however you want to make it “perfect” (where perfect = what you personally think is right).

     

    I’ve seen a few common questions on forums about profile tweaks (how do I make it do xyz) that I thought I’d call out in case you were interested:

     

    Some Common Profile Tweaks and Optimizations:

     

    Enable the output window to show up on build. 

     

    By default, the C# profile doesn’t show the build output window when you start a build (instead you need to manually show it).  I personally like to see the build output window always show up so that I can better track progress (note in Web Projects it will now list each directory as it builds them – so you can quickly see which directories are getting re-built when dependencies change).  

     

    To enable this by default, select the Tools->Options menu item.  Then under Project and Solutions->General select the “Show Output Windows when Build starts” checkbox.

     

    Note that this option is enabled by default with the web profile.

     

    Show MSBuild Output Verbosity “Normal:

     

    By default, the C# and Web profiles send only “minimal” MSBuild information to the output window.  You can configure additional levels of output information by selecting the Tools->Options menu item.  Then under Project and Solutions->Build and Run you can select the MSBuild project verbosity dropdown to be: “Quiet”, “Minimal”, “Normal”, “Detailed”, and “Diagnostic”. 

     

    I personally like “Normal”, since it gives me build times for projects, and is also explicit about when/where files outputs are updated and to where.  This is very useful when you have pre/post actions and are trying to track down when they are firing and what impact they are having.

     

    Here are two samples showing the output window differences between the two settings:

     

    Minimal Output:

     

    ------ Build started: Project: ClassLibrary1, Configuration: Debug Any CPU ------

    C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Csc.exe /noconfig /nowarn:1701,1702 /errorreport:prompt /warn:4 /define:DEBUG;TRACE /reference:C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Data.dll /reference:C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.dll /reference:C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Xml.dll /debug+ /debug:full /optimize- /out:obj\Debug\ClassLibrary1.dll /target:library Class1.cs Properties\AssemblyInfo.cs

     

    Compile complete -- 0 errors, 0 warnings

    ClassLibrary1 -> C:\Documents and Settings\Scott\My Documents\Visual Studio 2005\Projects\webtest\ClassLibrary1\bin\Debug\ClassLibrary1.dll

     

    Normal Output:

     

    ------ Build started: Project: ClassLibrary1, Configuration: Debug Any CPU ------

    Build started 10/20/2005 9:24:41 PM.

    Target CoreCompile:

        C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Csc.exe /noconfig /nowarn:1701,1702 /errorreport:prompt /warn:4 /define:DEBUG;TRACE /reference:C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Data.dll /reference:C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.dll /reference:C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Xml.dll /debug+ /debug:full /optimize- /out:obj\Debug\ClassLibrary1.dll /target:library Class1.cs Properties\AssemblyInfo.cs

     

    Compile complete -- 0 errors, 0 warnings

    Target CopyFilesToOutputDirectory:

        Copying file from "obj\Debug\ClassLibrary1.dll" to "bin\Debug\ClassLibrary1.dll".

        ClassLibrary1 -> C:\Documents and Settings\Scott\My Documents\Visual Studio 2005\Projects\webtest\ClassLibrary1\bin\Debug\ClassLibrary1.dll

        Copying file from "obj\Debug\ClassLibrary1.pdb" to "bin\Debug\ClassLibrary1.pdb".

     

    Build succeeded.

     

    Time Elapsed 00:00:00.21

     

    The difference is subtle between these two settings, but I think very useful.  Notice how with the minimal output you can’t tell whether the assembly was updated (note that it won’t be updated if no changes were made to the project), whereas with normal output it is clearly called out.  Normal output also shows build-times per project.

     

    Track Active Item in Solution Explorer

     

    One feature that was on by default with VS 2003 that a lot of people find useful was the ability to see the current document icon highlighted in the solution explorer as you moved around from document to document (it will also scroll the solution explorer so that the document is in view).  This can be useful when you have deeply nested content in sub-folders and want to see the current document’s relation to others. 

     

    By default, the C# profile has this disabled, while the Web profile has this on.

     

    To enable this feature in the C# profile, select the Tools->Options menu.  Under Projects and Solutions->General select the “Track Active Item in Solution Explorer” checkbox.

     

    Build Configuration Manager Dropdown in Toolbar

     

    VS supports the concept of build configurations.  For example: you can configure different settings for “debug” and “release” configurations (which projects build, etc) – as well as define your own (for example: staging, test, deployment, etc).  Note that the new Web Deployment Project solution my team is shipping in a few weeks will let you do some really cool things with this and VS 2005 web projects (including the ability to dynamically replace configuration settings like connection-strings as part of which build configuration you pick).

     

    You can configure which configuration in VS is the “active” one by selecting the Build->Configuration Manager menu item.  This will bring up a modal Configuration Manager dialog with a drop-down to let you pick the active one.  With the C# profile applied, you can also select the current configuration via a configuration drop-down located in the standard toolbar (this makes switching really fast – and was there by default with VS 2003).  This drop-down is not present in the VB or Web profile by default.

     

    To enable it in the VB or Web profile, select the Tools->Customize menu item.  Click on the Commands tab in the dialog that comes up.  Select the “Build” item in the Categories list box, and then scroll down to the very bottom of the Command list-box where you’ll fine the “Solution Configurations” list item.  To add it into one of the IDE toolbars, you need to click it and then drag and drop it to the toolbar in the IDE location you want to add it to.  (editorial note: this completely fails the “intuitive and discoverable sniff test” – but was actually the same behavior in past versions of VS).

     

    Hope these suggestions help.  As you’ll discover as you start to wade through the options dialog, there are literally thousands of tweaks you can make. 

     

    Scott

  • Great Site Navigation,TreeView and Menu Content

    Danny Chen on the ASP.NET product team has been blogging some really great content on the new Site Navigation, TreeView and Menu features in ASP.NET 2.0.  Definitely worth checking out -- these features can save a lot of time with common web-site navigation:

  • How to add a Login, Roles and Profile system to an ASP.NET 2.0 app in only 24 lines of code

    I’ve seen a few questions in the forums lately looking for examples on how to use the CreateUserWizard control to create new users in the ASP.NET 2.0 membership system, and then as part of the registration process assign the new user into custom roles and/or collect and store custom profile properties about them (country, address, gender, zipcode, etc).

     

    Stefan from my team had a cool CreateUserWizard control sample that I borrowed and expanded upon to build-up a sample that demonstrates how to build a fairly common user management, roles and personalization system in ASP.NET 2.0 that does this.  I was pleasantly surprised to find it only took about 25 lines of C# code in the entire app. J

     

    The sample comes with 6 pages:

     

     

    Specifically it supports:

     

    1) Login support to enable registered users to login to the web app using forms auth and the new membership system (login.aspx)

    2) Registration support to enable visitors to create and register new users in the membership system (CreateNewWizard.aspx)

    3) Profile support that enables the site to gather information about the user on registration, and for the users to see that information on a profile page (MyProfile.aspx). 

    4) Change Password support to enable registered users to change their password in the membership system (ChangePassword.aspx)

    5) Password Recovery support to enable users to reset their password if they forgot them (RecoverPassword.aspx)

     

    You can download and run the sample yourself from here.  Note that it is built with the final release of VS 2005 and ASP.NET 2.0 – so it won’t work with Beta2 (although it will probably work with the RC).

     

    Implementation Notes on CreateNewWizard.aspx and MyProfile.aspx:

     

    Only two of the above pages (CreateNewWizard.aspx and MyProfile.aspx) have code in them.  The others use the built-in Login controls in V2 to-do everything (asp:login, asp:passwordrecovery, asp:changepassword). 

     

    CreateNewWizard.aspx is the most interesting page.  It uses the built-in <asp:createuserwizard> server control to-do most of the heavy lifting and has two templated wizard steps defined within the wizard:

     

    <asp:createuserwizard> wizard step 1: gathering user-account data

     

     

    The <asp:createuserwizard> control handles gathering up the user-account, email, password, and password recovery/answer data and then calling into the ASP.NET 2.0 membership system to register the new user.  You simply have to override the control’s <createuserwizardstep> template and customize the control layout to have things look how you want. 

     

    The sample is using the ASP.NET validation controls to perform client-side validation on the inputs as well within the template (example: making sure passwords match, the age is a valid integer, etc).  One added benefit in ASP.NET 2.0 is that these validation controls now support client-side validation for FireFox and other modern browsers (note: all screenshots were done using FireFox).

     

    There are then three additional properties (their country, gender and age) that I wanted to gather up about the new user as part of the registration process.  Doing this was pretty easy using the new ASP.NET 2.0 Profile system – simply add their definitions within the <profile> tag of the web.config file to register them and store their values in the new profile system:

     

    <profile enabled="true">

        <properties>

            <add name="Country" type="string"/>

            <add name="Gender" type="string"/>

            <add name="Age" type="Int32"/>

        </properties>

    </profile>

     

    I then handled the “CreatedUser” event on the CreateUserWizard control within my CreateNewWizard.aspx.cs code-behind file to retrieve the values from the controls within the CreateUserWizard control template and set them in the profile store:

     

    // CreatedUser event is called when a new user is successfully created

    public void CreateUserWizard1_CreatedUser(object sender, EventArgs e) {

     

       // Create an empty Profile for the newly created user

       ProfileCommon p = (ProfileCommon) ProfileCommon.Create(CreateUserWizard1.UserName, true);

     

       // Populate some Profile properties off of the create user wizard

       p.Country = ((DropDownList)CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("Country")).SelectedValue;

       p.Gender = ((DropDownList)CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("Gender")).SelectedValue;

       p.Age = Int32.Parse(((TextBox)CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("Age")).Text);

     

       // Save profile - must be done since we explicitly created it

       p.Save();

    }

     

    Because the user is being created as part of this step, I explicitly choose to create a new Profile object in code (note that I was passing in the CreatedUserWizard1.UserName property as the username – since the user isn’t logged into the system yet).  I then accessed the controls within the template of the <asp:createuserwizard> control, pulled out their values, and stuck them within the newly created profile.  Calling p.save at the end registered this profile with the new username.  (note: I’ll walk through how we use this profile data later in a page below).

     

    <asp:createuserwizard> wizard step 2: picking roles

     

    After the user fills out the first step of registration information and clicks the next button, the user is created, the CreatedUser event fires, and we fill in the appropriate information about the user into the profile store. 

     

    The <asp:createuserwizard> control then displays the second step template we’ve defined.  This template lists all of the roles currently created in the ASP.NET Role Management system, and allows the user to select which roles they belong to:

     

     

    Note that you’d typically never assign roles to an end-user this way (instead you’d add your own logic to somehow calculate which role they belong in), but I thought this scenario was cool nonetheless which is why it works like the sample above.

     

    I think it is cool because of the way we populate and access these roles in the template of the <asp:createuserwizard>.  Basically, we have a template definition to the .aspx like this:

     

    <asp:WizardStep runat="server" AllowReturn="False"

                    OnActivate="AssignUserToRoles_Activate"             

                    OnDeactivate="AssignUserToRoles_Deactivate">

        <table>

            <tr>

               <td>

                  Select one or more roles for the user:

               </td>

            </tr>

            <tr>

                <td>

                   <asp:ListBox ID="AvailableRoles" runat="server"

                                SelectionMode="Multiple" >

                   </asp:ListBox>

                </td>

            </tr>

        </table>

    </asp:WizardStep>

     

    It simply contains a <asp:listbox> control named “AvailableRoles”.  When this wizard step is loaded (after the user hits the next button on the first step in the wizard), it will fire the “OnActivate” event.  We can use this to databind the list of all roles in the system to the above listbox.  When the user hits next again, the wizard will fire the “OnDeactivate” event.  We can then use this to determine which roles were selected in the above listbox, and use them to update the role-manager system.

     

    The code to-do both of these actions looks like this:

     

    // Activate event fires when user hits "next" in the CreateUserWizard

    public void AssignUserToRoles_Activate(object sender, EventArgs e) {

     

        // Databind list of roles in the role manager system to listbox

        AvailableRoles.DataSource = Roles.GetAllRoles(); ;

        AvailableRoles.DataBind();

    }

     

    // Deactivate event fires when user hits "next" in the CreateUserWizard

    public void AssignUserToRoles_Deactivate(object sender, EventArgs e) {

     

        // Add user to all selected roles from the roles listbox

        for (int i = 0; i < AvailableRoles.Items.Count; i++) {

            if (AvailableRoles.Items[i].Selected == true)

               Roles.AddUserToRole(CreateUserWizard1.UserName, AvailableRoles.Items[i].Value);

        }

    }

     

    That is all of the code for the CreateNewWizard.aspx.cs file – 17 lines total if you omit comments and whitespace (if my count is right). 

     

    Next Step: Displaying User Profile Data

     

    The only other page in this scenario that required me to add code was the MyProfile.aspx page.  This page looks like this:

     

     

    The page itself was pretty simple to implement.  I simply added a few asp:label controls on the page, as well a listbox for the roles.  Populating these controls with the profile and role information involved added a Page_Load event with 7 lines of code like so:

     

    protected void Page_Load(object sender, EventArgs e) {

     

       Country.Text = Profile.Country;

       Gender.Text = Profile.Gender;

       Age.Text = Profile.Age.ToString();

     

       RoleList.DataSource = Roles.GetRolesForUser(User.Identity.Name);

       RoleList.DataBind();

    }

     

    Note that the profile object is strongly typed – which means profile properties will get statement completion and compilation checking in VS 2005 with it.  I can also then query the role management system to retrieve an array of all the roles the current user belongs to and then databind this to the listbox control. 

     

    Since the MyProfile.aspx page requires a user to be logged in (otherwise retrieving profile information about them doesn’t make a lot of sense), I also added a <location> based authorization control tag in my web.config file:

     

    <location path="MyProfile.aspx">

         

       <system.web>

          <authorization>

                <deny users="?"/>

                <allow users="*"/>

          </authorization>

       </system.web>

     

    </location>

     

    This is the same configuration I would have added in ASP.NET V1.1 – and basically tells the system to deny all users who aren’t logged in (the ? = anonymous), and then allow all users who are logged in (the * = all). 

     

    Those who aren’t logged in will get automatically re-directed to the login.aspx page.  The <asp:login> control can be used there to allow users who have already registered to log-in without the developer having to write any custom code.

     

    Summary

     

    Hopefully this walks-through a fairly common real-world web app scenario and explains how it can be easily done in ASP.NET 2.0.  The ASP.NET 2.0 Membership, Role and Profile system (especially when combined with the new login controls) pack a lot of productivity power. 

     

    What is really nice is that they are all built on the new ASP.NET 2.0 provider model.  Our of the box ASP.NET ships built-in providers that provide Membership, Roles and Profile storage inside SQL Express, SQL Server and Active Directory stores (the later for Membership and Roles only).  What is even better is that you can replace any of these implementations using a custom provider that you either buy or build yourself (see this blog post for more details on how to-do this).  Replacing a provider in ASP.NET 2.0 simply involves changing a value in a web.config file – the above code sample will work regardless of what provider was plugged in (LDAP, Oracle, DB2, Custom SQL Table Schema, File-System, etc).

     

    Hope this helps,

     

    Scott

     

  • Web Hosting Upsize Tool for SQL Express

    Brad and Polita on my team have been working on a cool tool for hosting providers that will enable developers to easily deploy and manage ASP.NET 2.0 database driven applications written using SQL Express on a hosted web-server.

     

    Once the tool is deployed by a hoster, a developer will be able to copy their ASP.NET 2.0 web application using FTP or any other file-transfer mechanism to deploy the files for the app underneath the web-root like they do content today (note: the new “Copy Web Site” tool in VS 2005 could also be used for this).  If they want they can also use the app_offline.htm trick I posted about last week to avoid people accessing their app until the site is fully deployed and the database enabled.

     

    The developer can then access the upsize tool online (it is an ASP.NET web app that hosters expose).  It allows the developer to pick the SQL Express database (typically stored in the /app_data directory) that they want to enable.  The tool then automates uploading this SQL Express database into a full-blown SQL Server database account on the back-end (note: a hoster in a shared environment would typically partition this SQL database into several hundred or a thousand different database accounts). 

     

    As part of this process the new tool will perform a “deep clean” check to verify that the database being uploaded is correct and doesn’t have any malicious things in it (something hosters worry about in shared environments).  It can then also automatically fix up connection string references within the application’s web.config file to point to the new SQL Server account location (note that VS 2005 doesn’t store connection-string settings in code anymore – and instead uses the new <connectionstring> section in .NET 2.0 to store things).

     

    After that, the ASP.NET 2.0 web application w/ SQL database should be good to go on the web.  This should hopefully be a much easier solution than what people go through today, and really enable non-access-based database development for the masses. 

     

    Thanks,

     

    Scott

     

    P.S. We are targeting to have this tool available free for hosters in the November timeframe.

  • Async Pages in ASP.NET 2.0

    One of the cool new advanced features in ASP.NET 2.0 is support for pages that execute otherwise blocking operations asynchronously.  This allows ASP.NET to re-use the worker thread while waiting for a completion (for example: calling a remote web-service and waiting for the response) and allows the server to execute much more efficiently.

  • App_Offline.htm

    Update: A newer post about this can be found here.

     

    I was planning to break the news about the little-heard-of app_offline.htm feature in ASP.NET 2.0, but Erik beat me to it. J

     

    Basically, if you place a file with this name in the root of a web application directory, ASP.NET 2.0 will shut-down the application, unload the application domain from the server, and stop processing any new incoming requests for that application.  ASP.NET will also then respond to all requests for dynamic pages in the application by sending back the content of the app_offline.htm file (for example: you might want to have a “site under construction” or “down for maintenance” message).

     

    This provides a convenient way to take down your application while you are making big changes or copying in lots of new page functionality (and you want to avoid the annoying problem of people hitting and activating your site in the middle of a content update).  It can also be a useful way to immediately unlock and unload a SQL Express or Access database whose .mdf or .mdb data files are residing in the /app_data directory.

     

    Once you remove the app_offline.htm file, the next request into the application will cause ASP.NET to load the application and app-domain again, and life will continue along as normal.

     

    Hope this helps,

     

    Scott