Quantcast
Channel: Category Name
Viewing all 10804 articles
Browse latest View live

Course Manager VS 2012 Sample Part 1 – Introduction (Andy Kung)

$
0
0

When we released Visual Studio LightSwitch 2011 last year, we published a sample project called “Course Manager.” We also wrote a series of tutorials based on the sample. With the release of Visual Studio 2012, it is a good time to update the Course Manager tutorials and highlight some of the new features.

Course Manager is designed for the Office of Registrar of a fictional art school. It tracks students, instructors, courses, enrollments, etc. Office staffs can use Course Manager to browse course catalog, create new students, and register courses for existing students. Course Manager is aimed to showcase what you can achieve with LightSwitch out-of-the-box. It demonstrates how you can customize on top of the intelligent defaults LightSwitch gives you to suit your business needs and workflows.

In this introductory post, we will focus on learning what Course Manager does from the end-user’s perspective. We will walk through some basic user scenarios and features. We will publish a series of supplement posts to go into development details.

Run the Sample

Before we start, make sure you have Visual Studio 2012 Professional, Premium, or Ultimate properly installed. Course Manager is available in both VB and C#. You can download the projects from MSDN Code Sample Gallery:

Download the LightSwitch HTML Client Preview 

LightSwitch Course Manager End-to-End Application (Visual Studio 2012)

Unzip the project file, double click on the solution to launch Visual Studio LightSwitch. After the project is loaded, hit F5 to run the application!

clip_image002

Home Screen

Course Manager now launches and shows the home screen. The first thing you will notice is that Course Manager is a Desktop application with Windows authentication. You can see your name displayed on the upper right corner of the application. The application displays a logo on top, title, welcome text (with different font styles), and some entry points (with big pretty icons) to common screens. Since you (as the developer) are in debug mode, you also have access to all the permission-based screens, such as the screens under “Administration” menu group.

clip_image004

You might have noticed the look-and-feel of a LightSwitch application is different in Visual Studio 2012. In this release, LightSwitch comes with an additional shell/theme that provides a modern and immersive UI. A developer can, however, choose to use the Office-like shell/theme we shipped in version 1.

Browse Course Catalog

A student may call the office and ask for information about a particular course. A staff needs to be able to quickly find the course the student is looking and answer questions about availability, instructors, meeting times, etc.

To browse the course catalog, open “Course Catalog” screen from the menu. This screen shows a list of course sections. A course can have many sections (ie. Basic Drawing course is offered at 2 different time slots). A student can enroll in a course section. Each section has a maximum enrollment number allowed. The remaining space is calculated based on the current enrollments. You can filter this list by selecting a course category from the auto-complete box. Clicking on the Title link will take you to the details screen for the section. Clicking on the Instructor link will take you to the details screen for the instructor.

clip_image006

Create a Student

Say somebody really likes a course the school is offering, but has never taken courses at the school before. We need a screen to allow the office staff to add a new student record to the database before registering the course for the student.

To create a student, open “Create New Student” screen from the menu. Provide a student photo and fill out the student information. Click Save.

clip_image008

After the data is saved, the details screen for the student will appear. We can now register a course for the student. To do so, click “Register Course” button.

clip_image010

Register Course

If you open “Register Course” screen from the menu, the registration screen requires you to select a student and a course in order to create an enrollment. Since we launch the same “Register Course” screen from a student details screen, the student field is pre-selected for you. All we need to do now is to pick a course to register.

clip_image012

Click on the picker for “Select a course section” to see a list of available courses this student has not yet enrolled in. If you have selected the Academic Year/Quarter via the auto-complete boxes, the section list will be further filtered down accordingly.

Pick a course and click Save. Registration screen will close and you’re back to the student details screen. Click the refresh button on the enrollment grid to see the newly added course.

clip_image014

Find a Student

Last but not least, imagine an existing student calls to change the mailing address. A staff needs to find the student record quickly and update the information.

To search for a student record, open “Search Students” screen from the menu. Use the search box to find a student by last name. Click on the student link to open the student details screen.

clip_image016

This is the same student details screen we saw earlier but for a different student. Notice the name of the screen tab is based on the student name. This is very useful if you have multiple student records open at the same time.

We can go ahead and update the address on the screen. You can also find student’s registered courses shown at the bottom. You can filter the list by Academic Year and Academic Quarter. You can also add or remove an enrollment by clicking “Register Course” (as we saw earlier) or “Drop Course” (it will prompt for confirmation) button on the grid.

clip_image018

What’s Next?

We went over some basic user scenarios and workflows. By all means, this is a very simple application. Surely a real-world course registration system will be many times more complex. But believe it or not, this application covers many LightSwitch features that you will often use to build your fancy applications! On top of my head, this sample covers:

  • Create summary and calculated field for a table
  • Create permissions and enable authentications
  • Create many-to-many relationships and UI
  • Write middle-tier logic and validation
  • Add static images and text with different font styles
  • Create screen parameters and parameterized queries
  • Customize screens and work with different layouts

Over the next week, we will publish supplemental walkthroughs on different parts of the sample. So stay tuned! Some topics have already been covered by other posts, in which case, we will highlight and reference them. If you are particularly interested in a topic we haven’t covered, please let us know and we can prioritize accordingly.

I hope you’re motivated to find out how to build Course Manager and anxious to learn more behind-the-scene tips and tricks!

Coming up next: Course Manager Sample Part 2 – Setting up Data

-andy


Silverlight Show: Windows 8 and the future of XAML Part 7: The application lifecycle of Windows 8 applications

$
0
0

In the previous articles of this series, we have touched on quite a few important aspects of Windows 8 application development. In part 6, we looked at tiles. We saw that live tiles are a way of allowing your application to displaying up-to-date information to the end-user while it’s not running. A valid question that I often get is: why isn’t the application running? We’ve had the multi-tasking paradigm for many years now and it’s something we as developers take for granted.

Windows 8 breaks with this “tradition”: a new type of application lifecycle is introduced in Windows 8, entirely managed by the operating system itself. However, it has several places where we as developers need to hook into to build great experiences for our users.

In this article, we’ll take a look at the options we have to manage how our application behaves in combination with the new application lifecycle management. We’ll take a look at executing code in the background as well.

The code for this article can be downloaded here.

Read more…

Testing Windows 8 apps using Visual Studio 2012

$
0
0

As we continue to innovate on the operating system platform with Windows 8, we also enhanced the toolset available in Visual Studio to increase your productivity in testing your Windows 8 apps. Ensuring a top notch quality of your app in this new modern OS environment through thoughtful design and testing will help increase the success of your app. In a previous blog post on Testing Metro style apps in Windows 8, we highlighted some of the key areas you need to take into account for building a high quality Windows 8 app. In this post, we explore a few capabilities in Visual Studio 2012 that will make the testing and verification of your app easier.

How does my app look on Windows 8 devices?

While the success of any app hinges on the value it offers to its customers, an app that follows Windows 8 design guideline to provide a polished look and feel will delight the end users. To reduce your reliance on physical devices to verify the app’s user experience, Visual Studio 2012 provides a simulator so you don’t have to connect to a tablet device all the time during development. The simulator also reduces your need to have physical devices of every form factor at your disposal for testing. Your testing benefits in these areas where the simulator enables quick and convenient verification of your apps’ look and feel with just a few mouse clicks:

Visual Studio simulator displaying the Windows 8 start screenFigure 1. Visual Studio simulator displaying the Windows 8 start screen.

Windows 8 apps run on devices of multiple form factors. To help you test your app’s behavior in different screen sizes and resolutions, Visual Studio simulator provides 7 most common combinations of those two factors that cover from the minimum supported resolution to a 27” desktop monitor. Figure 1 illustrates an example of Windows 8 start screen shown in the simulator at the default resolution of 1366x768 and screen size of 10.6”. One of the first things to verify is that at all times the layout of your app is not clipped or misaligned vertically or horizontally at lower resolutions. On the other hand, you don’t want the app to leave a large amount of blank space at higher resolutions either. If your app’s layout extends beyond the screen, the scroll bar should show up appropriately if a user is interacting with the app using a mouse. These are examples of the type of verification you can easily accomplish by changing the simulated resolutions on the fly in the simulator and visually examining the behavior of the app.

If your app uses a fixed layout, you need to test whether it scales correctly to fill the screens of large sizes and make sure all the visual elements also scale proportionally. If your app has an adaptive layout, the simulator allows you to quickly verify that the app’s visual elements are dynamically rearranged as you intended when screen size or resolution changes.

The simulator can be rotated or flipped to see how your app behaves when a user changes the orientation of the screen. This comes in handy if you want to test such an app to see if it is correctly optimized for the portrait mode and the landscape mode. The simulator doesn’t eliminate the need to fully verify the app on physical devices, because it doesn’t simulate all the accelerometer sensitive capabilities such as tilt, but it will save you a lot of time in exposing potential problems in your app’s response to the changing of the orientation of the displaying device.

How does my app respond to touch on Windows 8 devices?

The simulator allows you to interact with your app using mouse or using simulated touch on your development computer. The latter is particularly handy if you don’t have a touch-capable device available for testing. Swipe, pinch to zoom and rotation gestures are all supported.

You typically launch your app in the simulator directly from within the Visual Studio through the debugging action. After the app is launched, the simulator stays running, which allows you to also exercise the app outside of the debugging context. For example, you can watch the activation behavior when a user taps your app’s tile or the termination behavior when a user swipes from the top to the bottom of the screen. You can take advantage of the touch gestures that the simulator provides to perform these actions and all the touch related testing and verification. Testing Metro style apps in Windows 8 has a detailed list of testing considerations related to touch. Refer to the Touch section in that blog post. If you want to learn more about the Visual Studio Simulator such as how to use the touch emulation, take a look at Running Windows Metro style apps in the simulator.

Unit testing your Windows 8 apps

