Red Gate is looking for feedback on its ASP.NET Web Development Education website.
Visit their website and answer the survey.
Patterns & Practices has released Hilo guidance: Developing a Windows Store app using C++ and XAML which is part of the Windows SDK.
Having created an Rx wrapper over the GeoCoordinateWatcher on a previous post, in this post I’ll demonstrate how it can be used in a simple application.
The application will display the status of the service, the position and the distance traveled.
For this simple application the service will be exposed as a singleton property of the App class:
public partial class App : Application
{
// ...
public static IGeoCoordinateReactiveService GeoCoordinateService { get; private set; }
public App()
{
// ...
InitializePhoneApplication();
// ...
}
// ...
private void InitializePhoneApplication()
{
// ...
GeoCoordinateService = new GeoCoordinateReactiveService();
// ...
}
// ...
}
Getting the status of the service is very simple. It just requires subscribing to the StatusObservable. Since we want to display the status, we need to observe it on the dispatcher before:
App.GeoCoordinateService.StatusObservable
.ObserveOnDispatcher()
.Subscribe(this.OnStatusChanged);
For the position we do the same with the PositionObservable:
App.GeoCoordinateService.PositionObservable
.ObserveOnDispatcher()
.Subscribe(this.OnPositionChanged);
The distance traveled would seem a bit more complicated because we need to keep track of the last position and calculate the distance traveled on every position change. But this is where the Rx excels with its query operators. If we combine the position observable with the position observable having skipped one position with the zip operator we end up with an observable with the current and previous position. And if we apply a selector, we get the traveled distance:
App.GeoCoordinateService.PositionObservable
.Zip(
App.GeoCoordinateService.PositionObservable.Skip(1),
(p1, p2) => p1.Location.GetDistanceTo(p2.Location))
.ObserveOnDispatcher()
.Subscribe(this.OnDistanceChanged);
You can find the complete implementation of the service and application here.
Resources:
The C++ Team (blog) has been researching roaming Visual Studio settings and they have a few questions that will help gain insights into what the best experience would be. They have created a survey (http://aka.ms/vsroaming) aimed at understanding Visual Studio settings usage patterns and gathering feedback. The survey should take less than 10 minutes, maybe more if you want to provide a ton of details.
Your voice is important. Make sure it is heard!
With Rx, events are first class citizens that can be passed around and composed as needed in a very simple way.
“The Reactive Extensions (Rx) is a library for composing asynchronous and event-based programs using observable sequences and LINQ-style query operators. Using Rx, developers represent asynchronous data streams with Observables, query asynchronous data streams using LINQ operators, and parameterize the concurrency in the asynchronous data streams using Schedulers. Simply put, Rx = Observables + LINQ + Schedulers.” – from the MSDN page.
The library also provides a considerable amount of helpers that make it easy to warp events into observables.
Wrapping the GeoCoordinateWatcher as a reactive service is quite simple. All it takes is creating observables and exposing the events as observables:
public class GeoCoordinateReactiveService : IGeoCoordinateReactiveService, IDisposable
{
private readonly GeoCoordinateWatcher geoCoordinateWatcher = new GeoCoordinateWatcher();
public GeoCoordinateReactiveService()
{
this.StatusObservable = Observable
.FromEventPattern<GeoPositionStatusChangedEventArgs>(
handler => geoCoordinateWatcher.StatusChanged += handler,
handler => geoCoordinateWatcher.StatusChanged -= handler);
this.PositionObservable = Observable
.FromEventPattern<GeoPositionChangedEventArgs<GeoCoordinate>>(
handler => geoCoordinateWatcher.PositionChanged += handler,
handler => geoCoordinateWatcher.PositionChanged -= handler);
}
public IObservable<EventPattern<GeoPositionStatus> StatusObservable { get; private set; }
public IObservable<EventPattern<GeoPosition<GeoCoordinate>> PositionObservable { get; private set; }
}
And now, instead of the StatusChanged and PositionChanged events we have respectively the StatusObservable and PositionObservable as a stream of EventPattern<TEventArgs> instances.
But the EventPattern<TEventArgs> class includes the source of the event and an the event arguments in properties which is far more than we need in this case. With normal LINQ operators we can convert thes streams of EventPattern<TEventArgs> instances in streams of the desired values.
public class GeoCoordinateReactiveService : IGeoCoordinateReactiveService, IDisposable
{
private readonly GeoCoordinateWatcher geoCoordinateWatcher = new GeoCoordinateWatcher();
public GeoCoordinateReactiveService()
{
this.StatusObservable = Observable
.FromEventPattern<GeoPositionStatusChangedEventArgs>(
handler => geoCoordinateWatcher.StatusChanged += handler,
handler => geoCoordinateWatcher.StatusChanged -= handler)
.Select(ep => ep.EventArgs.Status);
this.PositionObservable = Observable
.FromEventPattern<GeoPositionChangedEventArgs<GeoCoordinate>>(
handler => geoCoordinateWatcher.PositionChanged += handler,
handler => geoCoordinateWatcher.PositionChanged -= handler)
.Select(ep => ep.EventArgs.Position);
}
public IObservable<GeoPositionStatus> StatusObservable { get; private set; }
public IObservable<GeoPosition<GeoCoordinate>> PositionObservable { get; private set; }
}
And to use these observables all it is needed is to subscribe to them:
geoCoordinateWatcherService.StatusObservable
.Subscribe(this.OnStatusChanged);
geoCoordinateWatcherService.PositionObservable
.Subscribe(this.OnPositionChanged);
But, usually, we want to use these values in view model to bind to the UI and, consequently, we want this to happen in the UI thread:
geoCoordinateWatcherService.StatusObservable
.ObserveOnDispatcher()
.Subscribe(this.OnStatusChanged);
geoCoordinateWatcherService.PositionObservable
.ObserveOnDispatcher()
.Subscribe(this.OnPositionChanged);
It’s as simple as that!
Resources:
The purpose of the synchronization model implemented by the SynchronizationContext class is to allow the asynchronous/synchronization operations of the common language runtime to behave properly with different synchronization models. This model also simplifies some of the requirements that managed applications have to follow in order to work correctly under different synchronization environments. Examples of such synchronization environments are user interface infrastructures like Windows Forms, Windows Presentation Foundation and ASP.NET.
Providers of synchronization models extend this class to provide their own implementations. Because these user interface infrastructures usually run on their own threads, dispatching execution to their execution contexts usually means leaving the current thread.
The Task Parallel Library (TPL) provides dataflow components to help increase the robustness of concurrency-enabled applications. These dataflow components are collectively referred to as the TPL Dataflow Library. This dataflow model promotes actor-based programming by providing in-process message passing for coarse-grained dataflow and pipelining tasks. The dataflow components build on the types and scheduling infrastructure of the TPL and integrate with the C#, Visual Basic, and F# language support for asynchronous programming. These dataflow components are useful when you have multiple operations that must communicate with one another asynchronously or when you want to process data as it becomes available.
The TPL Dataflow Library (System.Threading.Tasks.Dataflow namespace) is not distributed with the .NET Framework 4.5. To install the System.Threading.Tasks.Dataflow namespace, open your project in Visual Studio 2012, choose Manage NuGet Packages from the Project menu, and search online for the Microsoft.Tpl.Dataflow package.
Sometimes, for demo or testing purposes, I need a synchronization context that behaves like the user interface ones but doesn’t force me to build applications with a user interface and the TPL Dataflow Library seemed like a good option to implement such synchronization context.
It was as easy as this:
public class TplDataflowSynchronizationContext : SynchronizationContext
{
private ActionBlock<ActionItem> ab
= new ActionBlock<ActionItem>(
item =>
{
Trace.WriteLine(
string.Format("{0}: {1}", Environment.CurrentManagedThreadId, item.operation));
try
{
item.d(item.state);
}
finally
{
item.SetResult(true);
}
});
public override SynchronizationContext CreateCopy()
{
return new TplDataflowSynchronizationContext();
}
public override void Post(SendOrPostCallback d, object state)
{
Trace.WriteLine(
string.Format("{0}: Posting...", Environment.CurrentManagedThreadId));
this.ab.Post(new ActionItem { d = d, state = state, operation = "Post" });
Trace.WriteLine(
string.Format("{0}: Posted.", Environment.CurrentManagedThreadId));
}
public override void Send(SendOrPostCallback d, object state)
{
Trace.WriteLine(
string.Format("{0}: Sending...", Environment.CurrentManagedThreadId));
ActionItem item = new ActionItem { d = d, state = state, operation = "Send" };
this.ab.SendAsync(item);
item.Task.Wait();
Trace.WriteLine(
string.Format("{0}: Sent.", Environment.CurrentManagedThreadId));
}
public class ActionItem : TaskCompletionSource<bool>
{
public SendOrPostCallback d;
public object state;
public string operation;
}
}
UPDATE:
Fixed implementation because the SynchronizationContext.Send method returned without having completely executed the operation. Thanks to Svick for pointing that out and Stephen Toub for the help fixing it.
Here are the materials from my What’s New In C# 5.0 session at the Rumos InsideOut Event.
Slide deck:
Sample code:
C# 5.0 Async/Await Demo Code
I’ve published the sample code I use to demonstrate the use of async/await in C# 5.0. You can find it here.
Projects
PauloMorgado.AyncDemo.WebServer
This project is a simple web server implemented as a console application using Microsoft ASP.NET Web API self hosting and serves an image (with a delay) that is accessed by the other projects.
This project has a dependency on Json.NET due to the fact the the Microsoft ASP.NET Web API hosting has a dependency on Json.NET.
The application must be run on a command prompt with administrative privileges or a urlacl must be added to allow the use of the following command:
netsh http add urlacl url=http://+:9090/ user=machine\username
To remove the urlacl, just use the following command:
netsh http delete urlacl url=http://+:9090/
PauloMorgado.AsyncDemo.WindowsForms
This Windows Forms project contains three regions that must be uncommented one at a time:
Sync with WebClient
This code retrieves the image through a synchronous call using the WebClient class.
Async with WebClient
This code retrieves the image through an asynchronous call using the WebClient class.
Async deadlock
This code how async operations can still deadlock.
Async with HttpClient with cancelation
This code retrieves the image through an asynchronous call with cancelation using the HttpClient class.
PauloMorgado.AsyncDemo.Wpf
This WPF project contains three regions that must be uncommented one at a time:
Sync with WebClient
This code retrieves the image through a synchronous call using the WebClient class.
Async with WebClient
This code retrieves the image through an asynchronous call using the WebClient class.
Async deadlock
This code how async operations can still deadlock.
Async with HttpClient with cancelation
This code retrieves the image through an asynchronous call with cancelation using the HttpClient class.
Microsoft is planning to expand the Remarks section of selected types in the .NET Framework Class Library to provide detailed usage information and code examples. (For an example, see the Remarks section for the System.String class.) In the current design, the Remarks section isn’t easily discoverable, because member tables take up a lot of screen real estate.
Some alternate page designs are proposed to address this problem.
Click here to provide your feedback.
Windows 8 introduces a number of innovations in the way information is delivered to developers. Microsoft would like to know how well these are working for you, and where they can make further changes to improve your experience.
To review the site before you complete the survey, visit the Windows 8 Dev Center. In particular, have a look at the section called Learn to build Metro style apps.
A few questions in the survey are about about how the Windows 8 site experience compares to the iOS and Android sites. If you aren’t an experienced iOS or Android developer, feel free to skip these parts. But, if you’ve made apps for those platforms, or if you’d like to compare site features based on just a browse through those sites, Microsoft would like to hear your opinion.
The survey will be available here until July 27, 2012.
The C# Language Specification states on §7.5.1.2 that “(…) the expressions or variable references of an argument list are evaluated in order, from left to right (…)”.
So, when this code is compiled with the C# 4.0 compiler:
static void M(
int x = 10,
int y = 20,
int z = 30)
{
Console.WriteLine(
"x={0}, y={1}, z={2}", x, y, z);
}
static void Main(string[] args)
{
int a = 0;
M(++a, z: ++a);
}
and run, this unexpected output is obtained:
x=2, y=20, z=1
In fact, fixing this compiler flaw was the cause of one of the few breaking changes introduced in C# 5.0.
Using the 5.0 compiler, the expected result is obtained:
x=1, y=20, z=2
To avoid this type of surprises, expression evaluation should be avoided in argument lists.
With this code:
int a = 0;
int i = ++a;
int j = ++a;
M(i, z: j);
the same result is obtained for both C# 4.0 and C# 5.0:
x=1, y=20, z=2
(This content was written based on Silverlight for Windows Phone, but might be valid for generic Silverlight.)
There are a many articles on MSDN (and all over the Internet) about globalization and localization of Silverlight applications in general and specifically Windows Phone 7 applications but I haven’t found any that uses a value converter.
If you read the documentation for the IValueConverter interface, you can see that both in the Convert and ConvertBack methods have a culture parameter of type CultureInfo.
And why would we need the culture for the conversion? Imagine the application is a shop that shows prices in more than one currency. Or the application is a currency converter.
The culture parameter is used as the culture of the conversion. Any place inside the Convert or ConvertBack methods where a CultureInfo or IFormatProvider instance is need, the culture parameter should be used:
public class MoneyValueConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value != null)
{
return string.Format(culture, "{0:C}", value);
}
return null;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
The value of the culture parameter is determined in the following order:
-
-
The first case is very straightforward:
<TextBlock Text="{Binding Euros, Converter={StaticResource MoneyValueConverter}, ConverterCulture=pt-PT}" />
<TextBlock Text="{Binding Dollars, Converter={StaticResource MoneyValueConverter}, ConverterCulture=en-US}" />
But that should only be used when the culture of the conversion differs form the application culture or has an explicit value. The second case is the most frequently used and that’s where things get complicated. The value of the Language property of an element, if not explicitly set, is inherited from its container. In the case of Windows Phone 7, up to the phone application frame. And it’s never null.
I was expecting that the value of the Language property of the phone application frame would reflect the value of the current culture but, as far as I can tell, it’s always en-US.
So, if, unless explicitly set, the language is always en-US. How to specify which culture to use inside the value converter methods? The current culture could be used, but how to know if the language has been changed or the culture has been explicitly specified?
The solution is setting the language on the phone application frame and always to be able to use the culture parameter inside the converter methods:
this.RootFrame = new PhoneApplicationFrame
{
Language = XmlLanguage.GetLanguage(CultureInfo.CurrentCulture.Name)
};
The correct way to get the XML language would be to use the IetfLanguageTag property of the current culture, but that property is not available on Silverlight.
As far as I could find, you won’t get into trouble unless you’re dealing with Chinese cultures. But if you’re like me, you’ll probably be publishing your applications worldwide.
It’s not an hard problem to solve, though. A couple of extension method can solve it:
public static class CultureInfoExtensions
{
public static XmlLanguage GetXmlLanguage(this CultureInfo culture)
{
return XmlLanguage.GetLanguage(culture.GetIetfLanguageTag());
}
public static string GetIetfLanguageTag(this CultureInfo culture)
{
switch (culture.Name)
{
case "zh-CHT":
return "zh-Hant";
case "zh-CHS":
return "zh-Hans";
default:
return culture.Name;
}
}
}
And now the language of the root phone application frame can be properly initialized:
// Avoid double-initialization
// Do not add any additional code to this method
private void InitializePhoneApplication()
{
Debug.WriteLine("{0} >> InitializePhoneApplication", DateTime.Now.Ticks);
if (this.phoneApplicationInitialized)
{
return;
}
// Create the frame but don't set it as RootVisual yet; this allows the splash
// screen to remain active until the application is ready to render.
this.RootFrame = new RadPhoneApplicationFrame
{
Language = CultureInfo.CurrentUICulture.GetXmlLanguage()
};
this.RootFrame.Navigated += CompleteInitializePhoneApplication;
// Handle navigation failures
this.RootFrame.NavigationFailed += RootFrame_NavigationFailed;
// Ensure we don't initialize again
this.phoneApplicationInitialized = true;
}
Resources:
Microsoft Patterns & Practices has released a book with guidance on Testing for Continuous Delivery with Visual Studio 2012 RC.
The book and its content can be found both in the MSDN site and the CodePlex site.
I’m deeply honored to have been part of the review panels.
Recently, I’ve released a Windows Phone application to explore and use contact information.
In this application I used components and/or guidance from:
In future posts, I’ll be showing some tips, tricks and components I’ve used in this application.
Explore and use your contacts’ information.
Search contacts by:
- name
- phone number
- e-mail address
- physical address
- websites
- company
- job title
- significant others
- children
- notes
* Trial limitations The trial version is fully functional but will show a purchase reminder and might show ads.
* Application limitations
The Windows Phone system imposes some limitations on application developers.
It is not possible to:
- access twitter information
- access linkedin information
- uniquely identify the contact
- change or provide access to change the contact information
* Privacy statement This application does not make any use of the contacts information other than displaying and searching it. When ads are displayed, however, device information might be sent to the ad provider (
smaato Privacy Policy).
Sometime ago I wrote a predicate equality comparer to be used with LINQ’s Distinct operator.
The Distinct operator uses an instance of an internal Set class to maintain the collection of distinct elements in the source collection which in turn checks the hash code of each element (by calling the GetHashCode method of the equality comparer) and only if there’s already an element with the same hash code in the collection calls the Equals method of the comparer to disambiguate.
At the time I provided only the possibility to specify the comparison predicate, but, in some cases, comparing a hash code instead of calling the provided comparer predicate can be a significant performance improvement, I’ve added the possibility to had a hash function to the predicate equality comparer.
You can get the updated code from the PauloMorgado.Linq project on CodePlex,
When I was localizing a Windows Phone application I was developing, I set the argument on the constructor of the AssemblyCultureAttribute for the neutral culture (en-US in this particular case) for my application.
As it was late at night (or early in the dawn
) I went to sleep and, on the next day, the application wasn’t launching although it compiled just fine.
I’ll have to confess that it took me a couple of nights to figure out what I had done to my application.
Have you figured out what I did wrong?
The documentation for the AssemblyCultureAttribute states that:
The attribute is used by compilers to distinguish between a main assembly and a satellite assembly. A main assembly contains code and the neutral culture's resources. A satellite assembly contains only resources for a particular culture, as in [assembly:AssemblyCultureAttribute("de")]. Putting this attribute on an assembly and using something other than the empty string ("") for the culture name will make this assembly look like a satellite assembly, rather than a main assembly that contains executable code. Labeling a traditional code library with this attribute will break it, because no other code will be able to find the library's entry points at runtime.
So, what I did was marking the once main assembly as a satellite assembly for the en-US culture which made it impossible to find its entry point.
To set the the neutral culture for the assembly resources I should haveused (and eventually did) the NeutralResourcesLanguageAttribute. According to its documentation:
The NeutralResourcesLanguageAttribute attribute informs the ResourceManager of the application's default culture, and also informs the ResourceManager that the default culture's resources are found in the main application assembly. When looking up resources in the same culture as the default culture, the ResourceManager automatically uses the resources located in the main assembly instead of searching for a satellite assembly. This improves lookup performance for the first resource you load, and can reduce your working set.
.png)
Microsoft patterns & practices symposiums are held regularly in the U.S. and abroad. Most of the speakers are from the Microsoft patterns & practices (p&p) team. The event is aimed primarily at software architects, developers, and technical managers. patterns & practices develops applied engineering guidelines to help software developers and architects build great solutions on the Microsoft platform.
Read more…
More Posts
Next page »