Silverlight Roles, Profile and Authentication Example Updated for Silverlight Beta2 Now with Visual State Manager (VSM) goodness!

I am very excited about Silverlight Beta2 shipping recently...  I took a few minutes to update my recent sample "Accessing the ASP.NET Authentication, Profile and Role Service in Silverlight" post to Beta2.  While I was at it, I thought I'd take advantage of the new Visual State Manager (VSM) feature to simplify some of the UI. 

VSM is a new Beta2 feature of Silverlight (and soon WPF) that makes it much easier to define and transition between UI states in your application.  For more information  check out Christian Schormann’s VSM blog post and this great VSM screen cast and associated demo files which I stole from... ah, I mean "leveraged" in this example. 

Download:  Silverlight Beta2 Roles, Profile and Authentication Example Code (you need all the good stuff from http://silverlight.net/GetStarted/ to play)

 

Here are a few "states" now in the application.

Not logged in:

image

Transitioning to logged in...

image

Logged in as manager:

image

It is very simple to do this in blend... You simply use the new "States" tab in Blend to define a base state (highlighted below)  and a set of transition states...

image

For example, here is the logged in state...  the pattern I am using is basically to move Xaml elements on and off the screen

image

As you can see here, in the logged in state, the controls for logging in are simply moved off the screen.

image

 

Then the source code is super simple.  The key line is the first one in each function.  This where I programmatically tell Silverlight to change what state the UI should be in.   Much better than hiding a show a bunch of controls and very designer friendly.  Now I do not need to touch my code when some aspect of the design changes. 

private void LogIn_Button_Click(object sender, RoutedEventArgs e)
{
    VisualStateManager.GoToState(this, "LoggedIn", true);
    AuthenticationServiceClient client = new AuthenticationServiceClient();
    client.LoginCompleted += new EventHandler<LoginCompletedEventArgs>(client_LoginCompleted);
    client.LoginAsync(UserName.Text, Password.Password, "", true, UserName.Text);
}

private void LogOut_Button_Click(object sender, RoutedEventArgs e)
{
    VisualStateManager.GoToState(this, "LoggedOut", true);
    WelcomeMessage.Text = "logging out..";
    AuthenticationServiceClient client = new AuthenticationServiceClient();
    client.LogoutCompleted += new EventHandler<System.ComponentModel.AsyncCompletedEventArgs>(client_LogoutCompleted);
    client.LogoutAsync();
}

 

Download:  Silverlight Beta2 Roles, Profile and Authentication Example Code (you need all the good stuff from http://silverlight.net/GetStarted/ to play).   Thanks to Hanu Kommalapati for help in porting to Silverlight beta2. 

I'd love to hear what you think!

 

Oh, while we are at it, Kathy updated her very popular controls sample page for Silverlight Beta2 as well. 

clip_image001

Silverlight Control Demo Sample
A sample of twenty-four Silverlight 2 controls that can be viewed live together with the source code used to drive the controls.

By clicking Download It you accept the license

View ItDownload It

Posted 08 June 08 08:23 by BradA | 1 Comments   
Filed under , ,
Visual Studio and .NET Framework Developer Documentation Survey

The developer focused documentation on the .NET Framework and VS is some of the best in the industry, none the less, we have all complained about it from time to time.  Now is your time to talk back!  the User Education Team has posted  a survey where they are trying to find out a few things:

    1. Your offline vs online documentation usage
    2. Opinions on sample code in the documentation
    3. How multiple versions of the framework should be shown
    4. What sorts of documentation is more important than others

Here is the pitch:

Help us improve the developer documentation by taking the Visual Studio and .NET Framework Developer Documentation Survey http://go.microsoft.com/fwlink/?LinkID=102169. This survey will give us a better understanding of the type of applications you are developing, how you use help, and how we can improve it. The survey takes only 10 minutes, and we appreciate your feedback!

Posted 05 June 08 08:27 by BradA | 4 Comments   
Managed Extensibility Framework Preview Available

A few months ago we announced that we are working on a Managed Externality Framework and there was a lot of feedback just on the announcement!   Today we posted the very first CTP of MEF.    I would love to get your feedback on this. 

Many people have noted that the industry has not yet achieved the level of code reuse the Object Oriented Design promised.  One of the reasons for this is the tight coupling that most OO systems tend allow.  Over the last few months (and for some of us, years) we have thought deeply about how we can encourage more reuse.    We believe MEF is part of the solution. 

The MEF provides developers with a framework to easily add extensibility to their applications and with minimal impact on existing code. The application developer can define extension points according to the functionality required of an extension, while the extension developer uses those points to interact with the application.
MEF enables this extensibility to take place without creating a hard dependency in either direction. Applications can be extended at run time without recompilation, and extensions can be used by multiple applications sharing the same extension requirements. MEF also allows an application to delay the loading of an extension while still examining its metadata, enabling efficient traversal of large catalogs of extensions.

There are some great samples included:

HelloWorld: A very simple example to show the concepts.   The Button's Caption is determined at runtime by what component is added.  This can be changed at runtime, and customized based on user, etc.

public MyHelloWorld()
{
    InitializeComponent();
    CompositionContainer container =
              new CompositionContainer();
    
    container.AddComponent<MefHelloWorld.MyHelloWorld>(this);
    container.AddComponent<ExampleStringProvider>(new
      ExampleStringProvider());
    
    //Alternatively, comment the above and 
    //use the DateStringProvider:

    // container.AddComponent<DateStringProvider>(new
    //               DateStringProvider());

    container.Bind();

    //theButton.Content = "Hello World!";
}
[Import("ButtonCaption")]
public String ButtonCaption
{
    get { return theButton.Content.ToString(); }
    set { theButton.Content = value; }
}

DirectoryWatching: a "Hello World" example, using Directory Watching rather than manual component insertion.  You can simply drop a DLL into a directory to enable new functionality in the app

Calculator: a stack-based calculator example..  You can add some "advanced" opperations that happen to be written in VB just by dropping the extension into a directory. 

image

You gotta have a game right??    Simply open the file menu to load some additional shapes

image

XFileExplorer: a MEF-based file explorer

Again, we'd love to have your feedback and thoughts on this very, very early preview.

TechEd2008 from your Couch

Seeing on the buzz from TechEd, I am bummed not to be there... I could not justify the trip to the image family with my big 10,343 mile trip to South Africa... 

So I get the enjoy TechEd from my couch here like many of you.  The good news is not only is there a ton of good blog traffic, but there is also TechEd Online.

There is three great clips from the Keynote today:

  • Silverlight 2 Beta 2 Announced (2 min 49 sec)
    Bill Gates announces Silverlight 2 Beta 2 and S. Somasegar demonstrates how the Crossfader application was built with Silverlight.
  • ADO.NET Distributed Cache (6 min 28 sec)
    SQL Server 2008 features including Spatial, Sync Framework and Sync Services for ADO.NET, and SQL Server Data Services.
  • Application Development, Looking Ahead(1 min 44 sec)
    Bill Gates discusses the future of application development and what to expect in the coming months.
  • Microsoft Robotics Studio Kit(2 min)
    University of Massachusetts Amherst’s Ballmer Bot takes the stage at Tech·Ed 2008.

Stay tuned to TechEd Online, as there is more to come!

Oh and if you are at TechEd, be sure to check out Kathy's talk... what a great way to end the conference! 

WUX10-TLC Tips, Tricks, and Techniques for Building a Great Microsoft Silverlight Application
Friday, June 6 4:30 PM - 5:45 PM, Blue Theater 2 
Speaker: Kathy Kam
Track: Web and User Experience
Level: 300 - Advanced

Posted 03 June 08 11:00 by BradA | 1 Comments   
Mix Essentials Event in South Africa in June

I am very excited that Joe Stagner and I will be heading to South Africa the week of June 23rd.   While banner_120x90 we are there, we will have a chance to interact with the very passionate .NET community in both Johannesburg and Cape Town. 

The South Africa Mix Essentials is an excellent chance to have a conversation about the next generation of web and designer technologies.   I hope you can make it!

Same great content, two venues: 

 

I'll be giving some very cool web technology talks while I am there including:

- Silverlight 2 (beta2!) Developer overview where I will talk about our generalal goals for Silverlight in the RIA space and walk through how to build a Silverlight application end-to-end. 

- Building Great Web Applications with ASP.NET AJAX where I will talk about some of the new AJAX\JavaScript advances in VS2008 and .NET Framework 3.5 SP1.  This will be an all-demo-no-slides sort of talk, so it will be a ton of fun!

- ASP.NET Futures including ASP.NET Dynamic Data and ASP.NET MVC

While I am there, I will also do a couple of user group events.. here is what we have locked so far:

On June 23rd, I will be talk to a local .NET users group in Johannesburg about Silverlight 2!  Thanks to Craig Nicholson for getting this setup

On June 25th, I will be talking to a local .NET Users group in Cape Town about ASP.NET MVC.  Thanks to Hilton Giesenow for getting it setup

 

I have never been to South Africa before, so any thoughts on what would be good to see while I am there?  See you there!

 

update: added the Johannesburg event, thanks Craig!

Posted 29 May 08 07:12 by BradA | 11 Comments   
Filed under , ,
Welcome to PDC08!

I can't believe it, it is PDC time again!  We are back in LA Oct 27th-30th, I hope you can make it!

You can register here: http://www.microsoftpdc.com/Registration/

Frenetic Multi Wallpaper

You can check out a very small sampling of session here: http://www.microsoftpdc.com/Agenda/Sessions.aspx

Our general theme for PDC sessions is all about super deep session that get you an under the covers look at how the developer platform really works and future looking sessions so you see and influence the future technology wave...

A few interesting things we will be talking about:

  • The Live Developer platform, including the MESH.
  • "Cloud Computing" from computation, to storage and much more!
  • "Visual Studio 10" and .NET Framework 4.0
  • ASP.NET Futures including v.next of MVC, Ajax and Dynamic data
  • Silverlight Futures, including Silverlight for business applications
  • And much, much more.

 

What would you like to see at the PDC? 

 

Posted 28 May 08 09:21 by BradA | 5 Comments   
Filed under
.NET Framework Client Profile

As I mentioned a few days ago, with .NET Framework 3.5 SP1 Beta we are taking some MAJOR steps toward making it easier for customers to acquire the .NET Framework. One of the ways we have done that is creating a client profile of the .NET Framework that includes only those parts of the framework that are relevant to client developers.  image

Several customers have asked me recently exactly what is in this subset.  Well the good news is it is a very large subset of what you need in a client application.  We profiled tons of client apps to be sure we got the right set.   But we'd also love your feedback.  Justin Van Patten has recently blogged out the official list of what is in this profile.   This includes WPF, WCF, WinForms, System.Data, etc...  Please check it out and give us your feedback.

Customers have also asked about the details of the development experience.  How do you target this profile?  How is it deployed? How does it work on different versions of Windows?  etc.   Troy Martez has done a great post that walks through all the details on targeting the .NET Framework Client Profile.  We'd love your feedback on this as well!

Enjoy!!

Posted 21 May 08 09:47 by BradA | 10 Comments   
Filed under , ,
Enhanced Mix08 Videos Posted

We recently finished the post product work required to get enhanced videos posted.  The videos not only include slides\demos, but also include a separate video stream of the speaker  so you get a deeper experience.  

Mix08 Session Overview: Building Great AJAX Applications from Scratch Using ASP.NET 3.5 and Visual Studio 2008

image

[Watch this video]

Unfortunately, this videos are not available for download, so you have to watch them on line..

Enjoy this and the rest of the sessions at http://sessions.visitmix.com/

Posted 16 May 08 09:25 by BradA | 5 Comments   
Filed under , , ,
Visual Studio 2008 and .NET Framework 3.5 "SP1" Beta

VS2008 and .NET Framework 3.5 offer a ton of customer value from Linq to Ajax and much more.  The service pack we have been working on to round out this release adds even more new value in addition to fixing a 100s of customer reported bugs!  All of it is driven by customer asks and I am excited about how we have begun to embrace a model of providing great customer value on a very regular cadence. 

Omar Khan and I recently recorded a DotNetRocks episode where we talked about all these great things.  I thought it would be fun to list just a few of my personal favorite new features in this SP...

What is your favorite one? 

For Web Developers:

- ASP.NET Dynamic Data makes building data driven web applications amazingly easy!   Now only does this work great with LinqToSql and LinqToEntities, but we can now support any OR mapping technologies.  The great folks working on LLBLGen have done the work to wire it into dynamic data.  We are also working with all the third party control vendors and they have controls on the way to work with Dynamic data. 

image

Check out the videos, podcast and reference material.

DynamicData - Main Menu  DynamicData - Product Details DynamicData - Products

- Url Routing is now built into ASP.NET!  So you can now customize your URLs in any ASP.NET application!

http://products/details/123  instead of http://products/details.aspx?id=123 
See Phil's blog for more information.

- Source code formatting for JavaScript - You can now format your javascript code in the same way you do with C# or VB.NET today.  No more spaghetti javascript!

clip_image002[9]

- Speaking of JavaScript, we significantly improved the javascript interpreter that runs behind scenes in VS and it now supports most other JavaScript frameworks giving you great intellisence. 

clip_image002

- Speaking of Ajax, we now support Ajax History server side via ScriptManager.AddHistoryPoint() as well as client side via the Microsoft Ajax Library.  This allows you to programmatically handle the "back button" and to add permalink and deeplinking support to your existing ASP.NET applications. 
Read more, watch the videos, etc.

- Also, on the subject of Ajax, we now, out of the box fully support script combining.  This support enables server side combining and therefore compression of multiple smaller JavaScript files.  This greatly reduces page load time because compression ratios are better on one larger file and one request is quicker than multiple smaller requests.  For example, take a reasonably complex Ajax application and look at how many calls are being made via FireBug

image

Now, turn on ScriptCombining in ScriptManager  and presto!

image

Read more here, see my blog from my mix talk

Also, we just released a very cool script profiling tool that can show you just what is loaded and, in exactly the format you need for ScriptManager...

<cc2:ScriptReferenceProfiler ID="ScriptReferenceProfiler1" runat="server" />

 

Visual Web Developer Express (that is the free version of VS) now supports Web Application Projects (WAP) and Class Library Projects.  This enables both ASP.NET MVC as well as Silverlight 2 development from Express!  I am relieved that I can now go back to doing all my demos in Express! 

Classic ASP development is back!  This was a very painful cut from VS2008 and I am glad it is back as many of our customers have to support older web applications.

For Client Developers

- .NET Framework Client Profile - Smaller .NET Framework Redist optimized for client scenarios

image

  1. Immediate Responsiveness - Bootstrapper is tiny (200K) to enable the fastest possible response to app setup URL.   No waiting around wondering if the click registered.  No “unpackaging” UI.  After the security prompts, the user immediately is presented with the EULA.
  2. 3 Clicks from 0 to 60 - We’ve got it down to the fewest possible number of clicks (1 for running exe, 1 for cert, 1 for eula) that are absolutely required for installing both the framework and the application.   For ClickOnce apps, the user clicks accept on the EULA and when setup completes the application and the framework is automatically launched. 
  3. Integrated, Custom/Branded UI - The framework and app as well as additional components can be packaged together so that there is a seamless install experience.  We now have a single progress bar indicates status overall.
  4. Reliable - We have poured through the error logs to debug and find root causes for setup failures... We think we are a LOT better now.  We are installing less stuff and doing it in a more solid way.
  5. Install Speed - We’re at 26.5 mb.  On a clean XP machine with a typical consumer broadband connection, the setup will take approximately 6 minutes.  On faster connections, setup will get even faster (4.5 minutes). 
  6. App first run - The app first run experience is quite nice.  Because we are ngening fully during the install, nothing is competing with the app at startup, no JITing, and bits are warm.   The user sees the setup window disappear and 3 seconds later, the app splash screen followed quickly by the app itself.  Nice.

Note: some of the above will be most noticeable in the RTM of SP1....

- Significant cold start performance wins... You will absolutely notice this with larger client applications.  

- Lots of WPF performance improvements with text, graphics, animations, etc

- WPF Effects API  which enables custom hardware accelerated effects on any control or shape in WPF.  Check out System.Windows.Effects.

- WPF Designer Event Tab Support

image

- Sort properties alphabetically

image

- Margin Snap Lines makes is way easy to do great form layout in the WPF designer

image

- Better XAML debugging.  You can now easily navigation to the offending line in your XAML file

image

- New WebBroswer Control in System.Windows.Controls 

image

<WebBrowser Source="http://blogs.msdn.com/brada" > </WebBrowser>

- A new BindingGroup in System.Windows.Data (additional databinding support)

A ton of valuable ClickOnce update

  • ClickOnce application publishers can now decide to opt out of signing and hashing the ClickOnce manifests as they see appropriate for their scenarios.

image

  • ClickOnce error dialog boxes now support links to application specific support sites on the Web
    image
  • ClickOnce applications can now be programmatically installed through a ‘Setup.exe’ while displaying a customized, branded install UX
  • Better Support for generating MSI + ClickOnce application packages
  • FireFox browser extension to support Clickonce installations using FireFox browsers
  • Design time support for setting file associations

 image

- Windows Forms get Line and Shape controls for all languages.  A new set of controls in the toolbox enable some cool shape controls for WinForms developers. 

image

- Run off a network share with local permissions - You have voted and we have listened!  We have brought managed executables in line with native code executables in how they behave when run off a network share.  Yea! 

image

For VB Developers

You can now add "XML to Schema" items to Visual Basic projects.

 

and get the great VB XML intellisense against it

 

For C# Developers

VB developers have long loved the feature of being able to get information about any sort of potential compiler error as they type.  C# developers on the other hand often have to relay on the lack of a feature (intellisence) to figure out if they are going to have a problem.  Now C# developers get clean, unobtrusive information about potential issues as they type.  A couple of examples:

clip_image002[11]

If you hover over the i in the above example it will tell you i is used before it is set.

clip_image004

if you hover over the Foo in the above example it will tell you no such method exists. 

Notice, these errors show up in the error list and are cleared automatically as you fix your code. 

All real time, as you type!  The error analysis happens at the expression level. This means that not every possible errors are caught (for example many errors outside of the method body). 

For Data Developers

Most notably we have fully plumbed SQL Server 2008 support throughout VS 2008 and .NET Framework 3.5... all the new datatypes are supported, etc.  

ADO.NET Entity Framework

The ADO.NET Entity Framework is the next evolution of ADO.NET, raising the level of abstraction at which programmers work with data, and allowing the database structure or data source to evolve without significant impact to the application code.

Rather than coding against rows and columns, the ADO.NET Entity Framework allows the definition of a higher-level Entity Data Model over your relational data, and allows developers to then program in terms of this model. Developers get to deal with the data in the shapes that make sense for the application, and those shapes are expressed in a richer vocabulary that include concepts like inheritance, complex types, and explicit relationships.

image

Use LINQ to Entities with the Entity Framework for queries that help create easy to maintain code that retrieves and works with strongly typed data objects or business entities.

image

There is a new asp:EntityFrameworkDataSource control which can be easily configured..

image

See more information on ADO.NET Entity Framework on MSDN

ADO.NET Data Services:

The Microsoft ADO.NET Data Services framework provides a first-class infrastructure for developing the next wave of dynamic Internet applications by enabling data to be exposed as REST-based data services that can be consumed by client applications (Windows Forms, WPF, ASP.NET, AJAX, Silverlight, etc.) in corporate networks and across the Internet. Easily build applications using a comprehensive set of .NET libraries and client components, accessing data through uniform URI syntax and using standard HTTP verbs to operate on the resource.  Use the Data Services client support and LINQ to program to your service through strongly typed .NET classes.

ADO.NET Data Services provides a framework to build data services for relational data sources, such as Microsoft SQL Server, MySQL, DB2, and Oracle, using the built-in support for the ADO.NET Entity Framework, or for non-relational data sources using the pluggable provider model. 

You can download the Ajax client library for Data Services here

image

image

ADO.NET 3.5 Provider Support

The list of provider writers is available on MSDN.  All up, there are 8 different companies writing 22 different providers against 14 different back end databases committed to have public availability within 3 months of RTM.    Here is a sampling:

IBM DB2 data server and Informix Dynamic Server (IDS) databases
MySQL databases
Oracle databases
PostgreSQL database versions 7.3+ and 8.x
SQLite databases
Sybase
VistaDB databases

For Service Developers:

Improvements in the areas of performance and scalability, such as:

  • Scalability increases of 5X – 10X for Web-hosted applications  in IIS7
  • Significant performance improvements in Work Flow Designer  for projects with a large number of activities.


Improvements in the area of user experience, such as:

  • Enhanced TestClient support to target a richer and broader set of WCF services, while providing the option to run the TestClient in a standalone fashion.
  • New Hosting Wizard for WCF Service projects

Improvements in the area of productivity, such as:

  • Improved Usability of DataContract Serializer, via the automatic serialization of types without the need to annotate the types with [DataContract] and [DataMember] attributes.
  • Improved Debugging in Partial Trust by adding support for accessing Event Logs when running Partial Trust
  • Improvements in REST capabilities of WCF by making it easier to use the UriTemplate feature, adding support to specify defaults and providing greater control over the UriTemplate.  The addition of the ServiceDocuments object model now allows easier publishing of APP metadata and easier consumption of service document for REST clients

Improvements in the area of data platform, such as:

  • Support Entity Fx entities in WCF contracts

Support for renaming Services in VS - if you invoke Rename on a WCF Service VS will rename all of the artifacts associated with that service (config, .svc file, etc.). 

image image image

         <service behaviorConfiguration="WebApplication7.Service1Behavior"
              name="WebApplication7.CoolNewService">

In Closing

I hope you are as excited as I am about SP1 and you go download the beta and let us know what you think!  The window is really tight for feedback, so anything you can get us soon would help.  I am particularly interested in compat issues... as this is an SP, we are working hard to ensure it works with all apps.     As this is an SP, it does update core parts of the tools and runtime stack, so I would NOT recommend installing on your production machine until the final RTM later this year.  Rather use a VPC our test machine (that is what I am doing now).   Related to this, there is a known issue that the Silverlight 2 tooling will not work with SP1 beta... we are fixing that for SP1 RTM of course, but it is a short term issues. 

Download links:

Update (5-14): Visual Studio 2008 SP1 Beta Resets Settings to Defaults

We recently found a bug with the VS2008 SP1 install... when installing Visual Studio 2008 SP1 Beta on top of Visual Studio 2008, VS user settings are reset to default VS settings.  This bug is caused by code originally put in place to reset settings when upgrading minor version of VS, for example from VS Beta1 to VS Beta2 so that VS would have the latest default profile settings.  VS does migrate settings from VS 2005 to VS 2008.  VS certainly should keep user settings when upgrading to a service pack, which will be fixed for SP1.

Please backup your VS settings before upgrading to VS 2008 SP1 Beta.

Before installing SP1 Beta1, use the "Export Settings" wizard (“Tools” menu, “Import and Export Settings…”) to save your current settings, then install SP1 Beta1, and then use the wizard to import your settings back into VS.

This issue will be resolved for the final release of Visual Studio 2008 SP1 where settings will be maintained when upgrading.

We sincerely apologize for the troubles this has caused

Posted 05 May 08 10:12 by BradA | 52 Comments   
Accessing the ASP.NET Authentication, Profile and Role Service in Silverlight

In ASP.NET 2.0, we introduced a very powerful set of application services in ASP.NET (Membership, Roles and profile).  In 3.5 we created a client library for accessing them from Ajax and .NET Clients and exposed them via WCF web services.    For more information on the base level ASP.NET appservices that this walk through is based on, please see Stefan Schackow excellent book Professional ASP.NET 2.0 Security, Membership, and Role Management.

In this tutorial I will walk you through how to access the WCF application services from a directly from the Silverlight client.  This works super well if you have a site that is already using the ASP.NET application services and you just need to access them from a Silverlight client.    (Special thanks to Helen for a good chunk of this implantation)

Here is what I plan to show:

1. Login\Logout
2. Save personalization settings
3. Enable custom UI based on a user's role (for example, manager or employee)
4. A custom log-in control to make the UI a bit cleaner

image

You can download the completed sample solution

 

 

Part I: Login\Logout

In VS, do File\New select the Silverlight solution.  Let's call it "ApplicationServicesDemo".

image

We will need both the client side Silverlight project and the ASP.NET serverside project. 

image

 

Let's configure our system with the test users.  To do this we will use the ASP.NET Configuration Manager.  In VS, under the Website menu, select "ASP.NET Configuration". Use this application to add a couple of users.  I created two employees:

ID:manager
password:manager!
and
ID:employee
password:employee!

image

 

To expose the ASP.NET Authentication system, let's add a new WCF service.  Because we are just going to point this at the default one that ships with ASP.NET, we don't need any code behind, so the easiest thing to do is to add a new Text File.  In the ASP.NET website, Add New Item, select Text File  and call it "AuthenticationService.svc"

image

Add this one line as the contents of the file.  This wires it up to the implementation that ships as part of ASP.NET.

<%@ ServiceHost Language="C#" Service="System.Web.ApplicationServices.AuthenticationService" %>


Now in Web.config, we need to add the WCF magic to turn the service on.

  <system.serviceModel>
    <services>
      <!-- this enables the WCF AuthenticationService endpoint -->
      <service name="System.Web.ApplicationServices.AuthenticationService"
               behaviorConfiguration="AuthenticationServiceTypeBehaviors">
        <endpoint contract="System.Web.ApplicationServices.AuthenticationService"
                  binding="basicHttpBinding" bindingConfiguration="userHttp"
                  bindingNamespace="http://asp.net/ApplicationServices/v200"/>
      </service>

    </services>
    <bindings>
      <basicHttpBinding>
        <binding name="userHttp">
          <!-- this is for demo only. Https/Transport security is recommended -->
          <security mode="None"/>
        </binding>
      </basicHttpBinding>
    </bindings>
    <behaviors>
      <serviceBehaviors>
        <behavior name="AuthenticationServiceTypeBehaviors">
          <serviceMetadata httpGetEnabled="true"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <!-- this is needed since this service is only supported with HTTP protocol -->
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
  </system.serviceModel>

Now, still in Web.config, we need to enable forms authentication.  Under the <system.web> change the authentication mode from "Windows" to "Forms".

<authentication mode="Forms" />

 

One last change to web.config, we need to enable authentication to be exposed via the web service.This is done by adding a System.Web.Extensions section.

  <system.web.extensions>
    <scripting>
      <webServices>
        <authenticationService enabled="true" requireSSL="false"/>
      </webServices>
    </scripting>
  </system.web.extensions>

 


Now, to consume this authentication service in Silverlight, let's open the page.xaml file and add some initial UI. Just buttons to log "employee" and "manager"  in and a textblock to show some status. 

    <Grid x:Name="LayoutRoot" Background="White">
        <StackPanel>
            <Button x:Name="employeeLogIn" 
                    Width="100" Height="50" 
                    Content="Log In Employee" 
                    Click="employeeLogIn_Click"></Button>
            <Button x:Name="managerLogIn" 
                    Width="100" Height="50" 
                    Content="Log In Manager" 
                    Click="managerLogIn_Click"></Button>
            <TextBlock x:Name="statusText"></TextBlock>
        </StackPanel>
    </Grid>


Now, let's add a reference to the service we just created

Right click on the Silverlight project and select Add Service Reference

image

Click Discover and set the namespace to "AuthenticationService"

image

If you get an error at this point, it is likely something wrong with your AuthenticationService.svc or the web config, go back and double check those. 

 

Now, let's write a little code to call that service to log us in.  First add the right using statement

using ApplicationServicesDemo.AuthenticationServices;

Then, in employeeLogIn_Click method write the code to call the service to log the employee in.  For now, we will hard code the name in password, but by the end we will be prompting the user to get this data.

First we create a the web services client class, then we call the login method asynchronously.  Remember all network calls in Silverlight are async, otherwise we'd lock up the whole browser.  Finally we sign up for the callback.

private void employeeLogIn_Click(object sender, RoutedEventArgs e)
{
    AuthenticationServiceClient client = new AuthenticationServiceClient();
    client.LoginAsync("employee", "employee!", "", true, "employee");
    client.LoginCompleted += new EventHandler<LoginCompletedEventArgs>(client_LoginCompleted);
}

In the callback, for now, let's just set our status.

void client_LoginCompleted(object sender, LoginCompletedEventArgs e)
{
    if (e.Error != null) statusText.Text = e.Error.ToString();
    else statusText.Text = e.UserState + " logged In result:" + e.Result;
}

Run it!  You should see a good status.  Try changing the password and ID, and see the status change to false.  It is working.

image

Now do the same thing for manager and you are set!

 

private void managerLogIn_Click(object sender, RoutedEventArgs e)
{
    AuthenticationServiceClient client = new AuthenticationServiceClient();
    client.LoginCompleted += new EventHandler<LoginCompletedEventArgs>(client_LoginCompleted);
    client.LoginAsync("manager", "manager!", "", true, "manager");
}

Part 2: Save Personalization Settings

In this part I will show how to leverage the ASP.NET profile system to store and retrieve data tied to a particular user.  The beautiful thing about this is there is no explicit database configuration required.

First, let's go back to the ASP.NET server project and add the ProfileService.svc.  The easiest way to do this might be to copy the AuthenticationService.svc change the file name and then change the contents as show below. 

<%@ ServiceHost Language="C#" Service="System.Web.ApplicationServices.ProfileService" %>

Now, we need to enable the service via WCF configuration in web.config.  This looks just like the config for the prfofile service.  In the system.serviceModel\services section add a new node.

      <!-- this enables the WCF ProfileService endpoint -->
      <service name="System.Web.ApplicationServices.ProfileService"
               behaviorConfiguration="ProfileServiceTypeBehaviors">
        <endpoint contract="System.Web.ApplicationServices.ProfileService"
                  binding="basicHttpBinding" bindingConfiguration="userHttp"
                  bindingNamespace="http://asp.net/ApplicationServices/v200"/>
      </service>

and in the system.serviceModel\behaviors\serviceBehaviors add a new node

        <behavior name="ProfileServiceTypeBehaviors">
          <serviceMetadata httpGetEnabled="true"/>
        </behavior>


Now we need to configure the profile system.  Again, in web.config add a section listing all the profile properties.  In the System.web section, add the following node.

    <profile>
      <properties>
        <add name="Color" type="string" defaultValue="Red" />
      </properties>
    </profile>

 

Now we need to enable profile service to be accessed from the webservice. To do this, add the following node to the system.web.extensions\scripting\webservices section.

        <profileService enabled="true" 
                        readAccessProperties="Color" 
                        writeAccessProperties="Color"/>

Now, let's go to the Silverlight client and add a reference to this service.  This is the same as we did authentication service. Add Service Reference, Discover and select the profileService. 

image

Now, we need to add a little UI to the page.xaml in order to give us a way to view and edit the personalized setting.

            <StackPanel Orientation="Horizontal" HorizontalAlignment="Center">
                <TextBlock>Favorite Color: </TextBlock>
                <TextBox x:Name="colorNameBox" Width="100" Height="25"></TextBox>
                <Button x:Name="submitButton" Width="50" Height="25" 
                        Content="submit" Click="submitButton_Click">
</
Button> </StackPanel>

Now, let's extend loginComplete to retrieve all the profile properties for the user that just logged in.   Again, we need to do that asynchronously so we don't block the browser.

void client_LoginCompleted(object sender, LoginCompletedEventArgs e)
{
    if (e.Error != null) statusText.Text = e.Error.ToString();
    else
    {
        statusText.Text = e.UserState + " logged In result:" + e.Result;
        ProfileServiceClient client = new ProfileServiceClient();
        client.GetAllPropertiesForCurrentUserAsync(false);
        client.GetAllPropertiesForCurrentUserCompleted += new EventHandler<GetAllPropertiesForCurrentUserCompletedEventArgs>(client_GetAllPropertiesForCurrentUserCompleted);
    }
}

When we get the property values back, we just set the LayoutRoot to have that background.

void client_GetAllPropertiesForCurrentUserCompleted(object sender, GetAllPropertiesForCurrentUserCompletedEventArgs e)
{
    if (e.Error == null)
    {
        colorNameBox.Text = e.Result["Color"];
        ChangeBackgroundColor(e.Result["Color"]);
    }
}

private void ChangeBackgroundColor(string colorName)
{
    SolidColorBrush brush = new SolidColorBrush();
    switch (colorName.ToLower())
    {
        case "black":
            brush.Color = Colors.Black;
            break;
        case "blue":
            brush.Color = Colors.Blue;
            break;
        case "brown":
            brush.Color = Colors.Brown;
            break;
        case "green":
            brush.Color = Colors.Green;
            break;
        case "orange":
            brush.Color = Colors.Orange;
            break;
        case "purple":
            brush.Color = Colors.Purple;
            break;
        case "yellow":
            brush.Color = Colors.Yellow;
            break;
        case "red":
            brush.Color = Colors.Red;
            break;
        case "white":
        default:
            brush.Color = Colors.White;
            break;
    }
    LayoutRoot.Background = brush;
}

Finally, when the submit button is pressed we need to set the value on the server.. for completeness, I show waiting until the result comes back from the server before setting the background locally. 

private void submitButton_Click(object sender, RoutedEventArgs e)
{
    ProfileServiceClient client = new ProfileServiceClient();
    Dictionary<string, object> properites = new Dictionary<string,object>();
    properites.Add("Color",colorNameBox.Text);
    client.SetPropertiesForCurrentUserAsync(properites, false, properites);
    client.SetPropertiesForCurrentUserCompleted += new EventHandler<SetPropertiesForCurrentUserCompletedEventArgs>(client_SetPropertiesForCurrentUserCompleted);
}

void client_SetPropertiesForCurrentUserCompleted(object sender, SetPropertiesForCurrentUserCompletedEventArgs e)
{
    Dictionary<string, object> properites = e.UserState as Dictionary<string, object>;
    ChangeBackgroundColor((string)properites["Color"]);
}

 

The end result looks good!  Notice the employee and the manager can each have different values for color. 

image

image

 

Part 3. Enable Custom UI Based on a User's Role

In this section, we want to customize the UI to display differently based on the users role. 

To start off, let's go back to the websites management tool (WebSite\ASP.NET Configuration) and setup a "Management" role and add our "manager" user in that role.

image

image

Now we follow the same three step pattern as all the other services. 

First, we add the service, this time called RoleService.svc with the following contents

<%@ ServiceHost Language="C#" Service="System.Web.ApplicationServices.RoleService" %>

Then add enable this service via WCF in web.config:

      <!-- this enables the WCF RoleService endpoint -->
      <service name="System.Web.ApplicationServices.RoleService"
               behaviorConfiguration="RoleServiceTypeBehaviors">
        <endpoint contract="System.Web.ApplicationServices.RoleService"
                  binding="basicHttpBinding" bindingConfiguration="userHttp"
                  bindingNamespace="http://asp.net/ApplicationServices/v200"/>
      </service>
and
        <behavior name="RoleServiceTypeBehaviors">
          <serviceMetadata httpGetEnabled="true"/>
        </behavior>
      </serviceBehaviors>

Then we need to enable the roles service for this site.  In web.config, under system.web add:

<roleManager enabled="true"/>

Final change to web.config, we expose it via web services in web.config under System.web.extensions\scripting\webServices add:

        <roleService enabled="true"/>

 

Now, we just need to consume this on the client.  Add Service Reference\Discover, select the role service

image

Now, let's add some UI tweaks.  In this case I am going to add an image that will change based on the role of the user logged in.   So to do that, I add a image tag to the page.xaml

            <Image x:Name="roleImage" Source="notLoggedIn.jpg" Width="200"></Image>

Then, I need to go in and add to what happens with the user logs in... We need to go and see what roles they are in.  So we add the following code to client_LoginCompleted(). 

if (e.Result == true) { // if log in successful
    RoleServiceClient roleClient = new RoleServiceClient();
    roleClient.GetRolesForCurrentUserAsync();
    roleClient.GetRolesForCurrentUserCompleted += new EventHandler<GetRolesForCurrentUserCompletedEventArgs>(roleClient_GetRolesForCurrentUserCompleted);
}

and when the callback comes back, we chose the right image based on the roles of the user that logged in.

void roleClient_GetRolesForCurrentUserCompleted(object sender, GetRolesForCurrentUserCompletedEventArgs e)
{
    if (e.Result.Contains("Management"))
    {
        roleImage.Source = new BitmapImage(new Uri("bossRole.jpg", UriKind.Relative));
    }
    else
    {
        roleImage.Source = new BitmapImage(new Uri("employee.jpg", UriKind.Relative));
    }
}
 

Now you can run it and see the results!

 

Not logged in

image

Management role:

image

Logged in, but not in a management role:

image

 

Part 4. A Custom log-in control

A developer on my team built a very cool little log in control that makes it easier to log in.  So let's replace the lame test buttons we have been using with this new log-in control.

Add the LoginControl project to your solution

image

Add a project reference from the silverlight project to the LogIn controls project

image

Add the xmlns:my tag for the login control

image

Then, remove the manager login and employee login buttons and replace them with

            <my:Login x:Name="loginControl" 
                      LoginClick="loginControl_LoginClick"
                      LogoutClick="loginControl_LogoutClick"
                      ></my:Login>

The implementing of loginClick is very easy.  It uses the login_Complete we have already written above.

private void loginControl_LoginClick(object sender, RoutedEventArgs e)
{
    AuthenticationServiceClient client = new AuthenticationServiceClient();
    client.LoginCompleted += new EventHandler<LoginCompletedEventArgs>(client_LoginCompleted);
    client.LoginAsync(loginControl.UserName, loginControl.Password, "", true, loginControl.UserName);
}

Notice we also add logout for completion. 

private void Login_LogoutClick(object sender, RoutedEventArgs e)
{
    ServiceReference1.AuthenticationServiceClient client = new ServiceReference1.AuthenticationServiceClient();
    client.LogoutAsync();
    client.LogoutCompleted += new EventHandler<System.ComponentModel.AsyncCompletedEventArgs>(client_LogoutCompleted);
}

void client_LogoutCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
{
    loginControl.IsLoggedIn = false;
    statusText.Text = "Logged out";
    ChangeBackgroundColor("white");
    roleImage.Source = new BitmapImage(new Uri("notLoggedIn.jpg", UriKind.Relative));
    colorNameBox.Text = "";
loginControl.ClearPassword(); }

 

Now we are done!  you can log in and out as any user.  have fun!

 

image

image

 

You can download the completed sample solution

Posted 03 May 08 04:40 by BradA | 36 Comments   
Check out popfly game creator

The Popfly guys are at it again.  They just launched a very cool game creator tool that lets normal people create great Silverlight based games.  The RIA development experience is very slick and I can't wait to see the games people create!

Check it out at Popfly.com and John's post.

 

 

popflybreakout

Posted 01 May 08 09:05 by BradA | 2 Comments   
Filed under
Job Openings Working on the .NET Framework Product Team

The single biggest factor for success on any project I have been apart of in the last 10 years at Microsoft is the people.  In a business like ours where intellectual capital is the biggest asset, hiring and growing people is an extremely important task. 

I have gathered some details on a few positions working on the .NET Framework product team, if you are interested  please click on the link and apply... If you know someone who would be just prefect for the job, please send them a link!

A few general tips for folks interested:

  1. Know what you want to do, but be flexible.  We typically hires for a specific role on a specific team.  The system is geared to work that, so if you have some solid ideas on what you'd like to get more information on that helps a lot.  During the interview process, if it becomes clear you'll be a better fit for a different position we will suggest that you. 
  2. Specific knowledge of .NET is not required.  By and large we don't hire for specific skills.  We hire for passion, smarts and the drive to get things done.  If you have those attributes, my feeling is that you can learn the details of .NET.   In fact, I think it is a plus if a candidate as deep experience in related technologies in the industry. 
  3. Follow your passions. The best way to succeed at Microsoft is to do something you are passion about.  That passion could be about the life changing technology you are working hard to bring out to customers, it could be people you get to work with on a day to day biases, it could be about the way we do development.  Whatever your passion is, find the position that best helps you follow it!
  4. A few details...For most jobs, we do consider international candidates, so please go ahead and apply!  For these jobs we do need you to relocate to sunny Redmond, WA.  We aren't looking for contractors or work-for-hire for any of these, we are looking for folks that want to make a career at Microsoft.

 

Program Manager Jobs

These are job openings on my team.  Read my past few "PM tips".. chances are if they resonate with you you could be a fit.   For both of these are are looking for senior folks...  people with 5+ years of industry experience and of course a passion for these spaces is very important.

Managed Extensibility Framework PM

We are looking for a someone to drive the release and design of the very recently announced Managed Extensibility Framework.  Our high level goal is to evolve the state of the art of component development.  If you know what DI, IoC and TDD\BDD are that is a good first step!  We have some big customers internally and lots of interest already externally.  Please see Krys's blog for more details and apply on line

Core ASP.NET Feature PM

ASP.NET runs a large chunk of the web today and there are some very exciting plans for what we can do to make it even better in the future.  If the day in the life of a ASP.NET PM sounds like your prefect day at work, then apply on line.

 

Software Development in Test

SDETs on our team are talented application developers and testers.  Our products (ASP.NET, ASP.NET AJAX, Silverlight 2, and Windows Forms) are focused on developer technologies and are first-class frameworks.  SDETs on our team are successful by representing the customer, participating in product design, and innovating in the test space.  SDETs are often the very first people that get to build applications with new technology that comes out.  They thrive on finding design and implementation issues early in the cycle and ensuring the customers have an excellent experience with the product. Apply on line.

Test Manager

For the ASP.NET Test Manager, we’re looking for someone who can manage a strong team of 25+ technical SDET’s to deliver the next generation web application platform.  Successful candidates are those that have experience shipping multiple products and can advance the state of the art of software testing. Apply on line

 

ASP.NET Developer

As you likely know AJAX development is becoming increasingly important.  We have some great plans for what is coming in the future of the Microsoft Ajax Library (part of ASP.NET AJAX) and we'd love to have your help in making it happen.  Of course you can work on any of the other tons of Ajax libraries out there, but only at Microsoft can you work on the Ajax framework that will be the best tooled, best server integrated, best supported and most used!   Apply on line

 

Other Positions:

Also, related my good buddy Doug Purdy has some very cool sounding positions open on his team as well:

Emacs.Net
New Languages & Compilers

 

Please apply on line for any of these positions or drop me an email if you have specific questions. 

Posted 30 April 08 09:46 by BradA | 13 Comments   
Reusable WPF Transitions Project is live!

Jared Bienz has been working on getting some cool WPF transitions code posted to codeplex.  The project, Transitionals, is now live!

Transitionals is a framework for building and using WPF transitions which provide an easy way to switch between UI views in a rich and animated way. Think of transitions for applications in the same way you think of transitions for video editing. Wipe, Cut, Dissolve, Star, Blinds and 3D Rotating Cube are all examples of transitions supported by the Transitionals framework.
The best way to get started with the Transitionals framework is to download and take a look at the TransitionalsHelp file. You can find it on the Releases tab and it includes a pretty comprehensive Getting Started guide. You can also download the binary archive which includes two sample projects. Transitionals is compiled in Visual Studio 2008 against .Net Framework 3.5.

clip_image001

Posted 29 April 08 12:33 by BradA | 2 Comments   
Filed under
Managed Extensibility Framework

Krzysztof recently announced on his blog that we have begun working on an extensibility framework for .NET..

 

We will blog more details about MEF in the upcoming months, but here are some early details (subject to changes, of course): MEF is a set of features referred in the academic community and in the industry as a Naming and Activation Service (returns an object given a “name”), Dependency Injection (DI) framework, and a Structural Type System (duck typing). These technologies (and other like System.AddIn) together are intended to enable the world of what we call Open and Dynamic Applications, i.e. make it easier and cheaper to build extensible applications and extensions.

[....]

And finally here is some code showing basic scenarios our framework supports:

Creating an Extension Point in an Application:

public class HelloWorld {

  [Import] // import declares what a component needs
  public OutputDevice Output;

  public void SayIt() {
        Output.WriteLine("Hello World");
  }
}

// Extension 
public abstract class OutputDevice {
  void WriteLine(string output){}
}

1. Creating an Extension

[Export(typeof(OutputDevice))] // export declared what a component gives
public class CustomOutput : OutputDevice {
  public void WriteLine(string output) {
    Console.WriteLine(output);
  }
}

 

2. Magic that makes composes (DIs) the application with the extensions.

var domain = new ComponentDomain();
var hello = new HelloWorld();
// of course this can be implicit
domain.AddComponent(hello); 
domain.AddComponent(new CustomOutput());
 
domain.Bind(); // bind matches the needs to gives
hello.SayIt();

We'd love to hear what you think.. please join the discussion on Kry's blog.

Posted 28 April 08 06:14 by BradA | 3 Comments   
Filed under ,
Where should the ASP.NET team release stuff?

One of the things I love about working on the ASP.NET team is that the team is very focused on getting customer feedback. One of the ways we do this we need to ship bits early and often.   While I think this is great, it does present some challenges in terms of helping customers find the right bits for their need.

Scott Galloway has been doing some thinking about this and has a good conversation over on his blog.  I encourage you to chime in!

Where should the ASP.NET team release stuff?

Posted 26 April 08 08:39 by BradA | 2 Comments   
Filed under
More Posts Next page »

Search

Go

This Blog

Syndication

Page view tracker