The ability to unit test your code is an important aspect of any development cycle. Unit test support has been shipping in Visual Studio for several releases. In Visual Studio 2012, we have streamlined the user experience with a new unit test explorer and created an extensible test runner that is independent of the underlying unit test framework. Now you can plug in your favorite unit test framework such as NUnit, XUnit or MbUnit, or you can continue to use MSTest.

New Project dialog in Visual Studio 2012  Figure 2. New Project dialog in Visual Studio 2012 shows the template for the
Unit Test Library project for the apps written in C#.

For the Windows 8 apps written in C#, VB.net or C++, Visual Studio now provides a unit test library project that follows the same workflow you use for developing a desktop app (see Figure 2). You will enjoy the improvements and many of the same features you are familiar with. Under the hood, the unit test support takes care of running your tests in the app container model and abstracts all the complexity away. The unit test project has its own appxmanifest file. This is helpful because in many cases such as when you are testing the code that handles location service or internet access, for the tests to run, you need to edit the manifest file to specify the capabilities that match your app’s requirement, as illustrated in Figure 3. Alternatively, if the part of the code path under testing doesn’t need a capability, you can group such test cases in a separate unit test project and deliberately exclude a capability from it to improve the modularization of your code.

package manifestFigure 3. Package.appxmanifest file of a unit test project opened in the Manifest Designer. 

In keeping with our commitment to quality, we made the improvements and new functionalities in unit testing available in all the SKUs of Visual Studio 2012, including Visual Studio 2012 Express for Windows 8. For more details or to learn how to effectively unit test your Windows 8 app, see Creating and running unit tests on a Windows Metro style app and this unit testing talk from the //BUILD conference.

Exploratory testing your Windows 8 apps

Windows 8 apps are designed to excite consumers and businesses alike. If you work on an app in an enterprise environment, and are used to a more structured development and testing process, Visual Studio 2012 provides a manual testing tool, Microsoft Test Manager, which in combination with Remote Tools for Visual Studio, allows you to conduct exploratory testing and structured manual testing of your app’s functionality on all types of Windows 8 devices. Microsoft Test Manager is part of the Visual Studio Premium and Ultimate SKU and the Test Professional SKU. In addition to the seamless integration with TFS for easy bug filing and test case management, the manual testing tool in Visual Studio 2012 simplifies testing of your app on a remote device. During the testing process, the tool can capture screen shots, action logs and event logs from the remote device when you discover a bug in your app. It provides a two-way communication between your main workstation and the connected device that guides you through the steps of deployment of your app packages to the targeted testing device, acquisition of developer license on the device, and the execution of test steps.

With TFS integration, the manual testing tool enables a continuous workflow in a team environment between testing and development of your app. For example, the info captured during exploration helps you reproduce the bug and improves the understanding of its nature. When a new app package becomes available with bug fixes or feature enhancement, it can be easily picked up and deployed to the same Windows 8 testing device for further verification from within the manual testing tool.

For more info, see Visual Studio 11 Beta: Manual Testing of Windows Metro Style Apps. Manual Testing Of Windows 8 Metro Style Applications provides a detailed walkthrough.

Conclusion

Windows 8 is an exciting platform for developers and users. We hope that this blog is a useful introduction to the tools shipped in Visual Studio 2012 that you can start using right away to test the Windows 8 app you are working on. We look forward to hearing your feedback to see how we can continue to make that part of your life easier. Don’t forget to leave comments on this post to share with us and the community tips, ideas, and personal experience on how you have been testing your apps.

--Rui Sun, Principal Test Manager, Visual Studio

--Andre Hamilton, SDET, Visual Studio

Special thanks to Ashwin Needamangala, Mete Goktepe, Jake Sabulsky, Jason Olson, Art Becker, Raul Gonzalez Tovar, Peter Provost, Mathew Aniyan, and Anutthara Bharadwaj for their contributions to this post.

Profile specific web.config transforms and transform preview

$
0
0

When we released VS2010 we add support for web.config (XDT) transforms during publish/package. Note: From now on I’ll only use the word publish from now on but the full content relates to packaging as well. In the original implementation when you published your web project the web.config file would be transformed by the file web.{Configuration}.config, where {Configuration} is the project build configuration. For example Debug, or Release. If you publish on Release and there exists a web.release.config we will take your web.config and transform it with web.release.config before publishing.

Cascading web.config transformations

In VS 2012 (as well as the publishing updates for VS2010 through the Azure SDK) now support the concept of publish specific transforms. You can also now specify the project configuration used for a profile when publishing on the publish dialog.

SNAGHTML45b19fc

In this case I have created a profile named Production and set the Configuration to Release. When I publish this project the following transformations will be applied (if the files exist) in this order.

  1. web.release.config
  2. web.production.config

I think that we got this wrong when we initially implemented the support. We should have created profile specific transforms instead of ones based on build config, but having these cascading transforms are still pretty useful. For example I may want to remove the attribute debug=”true” from the compilation element and then inside of the profile specific transform we would override appSettings/WCF endpoints/logging config/etc for that environment.

In VS there is a right-click option on web.config for Add Config Transform, but we were not able to update the functionality of that to automatically create profile specific transforms. Don’t worry, it will be released soon with one of our updates for web tooling. For now you will need to create a new file with the correct name and add it to your project. Note: if you want it to show up nested under web.config you’ll need to add the metadata Web.config to the item in the .csproj/.vbproj file.

web.config transform preview

Previously the only way to test the functionality for these transformation was to actually publish or package the web project. This gets old pretty quick. In order to simplify creating these transforms we have introduced the Preview Transform menu option. This is the coolest feature in VS 2012 (OK I’m a bit biased, but still its the coolest).

image

In my web.release.config I have left the default contents, which just removes the debug attribute. Here is what I see when I select this on web.release.config for my project.

image

You can see that in the image above we can see that the debug flag was indeed removed as expected.

In my web.production.config I have a transform which simply updates the email app setting value. Here is the really cool part when I preview the transform for web.production.config the previewer will look into the profile and determine the build configuration which has been configured, and it will ensure that transform is applied before the profile specific one. For example take a look at the result for web.production.config.

image

In the image above you can see the note that web.release.config was applied first followed by web.production.config. In the result we can see that web.release.config removed the debug flag and that web.production.config updated the email address value.

We also do a little bit to help out in case there are errors in either the web.config or a transform. You can see errors in the Output Window and double click it to go directly to where the error exists.

Note: Scott Hanselman has a 5 minute video showing this and other updates.

Another note: If you need to transform any file besides web.config during publish then install my extension SlowCheetah.

 

Cross posted to http://sedodream.com/2012/08/19/ProfileSpecificWebconfigTransformsAndTransformPreview.aspx

Sayed Ibrahim Hashimi | @SayedIHashimi

Getting Started with ASP.NET 4.5 Web Forms

$
0
0

The best way to learn what’s new in ASP.NET 4.5 Web Forms, is to work through the latest tutorial series by Erik Reitan: Getting Started with ASP.NET 4.5 Web Forms.

The 10 tutorials in the series progressively guide you through building a Web Forms application, which is a simplified example of a store front web site that sells items online. Each tutorial builds on the previous tutorial. When you’re finished, you’ll be familiar with common ASP.NET concepts, as well as many of the new features available in ASP.NET 4.5, including effective use of the new model binding features.

dataitems-01

In addition, you’ll learn about, Entity Framework Code First, unobtrusive validation, the Anti-XSS library, HTML5, data annotations, Local DB, value providers, PayPal integration, ASP.NET Membership, URL routing, and more.

Here's an outline of the tutorial series:

Introduction and Overview

  • Introduction
  • Audience
  • Application Features
  • Application Scenarios and Tasks
  • Overview
  • Prerequisites
  • Download the Sample Application
  • Tutorial Support and Comments

Create the Project

  • Creating the Project
  • Reviewing the Project
  • Running the Default Web Application
  • ASP.NET Web Forms Background
  • Web Application Features in the Web Forms Application Template
  • Touring Visual Studio
  • Summary
  • Additional Resources

Create the Data Access Layer

  • Creating the Data Models
  • Configuring the Application to Use the Data Model
  • Building the Application
  • Summary
  • Additional Resources

UI and Navigation

  • Modifying the UI
  • Updating the Master Page
  • Adding Image Files
  • Adding Pages
  • Updating the StyleSheet
  • Modifying the Default Navigation
  • Adding a Data Control to Display Navigation Data
  • Linking the Data Control to the Database
  • Running the Application and Creating the Database
  • Reviewing the Database
  • Summary
  • Additional Resources

Display Data Items and Details

  • Adding a Data Control to Display Products
  • Displaying Products
  • Adding Code to Display Products
  • Running the Application
  • Adding a Data Control to Display Product Details
  • Running the Application
  • Summary

Shopping Cart

  • Creating a Shopping Cart
  • Managing the Shopping Cart Business Logic
  • Creating the Shopping Cart Class
  • Creating the Add-To-Cart Functionality
  • Creating the Shopping Cart UI
  • Retrieving the Shopping Cart Items
  • Adding Products to the Shopping Cart
  • Testing the Shopping Cart
  • Calculating and Displaying the Order Total
  • Modify the Shopping Cart Display
  • Testing the Shopping Cart Total
  • Adding Update and Checkout Buttons to the Shopping Cart
  • Updating and Removing Shopping Cart Items
  • Adding a Shopping Cart Counter
  • Testing the Completed Shopping Cart
  • Summary
  • Addition Information

Checkout and Payment with PayPal

  • Adding Order Tracking
  • Adding Checkout Access
  • Enabling Logins from Other Sites Using OAuth and OpenID
  • Modifying Login Functionality
  • Migrating the Shopping Cart
  • Updating the Database Connection
  • Integrating PayPal
  • Running the Application
  • Reviewing the Database
  • Summary
  • Disclaimer

Membership and Administration

  • Adding an Administrator
  • Restricting Access to the Administration Page
  • Including Administrator Navigation
  • Enabling Product Administration
  • Running the Application
  • Summary
  • Additional Resources

URL Routing

  • ASP.NET Routing Overview
  • Mapping and Registering Routes
  • Retrieving and Using Route Data
  • Running the Application
  • Summary

ASP.NET Error Handling

  • Overview
  • Adding Error Logging Support
  • Adding an Error Page
  • Displaying Unhandled Error Messages for the Application
  • Including an Exception for Testing Purposes
  • Adding Application-Level Error Handling
  • Adding Page-Level Error Handling
  • Removing the Exception Used for Testing
  • Adding Code-Level Error Logging
  • Inspecting the Error Logging Information
  • Safe Error Messages
  • Using ELMAH
  • Viewing the ELMAH Log
  • Summary
  • Conclusion
  • Additional Resources
  • Acknowledgements

Using Git with TFS projects

$
0
0

If you having been following the updates to CodePlex over the last several months you will have noticed that we added support for Git source control. It is important to the CodePlex team to enable developers to use the source control system that supports their development style whether it is distributed version control or centralized version control.

There are many projects on CodePlex that are using TFS centralized version control. But we continue to see more and more developers interested in using Git. Last week Brian Harry announced a new open source project called Git-TF. Git-TF is a client side bridge that enabled developer to use Git locally and push to a remote backed by Team Foundation version control. Git-TF also works great for TFS based projects on CodePlex.

You may already be familiar with git-tfs. Git-TFS is a similar client side bridge between Git and TFS. Git-TFS works great if you are on Windows since it depends on the TFS .Net client object model. Git-TF adds the ability to use a Git to TFS bridge on multiple platforms since it is written in Java. You can use it on Mac OS X, Linux, and Windows, etc.

Since you are connecting to a TFS Server when using Git-TF make sure you use your CodePlex TFS account name: snd\YOUR_USERNAME_cp along with your password. At this point, you will need to be a member of the project to connect using Git-TF.

Resources

Git-TF Getting Started Guide

Download: Git-TF

Git-TF Source on CodePlex

Releasing Microsoft ASP.NET Universal Providers Core 1.2

$
0
0

I hope everyone has been busy downloading Visual Studio 2012 and have started building awesome web applications. We have been busy too during this time.

We have just released an update to the version of Universal Providers that shipped with VS2012. Following are the key changes with this release

  • Address key performance issues with the providers
  • Depends on EntityFramework Code First

 

What should you do

This version of Universal Providers Core that shipped with VS2012 was 1.1. Take a moment and update to 1.2

You can follow this documentation on  how to update a nuget package.

While updating you will get the EntityFramework 5.0.0 package as well from the nuget.org

Some common FAQ

  • Works on .NET v4.0/4.5
  • Works on VS2010/VS2012
  • 1.2 is compatible with 1.1

Please do reach out to us on the following forum channels for any questions on universal providers

All the best building awesome applications.

Cross posted to http://blogs.msdn.com/b/pranav_rastogi/archive/2012/08/20/releasing-microsoft-asp-net-universal-providers-core-1-2.aspx

Visual Studio 2012 released to the web!

$
0
0

On August 15th, we announced the release of Visual Studio 2012 to the web! Make sure to visit Somasegar’s Blog for the announcement, and if you haven’t downloaded yet, check out Jason Zander’s Blog for 12 reasons to upgrade. There was a lot of buzz across the blogs, so here’s a rollup of additional posts you might want to read about the release:

Start Downloading

MSDN Subscribers can download from the MSDN Subscriber Download Page. For free trial and Express versions, these releases are available on our Visual Studio product website.

To learn more about Visual Studio 2012, join us on September 12th for the Visual Studio 2012 Launch event online at http://www.visualstudiolaunch.com/.

As always, we want to hear your suggestions or feature ideas/improvements so please add your suggestions to UserVoice or vote on other user’s suggestions.

Enjoy!

Cathy Sullivan (Program Manager) and the Visual Studio Team


Visual Studio 2012 can only install to certified Windows To Go drives

$
0
0

Windows To Go is a cool new enterprise features to enable a mobile workforce to carry around an enterprise-managed installation of Windows on a USB thumb drive. However, only certified thumb drives appear as fixed drives and, therefore, Visual Studio 2012 can only install to certified drives. VS2012, like some other products, only supports installing to fixed drives because removable drives can be ejected and VS will not work correctly.

Screenshot: The path entered cannot be on a removeable drive.If you install Windows To Go (aka WTG or W2G) on a non-certified drive then boot to it and attempt to install VS2012 – or even try to install VS2012 to a separate removable drive – you will see an error similar to following screenshot and text description:

The path entered cannot be on a removeable drive.

If you’re running Windows on a fixed drive and just trying to install to a removable drive, please select another drive such as the system drive. If you do not have enough space on the system drive and do not have another fixed drive you can install to, you will need to free up the required drive space. For more information, please read why VS2012 requires space on the system drive.

If you are running W2G on a non-certified drive, there is no supported workaround for installing VS2012 directly onto the drive. Please purchase one of the certified thumb drives listed in the hardware consideration section of the Windows To Go feature overview.

Extra Information from OAuth/OpenId Provider

$
0
0

When you authenticate a user using the OAuth/OpenId providers, you can request for some extra information about the user if you have granted access for these providers to send this information.

For eg if you login using Facebook, you can request information such as Gender, country etc.

Each provider has different set of data that you can retrieve. I am not going to into the details of these different sets of data. In this post I am going to cover what kind of information can you retrieve from the implementations of the providers that we shipped with templates  in VS2012 and how can you retrieve this information.

What kind of information can you retrieve

Google

  • email
  • firstname
  • lastname
  • country

https://developers.google.com/accounts/docs/OpenID is a good place to look for more information

Facebook

  • id
  • Name
  • link
  • gender 
  • accesstoken

http://developers.facebook.com/docs/ is a good place to look for more information

    Twitter

    • name
    • location
    • description
    • url
    • accesstoken

    https://dev.twitter.com/docs/auth/oauth/faq is a good place to look for more information

    How to retrieve this information

    This data is available when you login using anyone of the providers. In specifics to the code you can access this data after the authentication has happened. The data is returned as a dictionary. Following image shows a snapshot of the data returned from facebook provider

    oauthextradata

     

    Web Forms

    • Create the ASP.NET WebForm template
    • Goto Account\RegisterExternalLogin.cs
    • In the AuthenticationResult type we have Extradata dictionary bag which has this data
    var authResult = OpenAuth.VerifyAuthentication(redirectUrl);

     

    MVC

    • Create the internet template in MVC4
    • Goto the account controller in ExternalLoginCallBack
    • In the AuthenticationResult type we have Extradata dictionary bag which has this data
     AuthenticationResult result = 
                    OAuthWebSecurity.VerifyAuthentication(Url.Action("ExternalLoginCallback", new { ReturnUrl = returnUrl }));

    Web Pages

    • Create the webpages2 template
    • Goto ExternalLoginCallBack
    • In the AuthenticationResult type we have Extradata dictionary bag which has this data

     

     AuthenticationResult result = 
                    OAuthWebSecurity.VerifyAuthentication(Url.Action("ExternalLoginCallback", new { ReturnUrl = returnUrl }));

     

    In the following posts I will be spending more time showing you how you can customize our OAuth/OpenId stack and how you can customize and plugin your own providers

    Cross posted to http://blogs.msdn.com/b/pranav_rastogi/archive/2012/08/22/extra-information-from-oauth-openid-provider.aspx

    NuGet Gallery Performance Issues

    $
    0
    0

    Since August 16th, and especially since August 21st, the NuGet Gallery has been exhbiting intermittent performance issues. Some users are reporting errors when attempting to browse or search for NuGet packages from Visual Studio or other clients. Many users are reporting that browsing and searching are slow. There have also been timeout errors when browsing the gallery’s packages page.

    During this time, we have been communicating with many of you on twitter, under the #nuget tag, as well as in JabbR’s #nuget room. We truly appreciate your patience and understanding with us.

    Status

    We have been working to address these performance issues over the last several days, and we hope to have a deployment in place this evening (August 22nd, Pacific Time). It looks like the deployment will cause a short outage though–we will post more information about that when the details are available.

    Root Cause

    The root cause of the performance issues boils down to some sub-optimal queries that are used when searching the gallery–especially when searching from Visual Studio. There are a couple reasons these queries are slow:

    1. Some missing indexes that could significantly aide the search queries.
    2. Table columns that have nvarchar(max) as their data type when a size constraint can be applied. We are seeing that when these nvarchar(max) columns are used in ORDER BY clauses, it becomes a bottleneck.

    The deployment we’re preparing will address both of these issues by adding size constraints to many fields and then creating several new indexes. Unfortunately, the process of altering the Packages and PackageRegistrations tables and then creating these new indexes is going to take some time to apply – during that time, the database will be rather unresponsive. Again, when we know more about the timing of the outage, we’ll share the details.

    Plugging custom OAuth/OpenID providers

    $
    0
    0

    In the previous post, I wrote about how you can use the existing providers for Google, Facebook etc. and retrieve extra metadata about the authenticated users. Let’s assume you wanted to change the way the providers request for information. Some examples of this could be

    • You want to request more data about the user
    • You want to apply different scope levels when requesting the data

    This post covers how you can write your own provider and plug it into your ASP.NET web application

    Write your own provider

    Each Provider implements from OpenIdClient. Following example shows a custom implementation of Google Provider which requests information about the user such as firstname/lastname etc

    Please Note:  This addresses a bug with the existing google provider which does not return the extra data about the user such as Country/FirstName/LastName. The version of google provider is DotNetOpenAuth.AspNet" version="4.0.3.12153". We have logged a bug for this and will fix it in next update of this package.

     

    namespace MyApplication
    {
        using System.Collections.Generic;
        using DotNetOpenAuth.OpenId.Extensions.AttributeExchange;
        using DotNetOpenAuth.OpenId.RelyingParty;
     
        /// 
        /// Represents Google OpenID client.
        /// 
        public class GoogleCustomClient : OpenIdClient
        {
            #region Constructors and Destructors
     
            public GoogleCustomClient()
                : base("google", WellKnownProviders.Google) { }
     
            #endregion
     
            #region Methods
     
            /// 
            /// Gets the extra data obtained from the response message when authentication is successful.
            /// 
            /// 
            /// The response message. 
            /// 
            /// A dictionary of profile data; or null if no data is available.
            protected override Dictionarystring, string> GetExtraData(IAuthenticationResponse response)
            {
                FetchResponse fetchResponse = response.GetExtension();
                if (fetchResponse != null)
                {
                    var extraData = new Dictionarystring, string>();
                    extraData.Add("email", fetchResponse.GetAttributeValue(WellKnownAttributes.Contact.Email));
                    extraData.Add("country", fetchResponse.GetAttributeValue(WellKnownAttributes.Contact.HomeAddress.Country));
                    extraData.Add("firstName", fetchResponse.GetAttributeValue(WellKnownAttributes.Name.First));
                    extraData.Add("lastName", fetchResponse.GetAttributeValue(WellKnownAttributes.Name.Last));
     
                    return extraData;
                }
     
                return null;
            }
     
            /// 
            /// Called just before the authentication request is sent to service provider.
            /// 
            /// 
            /// The request. 
            /// 
            protected override void OnBeforeSendingAuthenticationRequest(IAuthenticationRequest request)
            {
                // Attribute Exchange extensions
                var fetchRequest = new FetchRequest();
                fetchRequest.Attributes.AddRequired(WellKnownAttributes.Contact.Email);
                fetchRequest.Attributes.AddRequired(WellKnownAttributes.Contact.HomeAddress.Country);
                fetchRequest.Attributes.AddRequired(WellKnownAttributes.Name.First);
                fetchRequest.Attributes.AddRequired(WellKnownAttributes.Name.Last);
     
                request.AddExtension(fetchRequest);
            }
     
            #endregion
        }
    }

     

    Source Code for existing providers

    The source code for existing providers is public and can be accessed at https://github.com/AArnott/dotnetopenid/tree/master/src/DotNetOpenAuth.AspNet/Clients

    Register your provider with your application

    WebForms

    • In App_Start/AuthConfig.cs register the custom provider as follows
    OpenAuth.AuthenticationClients.Add("Custom Google", () => new MyApplication.GoogleCustomClient());
    //OpenAuth.AuthenticationClients.AddGoogle();
       

    MVC

    • In App_Start/AuthConfig.cs register the custom provider as follows

     OAuthWebSecurity.RegisterClient(new MyApplication.GoogleCustomClient(),"Google",null);
               // OAuthWebSecurity.RegisterGoogleClient();

    WebPages

    • In _AppStart.cshtml register the custom provider as follows

     

     OAuthWebSecurity.RegisterClient(new MyApplication.GoogleCustomClient(),"Google",null);
               // OAuthWebSecurity.RegisterGoogleClient();

    This post has been cross posted to http://blogs.msdn.com/b/pranav_rastogi/archive/2012/08/23/plugging-custom-oauth-openid-providers.aspx

    Please do reach me via twitter (@rustd) for any questions

    Course Manager VS 2012 Sample Part 4 – Implementing the Workflow (Andy Kung)

    $
    0
    0

    Welcome to part 4 of the Course Manager series! If you missed the previous posts you can read them here:

    Course Manager VS 2012 Sample Part 1 – Introduction
    Course Manager VS 2012 Sample Part 2 – Setting up Data
    Course Manager VS 2012 Sample Part 3 – User Permissions & Admin Screens

    In Part 3, we’ve set up a Desktop application with Windows authentication. We’ve created some “raw data” screens and wrote permission logic. In this post, we will dive into the main workflows of Course Manager. You can download the sample available in both VB and C# online here:

    Download the LightSwitch HTML Client Preview 

    LightSwitch Course Manager End-to-End Application (Visual Studio 2012)

    We will be covering quite a few screens in the remainder of the series. Some of them are fairly straightforward. In which case, I will briefly highlight the concepts and reference you to the online sample. Others are more interesting and require some explanations. I will walk through these examples step-by-step. Let’s begin!

    Workflow

    Course Manager is designed with 4 main entry points or workflows. From the Home screen, you can:

    1. Create a new student => view student detail => register a course for this student
    2. Search for an existing student => view student detail => register a course for this student
    3. Browse course catalog => view section detail => register this course for a student
    4. Register a course for a student

    Therefore, the rest of the series will focus on creating the following screens:

    • Create New Student
    • Search Students
    • Register Course
    • Course Catalog
    • Student Detail
    • Section Detail
    • Home

    clip_image001

    Screens

    Create New Student

    Create a screen using “New Data Screen” template on Student table.

    clip_image003

    By default, the screen vertically stacks up all the controls (using Rows Layout). In our case, we’d like to show the Picture on the left column and the rest of the fields on the right column.

    clip_image005

    To do this, first change “Student Property” from “Rows Layout” to “Columns Layout.” Each node under a “Columns Layout” will represent a column.

    clip_image006

    We only want 2 columns on the screen. So essentially, we need 2 group nodes under “Columns Layout.” Each group node represents a column and contains some student fields. Right click “Student Property” and select “Add Group” to add a group node under “Student Property.” Repeat and create a 2nd group node.

    clip_image007

    We’d like the picture to be in the first column, so drag and drop Picture under the first group node. Set the image’s width and height to 150 and 200 via Properties to make it bigger. We don’t want the picture to display any label, so set “Label Position” to “None.” We’d also like the first column to fit tightly with the Picture, select the first group and set its “Horizontal Alignment” to “Left” via Properties.

    Drag and drop the rest of the fields under the 2nd group node to make them appear in the 2nd column.

    clip_image008

    Let’s hit F5 to see the screen. As expected, we now have 2 columns on the screen. The first column shows a big image editor and the 2nd column contains the rest of the student fields. We can also use “Address Editor” to display the address fields instead, as we did in Part 3.

    clip_image010

    Search Students

    Create a screen using “Search Data Screen” template on Student table.

    clip_image012

    In screen designer, you will get a Data Grid of students showing all student fields. Let’s make the grid easier to read by removing some non-essential fields. Delete Picture, Street, City, State from Data Grid Row.

    clip_image013

    We’d also need a way for the user to drill into a record to see more details. One feature worth mentioning here is the ability to show a label-based control as links (provided the field is part of a record). When a link is clicked, the detail screen of the related record will open.

    Show a label as link

    Select First Name under Data Grid Row. Check “Show as Link” in Properties. It will be shown as a column of links in the running app. When a link is click, the corresponding Student detail screen will open. Notice you can also choose a target screen to launch in the Properties. This is useful if you have multiple customized details screens for Student (we will cover this in the later post).

    clip_image014

    Notice the Search Data Screen template automatically sets the first column to show as links in this case. But you can do the same thing to any other columns.

    Register Course

    From Part 2, we know the Enrollment table is essentially a mapping table between Student and Section table. To register a course is to create an Enrollment record in the database. Let’s create a “New Data Screen” called “RegisterCourse” on Enrollment table.

    clip_image016

    In the screen designer, you will see the EnrollmentProperty, which is the new enrollment record we are creating, on the data list. EnrollmentProperty’s Section and Student fields are represented as 2 data pickers on the screen content tree.

    clip_image017

    Using a custom query for data picker

    By default, the pickers on the screen will show you all available students and sections. In our case, when a student is selected, we only want to show the sections this student has not yet enrolled in.

    In Part 2, we’ve already created a custom query called AvailableSections. This query takes a StudentId as parameter and returns a list of Sections this student has not enrolled in. This is exactly what we need! Click “Add Data Item” button in the command bar. Use the “Add Data Item” dialog to add AvailableSections on the screen.

    clip_image018

    Select StudentId query parameter and bind it to EnrollmentProperty’s Student.Id field in the Properties.

    clip_image019

    Finally, select the Section picker on the screen. Set the Choices property to AvailableSections. The source of the picker is now set to the custom query instead of the default “select all.”

    clip_image020

    Adding local screen choice list properties

    Now we have a Section picker that filters its list of Sections based on a Student. We’d also like to further filter it down by Academic Year and Academic Quarter. We need a choice list picker for Academic Year and a choice list picker for Academic Quarter on the screen.

    LightSwitch enables the ability to add a choice list as a screen property. Use “Add Data Item” dialog, add a local property of Integer type called AcademicYear. Mark it as not required since we’d like it to be an optional filter.

    clip_image021

    Select the newly created AcademicYear. Click “Choice List” in Properties. Enter choice list options in the dialog.

    clip_image022

    Create a group node on the screen content tree using “Columns Layout.”

    clip_image023

    Use “+ Add” button to add “Academic Year.” A picker will be added to the screen.

    clip_image024

    Follow similar steps. Add an optional local property of String type called AcademicQuarter. Set its choice options to Fall/Winter/Spring/Summer. Add it below the Academic Year picker.

    clip_image025

    Applying additional filters on custom query

    Now we have Academic Year and Academic Quarter pickers on the screen. We need to wire them up to the custom query. This means that we need to create 2 additional filters to the AvailableSection query. To do this, click “Edit Query” on AvailableSections to go to query editor.
    clip_image026

    Add 2 optional parameterized filters for AcademicYear and AcademicQuarter. We are marking the parameters as optional so if they are not specified, it still returns results.

    clip_image027

    Click “Back to RegisterCourse” link on top to go back to the screen designer. You will see AvailableSections now has 2 more parameters.

    clip_image028

    Select AcademicYear parameter, set parameter binding to AcademicYear, which is the local choice list property we just added.

    clip_image029

    Follow the same steps to bind AcademicQuarter.

    Using optional screen parameters to pre-set screen fields

    Our workflow indicates that we can also navigate to Register Course screen from a student or section screen. Wouldn’t it be nice if we could pre-populate the student or section picker in this case? To achieve this, we need to create optional screen parameters.

    Use “Add Data Item” dialog, add a local property of Integer type called StudentId. Mark it as not required since it will be used as an optional parameter.

    clip_image030

    In the Properties, check “Is Parameter.” Repeat the same steps to create a local property of Integer type called SectionId. Set it as an optional parameter.

    Just a side note, if a screen has required screen parameters, it will not be shown on the menu of the running application. This makes sense because the screen can only be opened with parameters. In our case, we have 2 optional screen parameters. “Register Course” screen will still show up in the menu since it can be open with or without screen parameters.

    clip_image031

    Now we write logic to handle the screen parameters if they’re available. Use the “Write Code” dropdown menu and select RegisterCourse_InitializeDataWorkspace method.

    clip_image032

    At the end of the method, add:

    ' StudentId is an optional screen parameter
    If (StudentId.HasValue) Then
        ' If StudentId is set, run a query to get the student record, pre-set the student field on the screen
        Me.EnrollmentProperty.Student = DataWorkspace.ApplicationData.Students_Single(StudentId)
    End If
    
    ' SectionId is an optional screen parameter
    If (SectionId.HasValue) Then
        ' If SectionId is set, run a query to get the section record, pre-set the section field on the screen
        Me.EnrollmentProperty.Section = DataWorkspace.ApplicationData.Sections_Single(SectionId)
    End If

    We check if the screen is supplied with a StudentId (or SectionId) parameter. If so, we run a query to get the student (or section) record and pre-set the field of the EnrollmentProperty on the screen.

    Adjusting screen layout with runtime screen designer

    Let’s hit F5 to run the application and make some layout adjustments on the fly. Click “Design Screen” button in the ribbon to launch the runtime screen designer.

    clip_image033

    Select the screen root node. Make the following tweaks and Save the design.

    • Label Position = Top
    • Horizontal Alignment = Left
    • Vertical Alignment = Top
    • Move Student picker above Section picker
    • Use Modal Window Picker control for both Student and Section

    clip_image035

    Ahh. Much better!

    clip_image036

    Conclusion

    We have covered quite a few topics in this post! We created “Create New Student,” “Search Students,” and “Register Course” screens.

    clip_image037

    During the process, we customized screen layouts, added detail links, utilized custom queries, created screen parameters, etc. These are all very useful techniques for your own apps. We will continue the rest of the screens in Part 5.

    Coming up next: Course Manager Sample Part 4 – Detail Screens

    -andy

    New Visual Studio 2012 Debugging Features for the Windows 8 App Lifecycle Model

    $
    0
    0

    Windows 8 brings a new app lifecycle model, in which Windows Store apps are automatically managed for the user. These apps always feel alive, even though they never run when they’re off the screen. This provides great benefits for power consumption and battery life.

    Here are a few related blog posts we recommend for background reading on this topic:

    1. Building Windows 8 Blog: Building a power-smart general-purpose Windows (see “The Metro style application model” section)
    2. Building Windows 8 Blog: Improving power efficiency for applications (explains the different app states)
    3. Windows 8 app developer blog: Managing app lifecycle so your apps feel "always alive" (explains how to program for the different lifecycle states)

    In this post, we’ll take a look at what this all means for debugging. Of all the debugging advances we made in Visual Studio 2012 (from JavaScript debugging, to the Windows 8 Simulator, to remote debugging on Windows RT devices), the debugging experience for Windows 8 lifecycle states and background tasks was one of the most challenging to design!

    Simulating events

    The first challenge we encountered in this process was how to simulate the events your app would encounter with real world usage, so that you could debug those interesting cases. How could we simulate your app being suspended because a text message was sent and caused another app to activate? How could we simulate your app being terminated, without ending your debugging session?

    One principle that we used in designing the solution was that we wanted the model to be simple, so that you could use a core set of debugging commands to simulate the variety of lifecycle events that your app might experience. Therefore, we decided to add the following three commands to Visual Studio: Suspend, Resume and “Suspend and Shutdown”.

    1. Suspend: The Suspend command leaves the app in suspended state after it has handled the event.
    2. Resume: The Resume command resumes the app, and brings it back into a running state as the active app in the foreground.
    3. “Suspend and shutdown”: “Suspend and shutdown” first does a “Suspend”. Then (once the app is suspended), this command terminates the app and stops debugging.

    You may wonder why we needed to create a “Suspend and shutdown” command. The goal of this command is to simulate the natural sequence of events that occur when your app is suspended and terminated by Windows 8. When an app gets suspended, it receives a suspending event, and the suspending event handler usually saves data the app may need when it is later activated (after going from suspended to terminated state). We observed users try to simulate this in other ways on the pre-release bits. For example, we saw some users just stop debugging, which would shut down the app, but there would be no suspending event triggered. Other users would explicitly close the app by pressing Alt+F4 or by dragging it to the bottom of the screen. In that case, a suspending event would be triggered before the app was terminated; however the next time the user activated the app, its PreviousExecutionState would be ClosedByUser (which is not what we’re trying to simulate). Therefore, the “Suspend and shutdown” command provides a way to simulate your app being suspended and terminated by Windows, as opposed to being explicitly closed by the user.

    Exposing the commands

    The next question we faced in the design process was how to expose these commands.

    In the Visual Studio 2012 Beta release, we created dedicated buttons for these commands in the “Debug Location” toolbar. We chose this toolbar because it provides the unique ability to select a process during run mode. This makes it easy to determine which process to apply the commands to, when debugging multiple processes.

    Starting in Visual Studio 2012 RC (and continuing for Visual Studio 2012 RTM), we collapsed these buttons into a dropdown list on the same “Debug Location” toolbar. The dropdown design provided more space for the multiple commands which we wanted to expose, without cluttering the toolbar:

    image

    Please note that the “Debug Location” toolbar is not always enabled. Therefore, if you don’t see this toolbar, please enable it through the View menu:

    image

    App activation

    Another case that we wanted to allow you to simulate in the debugger is app activation.

    When you start debugging your Metro style app in Visual Studio, by default the app automatically gets activated. (This occurs in a very similar way to tile activation.)

    However, there are also other ways your app can be activated, which you’ll want to simulate as well. For example, your app can receive some content shared from another app, and get activated through contract or extension. (See the Sharing content target app sample for more info on how this works.)

    Starting in the beta release of Visual Studio 2012, we added the ability for you to change the project properties to not launch the app when you start debugging (in order to simulate these other activation scenarios). When you start debugging your project with this option set, Visual Studio 2012 goes into debug mode but nothing actually runs yet. You’ll also notice that the “Debug Location” toolbar shows your project name instead of a running process.

    image

    This indicates that the app package deployed by this project is in debug mode, and as soon as an app from that package gets activated, the debugger will attach to the process.

    image

    For example (as described in the Sharing content target app sample mentioned above), we can simulate sharing text from another app and selecting the sample app as the share target. In that case, the app gets activated and we can debug it:

    image

    Note that now the “Debug Location” toolbar shows the actual process that is running.

    Debugging background tasks

    There’s one more Windows 8 behavior that we wanted to allow you to simulate in the debugger, and that is background tasks. The idea behind background tasks is that your app may need to perform certain actions in the background, while the app is off-screen and not running. To learn how to program background tasks, please see the following post on the Windows 8 app developer blog: Being productive in the background – background tasks.

    Background tasks get triggered by a system event such as a timer event. (Your app needs to run at least once to register the task.) Background tasks normally run in a system provided host (backgroundTaskHost.exe or wwahost.exe for JavaScript), however you can also provide your own executable for some background task triggers. Regardless of which process hosts the task, the background task runs as part of your package.

    We designed the debugging experience for background tasks to utilize the same auto-attaching functionality as at runtime. That is, when your package is in debug mode, the debugger will automatically attach to the host process once it starts.

    Given that you can debug apps from multiple packages at a time, we needed to present these in a control that had the ability to expand based on the number of tasks. Therefore, we added these to the same “Debug Location” toolbar dropdown control as shown above. As a result, the trigger commands of all background tasks registered for currently active packages will appear in this dropdown. As an example, when debugging the Background Task sample, you will see the following background tasks in the dropdown list (once registered).

    image

    Next, to debug a background task, add a break point to the Run method and trigger the background task:

    image

    And that’s how easy it is to debug your background task!

    Please note that there are just a few exceptions to this design… Background tasks that have a data payload (for example, TriggerDetails in the IBackgroundTaskInstance) cannot be triggered through Visual Studio and must be triggered naturally by the system instead, in order to debug. Similarly, for the ControlChannel, PushNotification, and SmsReceived triggers. However, all other background task triggers can be triggered via Visual Studio.

    Summary

    The Windows 8 app lifecycle model presents some new debugging scenarios to consider, as you develop your Windows Store apps. Using Visual Studio 2012, you can simulate the events and states that your app will encounter, as it gets suspended and resumed. Visual Studio 2012 also provides a way to debug different app activation mechanisms, by putting the package in debug mode without activating the app. Finally, you can use the Debug Location toolbar dropdown to trigger background tasks. For more information on this topic, please reference the MSDN documentation. We look forward to hearing what you think on Connect, the Forums, or UserVoice!

    clip_image002

    Dmitri Leonov – Software Development Engineer in Test, Visual Studio Ultimate team.

    Short Bio: Dmitri Leonov joined the Visual Studio team in 2008. He has been working on the Debugger team since then, where he is now focusing on JavaScript debugging.

    Special thanks to Lisa Feigenbaum for contributing to this blog post.

    An "is" operator puzzle, part one

    $
    0
    0

    It is possible for a program with some local variable x:

    bool b = x is FooBar;

    to assign true to b at runtime, even though there is no conversion, implicit or explicit, from x to FooBar allowed by the compiler! That is,

    FooBar foobar = (FooBar)x;

    would not be allowed by the compiler in that same program.

    Can you create a program to demonstrate this fact? This is not a particularly hard puzzle but it does illustrate some of the subtleties of the "is" operator that we'll discuss in the next episode.


    Release Notes for 8/23/2012

    $
    0
    0

    Below are the release notes from today's deployment.

    • Improved the inline diff load performance for large diff sets
    • Fixed a few issues related to sending and saving comments within a Pull Request
    • Improved stability of the notification service
    • Fixed an issue when directly linking to a file in the source browser, selected file was not being shown in the tree view

    Have ideas on how to improve CodePlex? Please visit our suggestions page! Vote for existing ideas or submit a new one.

    As always you can reach out to the CodePlex team on Twitter @codeplex or reach me directly @mgroves84

    OData 101: Building our first OData-based Windows Store app (Part 2)

    $
    0
    0

    Download the sample code

    In the previous blog post, we walked through the steps to build an OData-enabled client using the new Windows UI. In this blog post, we’ll take a look at some of the code that makes it happen.

    ODataBindable, SampleDataItem and SampleDataGroup

    In the walkthrough, we repurposed SampleDataSource.cs with some code from this gist. In that gist, ODataBindable, SampleDataItem and SampleDataGroup were all stock classes from the project template (ODataBindable was renamed from SampleDataCommon, but otherwise the classes are exactly the same).

    ExtensionMethods

    The extension methods class contains two simple extension methods. Each of these extension methods uses the Task-based Asynchronous Pattern (TAP) to allow the SampleDataSource to execute an OData query without blocking the UI.

    For instance, the following code uses the very handy Task.Factory.FromAsync method to implement TAP:

    public static async Task> ExecuteAsync(this DataServiceQuery query)
    {
        return await Task.Factory.FromAsync>(query.BeginExecute(null, null), query.EndExecute);
    }

    SampleDataSource

    The SampleDataSource class has a significant amount of overlap with the stock implementation. The changes I made were to bring it just a bit closer to the Singleton pattern and the implementation of two important methods.

    Search

    The Search method is an extremely simplistic implementation of search. In this case it literally just does an in-memory search of the loaded movies. It is very easy to imagine passing the search term through to a .Where() clause, and I encourage you to do so in your own implementation. In this case I was trying to keep the code as simple as possible.

    public static IEnumerable Search(string searchString)
    {
    	var regex = new Regex(searchString, RegexOptions.CultureInvariant | RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace);
    	return Instance.AllGroups
    	    .SelectMany(g => g.Items)
    	    .Where(m => regex.IsMatch(m.Title) || regex.IsMatch(m.Subtitle))
    		.Distinct(new SampleDataItemComparer());
    }

    LoadMovies

    The LoadMovies method is where the more interesting code exists.

    public static async void LoadMovies()
    {
        IEnumerable titles = await ((DataServiceQuery<title>)Context.Titles
            .Expand("Genres,AudioFormats,AudioFormats/Language,Awards,Cast")
            .Where(t => t.Rating == "PG")
            .OrderByDescending(t => t.ReleaseYear)
            .Take(300)).ExecuteAsync();
    
        foreach (Title title in titles)
        {
            foreach (Genre netflixGenre in title.Genres)
            {
                SampleDataGroup genre = GetGroup(netflixGenre.Name);
                if (genre == null)
                {
                    genre = new SampleDataGroup(netflixGenre.Name, netflixGenre.Name, String.Empty, title.BoxArt.LargeUrl, String.Empty);
                    Instance.AllGroups.Add(genre);
                }
                var content = new StringBuilder();
                // Write additional things to content here if you want them to display in the item detail.
                genre.Items.Add(new SampleDataItem(title.Id, title.Name, String.Format("{0}\r\n\r\n{1} ({2})", title.Synopsis, title.Rating, title.ReleaseYear), title.BoxArt.HighDefinitionUrl ?? title.BoxArt.LargeUrl, "Description", content.ToString()));
            }
        }
    }

    The first and most interesting thing we do is to use the TAP pattern again to asynchronously get 300 (Take) recent (OrderByDescending) PG-rated (Where) movies back from Netflix. The rest of the code is simply constructing SimpleDataItems and SimpleDataGroups from the entities that were returned in the OData feed.

    SearchResultsPage

    Finally, we have just a bit of calling code in SearchResultsPage. When a user searches from the Win+F experience, the LoadState method is called first, enabling us to intercept what was searched for. In our case, the stock implementation is okay aside from the fact that we don’t any additional quotes embedded, so we’ll modify the line that puts the value into the DefaultViewModel to not append quotes:

    this.DefaultViewModel["QueryText"] = queryText;

    When the filter actually changes, we want to pass the call through to our implementation of search, which we can do with the stock implementation of Filter_SelectionChanged:

    void Filter_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        // Determine what filter was selected
        var selectedFilter = e.AddedItems.FirstOrDefault() as Filter;
        if (selectedFilter != null)
        {
            // Mirror the results into the corresponding Filter object to allow the
            // RadioButton representation used when not snapped to reflect the change
            selectedFilter.Active = true;
    
            // TODO: Respond to the change in active filter by setting this.DefaultViewModel["Results"]
            //       to a collection of items with bindable Image, Title, Subtitle, and Description properties
            var searchValue = (string)this.DefaultViewModel["QueryText"];
            this.DefaultViewModel["Results"] = new List(SampleDataSource.Search(searchValue));
    
            // Ensure results are found
            object results;
            ICollection resultsCollection;
            if (this.DefaultViewModel.TryGetValue("Results", out results) &&
                (resultsCollection = results as ICollection) != null &&
                resultsCollection.Count != 0)
            {
                VisualStateManager.GoToState(this, "ResultsFound", true);
                return;
            }
        }
    
        // Display informational text when there are no search results.
        VisualStateManager.GoToState(this, "NoResultsFound", true);
    }

    Item_Clicked

    Optionally, you can implement an event handler that will cause the page to navigate to the selected item by copying similar code from GroupedItemsPage.xaml.cs. The event binding will also need to be added to the resultsGridView in XAML. You can see this code in the published sample.

    Media Playback: What you need to know about playing media to make your app shine in Windows 8

    $
    0
    0

    For Windows 8, we made some changes in our audio system designed to improve the app experience. In this blog, I discuss these changes, and how you can take advantage of them in your media apps. Hopefully this info helps you better understand how audio works in Windows Store apps, especially when it comes to audio playback in the background. Let me begin by describing a common user scenario.

    You’re listening to your favorite band in a Windows music app, and a friend sends you an mp3 of a sweet live version of a song by his favorite band. When you open the mp3, Windows Media Player opens and starts playing the song. Now both your favorite band and his favorite band are playing at the same time. Then your alarm goes off reminding you to pick up your sister from school and it’s a cacophonous mess. You panic, and shut the lid to your laptop. Well, if you’re like me, you’re probably looking for a better way to manage the sounds coming out of your machine.

    For Windows 8 apps, we addressed this problem with the introduction of the Playback Manager and Media Transport Controls. The Playback Manager uses audio categories, which assign behaviors to audio streams—and, by extension, audio apps. Incoming audio streams in the foreground are always allowed to play audio. But by tagging streams, Playback Manager can make intelligent decisions about how to handle multiple streams in the foreground and background.

    For example, if a background capable app is playing music and is moved to the background, and then the user opens a new app in the foreground to play music, Playback Manager mutes the audio in the background app. This allows for a more fluid and intuitive user experience. Users hear what they want to hear, not what they don’t. Add in intelligent attenuation of background music for alerts (like alarms and ringtones), and easy to access to Media Transport Controls to stop, start, skip to next/previous tracks, and you have a system that is designed to keep you from panicking and frantically looking for apps that are making noise when you don’t want them to.

    Why did we do what we did?

    In previous versions of Windows, users could have multiple applications open and running simultaneously. On the audio front, they could minimize your media player, work on a document and surf the web at the same time on one big monitor. With two monitors, they could do much more multitasking. In Windows 8 in the new immersive environment, things have changed with respect to how many apps you can see on the screen at once. With only one app in the body and one snapped, finding the app that’s making sound becomes more of a problem if it’s on the back stack. This is the primary reason behind the evolution of Playback Manager and the Media Transport controls. With these features in place, it is now much easier to make music start and stop when you need it to. And because Playback Manager can mute apps that should not be making sound, it keeps users from having to swipe back through a stack of apps to make something be quiet.

    There is no audio mixer in this environment as there is in the desktop. It still exists for desktop applications, but your app won’t show up here because we felt it was not a great experience to pop out into desktop to adjust relative app volumes. Instead, we are encouraging apps to not include volume controls. This way users are focused on the master volume control which helps simplify the entire volume experience as well – but that’s a different story.

    Stream categories

    To allow the system to manage when audio streams can or cannot be heard, we added stream categories.  By doing this, Windows now has the ability to make some logical decisions about whether audio should be heard.  Audio categories determine how streams are handled when apps are in the foreground (app visible on the device display) or the background (app hidden by another app).  Apps enter the foreground when they are launched or swiped onto the screen.  They are also in foreground and kept there when snapped.

    For example, an app that plays some incidental sounds – interactive dings or clicks, likely doesn’t need to be heard in the background. It would be annoying.  So Playback Manager mutes this app as soon as it goes to the background.  But a media app, playing your playlist of music should continue playback so you can surf the web or work while you listen to music.

    Here is a brief description of how to use the audio categories. The easiest way to play audio in a Windows 8 app is by using an audio tag.


    JavaScript

    audtag = document.createElement('audio');
    audtag.setAttribute("id", "audtag");
    audtag.setAttribute("msAudioCategory", "BackgroundCapableMedia");
    document.getElementById("MediaElement").appendChild(audtag);
    audtag.load();

    C#

    In C#, you can set the audio category like this:

    Playback.SetAudioCategory(AudioCategory.BackgroundCapableMedia);
    Playback.SelectFile();

    There are several audio categories to choose from. The table lists the available categories, and provides a description of the behavior associated with each one. You need to decide very carefully which category should be associated with which stream because your app will behave differently in each case.

    Available stream categories

    Stream type

    Description

    Background capable?

    ForeGroundOnlyMedia

    Games or other sounds designed to work only in the foreground, but will mute existing background media sounds.

    • Game audio needed for a game (dancing games, music games)
    • Feature films (designed to pause when they go to the background)

    No

    BackgroundCapableMedia

    For audio that needs to continue playing in the background. Examples include:

    • Local media playback
    • Local playlist
    • Streaming radio
    • Streaming playlist
    • Music videos
    • Streaming audio/radio, YouTube, Netflix, and so on

    Yes

    Communications

    For audio streaming communication audio such as:

    • Voice over IP (VoIP)
    • Real-time chat or other type of phone call

    Yes

    Alert

    Looping or longer running alert sounds:

    • Alarm
    • Ring tones
    • Ringing notification
    • Sounds that need to decrease existing audio

    No

    GameMedia

    Background music played by a game

    No

    GameEffects

    Game sound effects designed to mix with existing audio, such as:

    • Balls bouncing, engine sounds, and so on
    • Characters talking
    • All non-music sounds

    No

    SoundEffects

    Sounds designed to mix with existing audio, such as beeps, dings, and other brief sounds

    No

    Other

    Default stream category used for uncategorized streams.

    No

    Here are some rules of thumb to help you decide how to categorize your audio stream:

    • To use multiple stream types, you can generate your audio and video tags dynamically, tearing them down as you go.
    • Using the Communications category automatically defaults to low-latency audio. This creates one less step for you when designing two-way communications apps.
    • Don’t configure your audio tag to use low latency mode unless it is absolutely necessary. This is because communication streams already default to low-latency mode. A large amount of CPU resources will be required if you have an audio stream in low latency mode and a communication stream is also initialized.

    Stream categories and app behavior

    [App behaviors are documented in detail in Audio Playback in a Metro Style App]

    The overall rationale for determining if an app can be heard is largely based on whether it is in the foreground. But when you factor in other considerations, like communications apps and background capable media apps, things get more complicated. But don’t worry - in general, app behavior based on stream type is fairly easy to explain. These rules apply:

    • If your app is in the foreground, it doesn’t matter what category its audio stream is. It will always play sound, unless the system is muted or the volume is down.
    • Only one background capable audio app can play at a time, except when two are in the foreground.
    • Communications apps will always attenuate other system sounds when a call comes in on a communications stream type. If background music was playing, to hear the music again while in a call, the user can bring the music app to the foreground (snap the app or just bring it forward full screen) and then rune 1 applies.
    • Sounds from an app in the foreground will mix with background-capable audio if the foreground streams are not incompatible with the background stream. For example, a ForegroundOnlyMedia stream will mute a BackgroundCapableMedia stream playing in the background, but GameEffects will mix with the BackgroundCapableMedia so users can play games and listen to music.

    When you choose a category for an app, you must follow some rules for your app to work as expected. To have your app play audio in the background, you must:

    • Add a background audio declaration in the app manifest
    • Set msAudioCategory to either Communications or BackgroundCapableMedia
    • Your app must register for media transport controls (more on this later)

    For categories that don’t play audio in the background, you don’t need to use a background capable media type. Instead, choose Other, or use GameEffects, or another relevant type.

    For general info about using apps in the background, see http://blogs.msdn.com/b/windowsappdev/archive/2012/05/24/being-productive-in-the-background-background-tasks.aspx.

    Background audio and connected standby

    Connected standby is a new low power state in Windows 8 that enables a smartphone-like power mode on system-on-a-chip (SoC) devices. In connected standby, the device looks like it’s off, but it’s not. Apps can continue to play music in the background, receive updates, and use the network. For more info see the blog post on improving power efficiency for applications. For streaming music apps, there are some important steps to take if you want your background audio app to continue streaming from the network when a device enters connected standby.

    In a nutshell, if the network connection is not up, your app can’t play streaming audio. Local audio will work fine, but if you have a server that’s dictating a playlist, your app won’t get the next song until your network is up.

    For your app to continue to stream music even when the device is in connected standby, you have 3 options:

    1. Use the Background Transfer API, which will do all the work for you.
    2. Wrap an existing MF bytestream, when just a small amount of data needs to be transferred.
    3. Use Custom Media Foundation source or bytestream.

    For details about these options; see Writing a power savvy background media app.

    SoundLevel system notifications

    SoundLevel notifications help apps know when they can be heard. When we first started developing the Playback Manager, we were not certain if we would actually end up sending notifications to apps to inform them they were muted, but we soon realized we could end up with apps in the background that are rendering audio or video and using up system resources unnecessarily, which could be a drain on the battery. So, when you register your app to receive SoundLevel notifications, Playback Manager will send your app one of 3 such notifications, depending on the audible state of your app:

    • SoundLevel(Full) means your audio from your app is audible
    • SoundLevel(Mute) means audio from your app is not audible (but can still play audio)
    • SoundLevel(Low) means your app has been attenuated by -28dB and is barely (but still) audible.

    Let’s talk about why each notification is sent and what your app should do in response to each one.

    SoundLevel(Full)

    A SoundLevel(Full) notification will be sent to your app when:

    What your app must do:

    A non-background capable app moves from the background to the foreground

    No action needed

    Rhe app first becomes visible after startup

    No action needed

    SoundLevel(Mute)

    A SoundLevel(Mute) notification will be sent to your app when:

    What your app must do:

    A non-background capable app moves from the foreground to the background

    Pause

    Another similar stream type begins to play while your app is playing (e.g. a second BackgroundCapableMedia stream begins while another is playing, the older will get a Mute)

    Pause (unless you have a good reason not to) to save system resources

    If a Communications stream type is in the background, it will get a SoundLevel(Mute) when another Communications stream is started in the foreground

    Place the call on hold

    SoundLevel(Low)

    A SoundLevel(Low) notification will be sent to your app when:

    What your app must do:

    A communications stream begins to play while your app is playing audio

    Pause if it is playing content that you don’t want the user to miss. It can be heard, but the volume will be very low unless it is moved to the foreground. So although it is your choice here, we recommend you pause.

     

    Here is a sample showing how to register for and use the SoundLevel events:

    JavaScript

    // Create the media control. 

    mediaControl = Windows.Media.MediaControl;

    // Add event listeners for PBM notifications to illustrate app is
    // getting a new SoundLevel and pass the audio tag to the function

    mediaControl.addEventListener("soundlevelchanged", soundLevelChanged, false);


    function soundLevelChanged() {

    // Catch SoundLevel notifications and determine SoundLevel state. If it's muted, pause the player.

    var soundLevel = Windows.Media.MediaControl.soundLevel;


    switch (soundLevel) {

    case Windows.Media.SoundLevel.muted:
    log(getTimeStampedMessage("App sound level is: Muted"));
    break;
    case Windows.Media.SoundLevel.low:
    log(getTimeStampedMessage("App sound level is: Low"));
    break;
    case Windows.Media.SoundLevel.full:
    log(getTimeStampedMessage("App sound level is: Full"));
    break;
    }

    C#

    // add new handlers
    MediaControl.SoundLevelChanged += MediaControl_SoundLevelChanged;
    MediaControl.PlayPauseTogglePressed += MediaControl_PlayPauseTogglePressed;
    MediaControl.PlayPressed += MediaControl_PlayPressed;
    MediaControl.PausePressed += MediaControl_PausePressed;
    MediaControl.StopPressed += MediaControl_StopPressed;

    // save current handlers
    SoundLevelChangedHandler = MediaControl_SoundLevelChanged;

    string SoundLevelToString(SoundLevel level)
    {
    string LevelString;

    switch (level)
    {
    case SoundLevel.Muted:
    LevelString = "Muted";
    break;
    case SoundLevel.Low:
    LevelString = "Low";
    break;
    case SoundLevel.Full:
    LevelString = "Full";
    break;
    default:
    LevelString = "Unknown";
    break;
    }
    return LevelString;
    }

    Capture and loopback

    We added a couple of small considerations to capture and loopback. First, if you decide to create a capture-based app, you’ll need to use the “Other” category to tag your capture stream (or the system will assign that category),but more importantly, you can’t categorize your capture stream with any other category. For Communications apps, when you have labeled your render stream as a Communications stream, you don’t need to tag your capture stream.

    In addition, when the system sends SoundLevel(Mute), render, capture and loopback are all muted.

    Why not use Visibility Notifications?

    Although app visibility is closely tied to app audibility, it is important to only listen to SoundLevel events if you want to know when your app is heard. Don’t use visibility events for this, or your app’s audible state may be out of sync with its visible state.

    Media Transport controls

    [See System Transport Controls for a complete usage guide.]

    The addition of the globally available Media Transport control (shown in the next figure) makes playing and controlling music from a music app a breeze.

    start_screen
    Figure 1 - View of the Start screen with Media Transport Control

    mt_control
    Figure 2 - Cropped view of just the Media Transport Control
    showing album art and metadata.

    The MTC UI (as it is affectionately known in the halls of the Media Platform team) allows a user to play/pause audio whether it is in the foreground or the background, even if the app has been suspended in the background. This UI is invoked when a user presses the volume buttons on a keyboard or slate. It shows up everywhere: the new immersive environment, desktop, and even in the lock screen. It is a great addition to Windows 8 and your apps can (and should) make use of it where appropriate.

    Going back to the opening scenario (where the user has a bunch of audio playing at once and closes the lid), it is for this reason that we felt a global transport control like this was needed. Because there are not multiple windows to switch to, like on the Desktop, users must have a way to quickly stop an app that is making sound. We felt that tying the MTC UI to the volume controls would be intuitive and it would provide a lot of detail about what’s playing on a user’s system in one button press.

    If you are using a media app, (and especially one that is background capable) here’s how you can tie in to the controls:

    JavaScript:

    // Assign the button object to MediaControls
    MediaControls = Windows.Media.MediaControl;

    // Add event listeners for the buttons
    MediaControls.addEventListener(“playselected”, play, false);
    MediaControls.addEventListener(“pauseselected”, pause, false);
    MediaControls.addEventListener(“playpausetoggleselected”, playpausetoggle, false);

    C#

    using Windows.Media;
    MediaControl.SoundLevelChanged += MediaControl_SoundLevelChanged;
    MediaControl.PlayPauseTogglePressed += MediaControl_PlayPauseTogglePressed;
    MediaControl.PlayPressed += MediaControl_PlayPressed;
    MediaControl.PausePressed += MediaControl_PausePressed;
    MediaControl.StopPressed += MediaControl_StopPressed;

    The next code snippet shows how to enable the Previous Track and Next Track buttons by adding event listeners to the MediaControl object.

    JavaScript

    // enable the previous track button
    MediaControls.addEventListener(“previoustrackselected”, previoustrack, false);

    // enable the next track button
    MediaControls.addEventListener(“nexttrackselected”, nexttrack, false);

    C#

    MediaControl.NextTrackPressed   += MediaControl_NextTrackPressed; 
    MediaControl.PreviousTrackPressed -= MediaControl_PreviousTrackPressed;

    You can also add artist metadata and artwork to the flyout. See the white paper referenced above for details.

    The MTC UI is populated by the media app in use. The UI stays populated until is the system clears it. The situations when the UI will be cleared are:

    1. User closes the app
    2. User clears recently used apps from app switch list
    3. The system terminates the app to free up resources
    4. The app crashes
    5. User shuts down the machine
    6. App unregisters for MTC controls

    Summary

    We’ve worked hard to bring a totally new audio paradigm your way for Windows 8 that lines up with new form factors and a new user experience in Windows. Audio Categories provide Windows with context so the system will treat your app appropriately. If your app needs to play background audio, all you do is set the category, hook up media transport controls and declare it in the manifest.

    SoundLevel notifications let you know if your app can be heard by the user. This gives you info you need to help save battery life by pausing the audio if it can’t be heard in the background.

    The Media Transport UI shows volume state, allows users to quickly start and stop audio, and get artist info. from a media app.

    We hope you use these new technologies in your apps to enable great audio experiences for your customers. All in all they are easy to implement, and can have huge payback for users.

    --Johnny Bregar, Program Manager, Windows

    Visual Studio 2012 RTM will not install on pre-release versions of Windows 8

    $
    0
    0

    Symptom

    Customers installing Visual Studio 2012 RTM on pre-release versions of Windows 8 or Windows Server 2012 may see the following error after launching the setup application:

    The .Net Framework installed on this machine does not meet the minimum required version: 4.5.50709.

    This is a blocking error and only allows the install to be canceled.

    Cause

    Visual Studio 2012 RTM is not supported on pre-release versions of Windows 8 or Windows Server 2012.

    Resolution

    To install Visual Studio 2012 RTM, you will need to install it on Windows 7 SP1, Server 2008 R2 SP1, or install VS2012 RTM on Windows 8 or Server 2012 RTM. If you are an MSDN or TechNet subscriber, you can get Win8 now from the following links:

    If you are not an MSDN or TechNet subscriber, you can download a 90-day evaluation of Windows 8 Enterprise to make sure your software or hardware is ready for the Windows 8 launch.

    You may also continue to use pre-release versions of VS2012 on supported pre-release versions of Win8, such as VS2012 RC on the Win8 Release Preview (RP).

    More Information

    See the system requirements on the download page for Visual Studio 2012 for more information.

    Course Manager VS 2012 Sample Part 5 – Detail Screens (Andy Kung)

    $
    0
    0

    This week I’ve been writing a series of articles on building the Course Manager Sample, if you missed them:

    Course Manager VS 2012 Sample Part 1 – Introduction
    Course Manager VS 2012 Sample Part 2 – Setting up Data
    Course Manager VS 2012 Sample Part 3 – User Permissions & Admin Screens
    Course Manager VS 2012 Sample Part 4 – Implementing the Workflow

    You can download the sample available in both VB and C# online here:

    Download the LightSwitch HTML Client Preview

    LightSwitch Course Manager End-to-End Application (Visual Studio 2012)

     

    In Part 4, we identified the main workflow we want to implement. We created screens to add a student, search for a student, and register a course. In this post, we will continue and finish the rest of the workflow. Specifically, we will create detail screens for student and section records and a course catalog screen that allows user to filter sections by category.

    clip_image001

    Screens

    Student Detail

    Remember the Search Students screen we built in Part 4? If you click on a student link in the grid, it will take you to a student detail screen.

    clip_image002

    This is pretty cool. But wait… we didn’t really build this screen! In reality, LightSwitch recognizes that this is a common UI pattern, and therefore it generates a default detail screen for you on the fly. Of course, we can always choose to build and customize a detail screen, as we’re about to do for Student and Section.

    Adding a detail screen

    Create a screen using “Details Screen” template on Student table. In this screen, we want to also include student’s enrollment data, so let’s check the “Student Enrollments” box.

    Make sure “Use as Default Details Screen” is checked. It means that this detail screen will be used as the detail screen for all student records by default. In other words, if you click on a student link, it will take you to this detail screen instead of the auto-generated one. As a side note, if you forget to set it as the default details screen here. You can also set the property of the Student table (in table designer).

    clip_image004

    By default, the details screen template lays out the student info on top and the related enrollment data on the bottom.

    clip_image005

    We can make similar layout tweaks to the student portion as we did for “Create New Student” screen in Part 4 (such as moving the student picture to its own column, etc).

    Including data from related tables

    I’d like to draw your attention to the Enrollments portion of the screen. Since Enrollment is a mapping table between Student and Section, the grid shows you a student (shown as a summary link) and a section (shown as a picker). Neither of the fields is very useful in this context. What we really want is to show more information about each section (such as title, meeting time, instructor, etc.) in the grid. Let’s delete both Enrollment and Section under Data Grid Row.

    clip_image006

    Use the “+ Add” button and select “Other Screen Data.”

    clip_image007

    It will open the “Add Screen Data” dialog. Type “Section.Course.Title”. You can use Intellisense to navigate through the properties in this dialog. Click OK.

    clip_image008

    The Title field will now appear in the grid. Follow similar steps to add some other section fields. The “Add Screen Data” dialog is a good way to follow the table relationship and include data that is many levels deep.

    clip_image009

    Making a read-only grid

    Now we have an editable grid showing the sections this student is enrolled in. However, we don’t expect users to directly edit the enrollments data in this screen. Let’s make sure we don’t use editable controls (ie. TextBox) in grid columns. A quick way to do this is to select the “Data Grid Row” node. Check “Use Read-only Controls” in Properties. It will automatically selects read only controls for the grid columns (ie. TextBox to Label).

    clip_image010

    We also don’t expect users to add and delete the enrollments data directly in the data grid. Let’s delete the commands under data grid’s “Command Bar” node. In addition, data grid also shows you an “add-new” row for inline add.

    clip_image011

    We can turn it off by selecting the “Data Grid” node and uncheck “Show Add-new Row” in Properties.

    clip_image012

    Launching another screen via code

    In Part 4, we’ve enabled the Register Course screen to take a student ID as an optional screen parameter. The Student picker will be automatically set when we open the Register Course screen from a Student detail screen. Therefore, we need a launch point in the student detail screen. Let’s add a button on the enrollment grid.

    Right click on the Command Bar node, select Add Button.

    clip_image013

    Name the method RegisterCourse. This is the method called when the button is clicked.

    clip_image014

    Double click on the added button to navigate to the screen code editor.

    clip_image015

    Write code to launch the Register Course screen, which takes a student ID and a section ID as optional parameter.

    Private Sub RegisterCourse_Execute()
        ' Write your code here.
        Application.ShowRegisterCourse(Student.Id, Nothing)
    End Sub

    That’s it for Student Detail screen. F5 and go to a student record to verify the behavior.

    clip_image016

    Section Detail

    Now that we’ve gone through customizing the student detail screen, let’s follow the same steps for Section. Please refer to the sample project for more details.

    1. Create a screen using “Details Screen” template on Section table. Include section enrollments data
    2. Tweak the UI and make the enrollment grid read-only
    3. Add a button to the enrollment grid to launch Register Course screen

    Course Catalog

    In Course Catalog screen, we’d like to display a list of course sections. We’d also like to filter the list by the course category. In Part 2, we’ve created a custom query for exactly this purpose called SectionsByCategory. It takes a category ID as a parameter and returns a list of sections associated with the category. Let’s use it here!

    Create a screen using “Search Data Screen” template. Choose SectionsByCategory as screen data.

    clip_image018

    In screen designer, you will see SectionsByCategory has a query parameter called CategoryId. It is also currently shown as a TextBox on the screen. User can enter a category ID via a text box to filter the list. This is not the most intuitive UI. We’d like to show a category dropdown menu on the screen instead.

    clip_image019

    Select SectionCategoryId (you can see it is currently bound to the query parameter) and hit DELETE to remove this data item. After it is removed, the text box will also be removed from the visual tree.

    clip_image020

    Click “Add Data Item” button in the command bar. Use the “Add Data Item” dialog to add a local property of Category type on the screen.

    clip_image021

    Select CategoryId query parameter, set the binding via property.

    clip_image022

    Drag and drop the Category property to the screen content tree (above the Data Grid). Set the “Label Position” of Category to “Top” in Properties.

    clip_image023

    Follow the Course Manager sample for some layout tweaks and show some columns as links (as we did in Search Students). Now, if you click on a section link. It will open up the Section Detail screen we customized!

    clip_image024

    Conclusion

    In this post, we’ve completed the main workflow in Course Manger. We are almost done! All we need is a Home screen that provides some entry points to start the workflow.

    clip_image025

     

    clip_image027

    Setting a screen as the home (or startup) screen is easy. We’ve also made it easy to lay out static images, text, and group boxes on the screen. In the next post, we will conclude the Course Manager series by finishing our app with a beautiful Home screen!

    Coming up next: Course Manager Sample Part 5 – Home Screen

    -andy

    Viewing all 10804 articles
    Browse latest View live




    Latest Images