Showing posts with label WPF. Show all posts
Showing posts with label WPF. Show all posts

Monday, June 27, 2011

Windows 8 for software developers: the Longhorn dream reborn?

images?q=tbn:ANd9GcQGGVP3wdbIPh2wZ9ZeOxD2-fy9HvDSF_yGtXRKzly8JtTI2r5S&t=1

A brave new world
Windows 8 will ship with a pair of runtimes; a new .NET runtime (currently version stamped 4.5), and a native code C++ runtime (technically, COM, or a derivative thereof), named WinRT. There will be a new native user interface library, DirectUI, that builds on top of the native Direct2D and DirectWrite APIs that were introduced with Windows 7. A new version of Silverlight, apparently codenamed Jupiter, will run on top of DirectUI. WinRT and DirectUI will both be directly accessible from .NET through built-in wrappers.

WinRT provides a clean and modern API for many of the things that Win32 does presently. It will be, in many ways, a new, modern Win32. The API is designed to be easy to use from "modern" C++ (in contrast to the 25 year old, heavily C-biased design of Win32); it will also map cleanly onto .NET concepts. In Windows 8, it's unlikely that WinRT will cover everything Win32 can do—Win32 is just so expansive that modernizing it is an enormous undertaking—but I'm told that this is the ultimate, long-term objective. And WinRT is becoming more and more extensive with each new build that leaks from Redmond.
WinRT isn't just providing a slightly nicer version of the existing Win32 API, either. Microsoft is taking the opportunity to improve the API's functionality, too. The clipboard API, for example, has been made easier to use and more flexible. There will also be pervasive support for asynchronous operations, providing a clean and consistent way to do long-running tasks in the background.

DirectUI is built around a core subset of current WPF/Silverlight technology. It includes support for XAML, the XML language for laying out user interfaces, and offers the rich support for layouts that Win32 has never had. This core will give C++ programs their modern user interface toolkit and, at its heart, it will be the same toolkit that .NET developers use too. (DirectUI is a name Microsoft has used before, internally, for a graphics library used by Windows Live Messenger. The new DirectUI appears to be unrelated.)

Jupiter is essentially Silverlight 6; a fully-featured, flexible toolkit for building applications. The exact relationship between DirectUI and Jupiter isn't entirely clear at the moment. It's possible that they're one and the same—and that DirectUI will grow in functionality until it's able to do everything that Silverlight can do. It's also possible that DirectUI will retain only core functionality, with a more complete framework built on top of its features. Another option is that Jupiter refers specifically to immersive, full-screen, touch-first applications.


Read more: Ars technica
QR: windows-8-for-software-developers-the-longhorn-dream-reborn.ars

Workaround For Crash In Performance Profiling Tools for WPF

Introduction
Every WPF developer knows the situation where you have a large line-of-business application, you’ve implemented all the features and when you finally run it on real data – it runs s-l-o-w.


Optimization Time!

Optimization for performance is fun since a 1% change of code gets you 99% change in performance. However, finding the one location you should change can be a pain.
This is why we’ve invented performance profilers. Profilers can help you pin-point the problem.


WPF?

WPF applications performance problems can usually be categorized to several kinds, for example, layout related, rendering related, etc.
Following is a nice list of common places to optimize when you work with WPF applications.
Microsoft provides a profiler specifically tuned for finding WPF related issues. You can find the installation guidelines on MSDN.
Note: if this is the first time you use it, and you don’t get the data, try the patch mentioned in this post.
When the profiler does work, it produces very interesting information.

For example, in the following image we can see the visual tree on the left and in it the hot element (painted red) where a lot of CPU cycles went (either due to rendering or layout).

Read more: Arik Poznanski's Blog

Sunday, June 26, 2011

Creating a Radial Effect in Blend

Today i'm going to show you how to create the radial effect i use in my free game Apple Bin (shameless plug, check it out here ).


ScreenShot_Main.png

There are a couple of advantages in doing this in blend. Download size is a lot smaller and you can animate colours rotation scale etc.
I'm doing this on windows phone, but same technique can be used in WPF or Silverlight.
Fire up blend and add a canvas on your page.

Canvas.png

Read more: Escape development

WPF/Silverlight Data Binding Tip: FallbackValue

Consider the following piece of XAML (part of an Image Viewer application), that wants to set the Window title (in WPF) based on the currently loaded image file:

Title="{Binding ImagePath, StringFormat=Image Viewer ({0})}"

This assumes that a DataContext exists, and exposes a property named ImagePath. This works well if such an object actually exists. But what happens when the application starts up and there is no image loaded yet, meaning the DataContext remains null? The Title would show nothing, because the binding fails. How can we fix that?
One way would be to create a dummy DataContext with the ImagePath property set to some value we want. But that’s cumbersome and limiting. What if we wanted a completely different title when there is no image?

Read more: Pavel's blog

Sunday, June 19, 2011

Premature cries of Silverlight / WPF skill loss. Windows 8 supports all programming models

Summary
  • Windows 8 supports applications being built in C# / XAML / VB.Net / C++ / HTML+JS.
  • The new UI framework ‘Jupiter’ allows applications to be written in your language of choice. This is similar to how the .Net framework allowed people to code against the framework in their language of choice.
  • Jupiter seems to be a ‘Next generation’ XAML based framework
  • I’m more excited about the new possibilities coming in the new Jupiter XAML programming model than the misconception that HTML+JS is the only way to create apps.
History
In the last few weeks, the internet has been in frenzy over the newly released demo video of Windows 8. In the video there is only mention of the new “Immersive applications” being created in a mixture of HTML + Javascript. People took this as more evidence that WPF & Silverlight are dead. Which hasn’t helped after the lack of attention which caused events like Silverlight Firestarter to be needed, or the http://FixWPF.org movement. It also doesn’t help when Microsoft have remained tight lipped even after an outcry from developers. The famous thread on the Silverlight forums has seen over 13,000,000 views. Which is more than the forums usually see in a single month.


Digging into the Windows 8 leak
A few people have been digging into the Windows 8 Milestone 3 leak and peeking into the UI framework and .dlls that exist. The most vocal of these have been @JoseFajardo and people in this forum thread http://forums.mydigitallife.info/threads/26404-Windows-8-(7955)-Findings-in-M3-Leak
What people have found so far is that while yes it is possible to create applications using HTML + Javascript, there is a whole new framework laying underneath that can be programmed against by almost any language / framework.

The first piece of the puzzle comes from the new application model for creating applications. There are a number of codenames here that need to be sorted out
  • DirectUI: The underlying framework that creates, draws the visual elements on the screen.
  • Jupiter: The new packaging format of applications on Windows 8. Allows apps to be written in language of choice.
  • Immersive applications: Current theory is that these are apps that execute within the ‘new shell’ in windows 8. And are aware of being split paned and resized. Like was shown with the RSS feed reader.
Read more: Burela's house-o-blog

Wednesday, June 15, 2011

patterns & practices: Project Silk

FileDownload.aspx?ProjectName=silk&DownloadId=233650


Overview
Project Silk provides guidance for building cross-browser web applications with a focus on client-side interactivity. These applications take advantage of the latest web standards like HTML5, CSS3 and ECMAScript 5 along with modern web technologies such as jQuery, Internet Explorer 9, and ASP.NET MVC3.

To illustrate this guidance, the project includes a reference implementation called Mileage Stats that enables its users to track various metrics about their vehicles and fill-ups. Much of the effort in building Mileage Stats was applied to the usability and interactivity of the experience. Animations were included to enhance the enjoyment of the site and AJAX is used to keep the interface responsive and immersive. A great deal of care was also taken to ensure the client-side JavaScript facilitates modularity and maintainability. To accomplish these design goals, the JavaScript code was structured into “widgets” that benefit from the jQuery UI Widget Factory.

About the Mileage Stats RI
The Mileage Stats RI is a multi-page interactive web application where the pages are rendered without requiring a postback. This creates the illusion of a desktop application. The lack of postbacks enable rich UI transitions between states (pages.) The browser application runs very fast because of the client-side data caching.
The Mileage Stats RI JavaScript is modularized using jQuery UI Widgets. The widgets allow breaking the UI into small discrete stateful objects; providing a clean separation of responsibilities and concerns. See the Widget QuickStart (included with the latest download) for an example application that uses the jQuery UI widget factory.

Read more: Karl of WPF
Read more: Codeplex

Monday, May 30, 2011

How to customize an ItemsControl

Introduction
If you are a Silverlight developer there will be a moment when you’ll look at a ListBox and not be happy with its default behavior. You are not exactly a beginner – you know how to style and retemplatize controls and even how to write your own custom controls – in fact you did that quite a few times. Depending on what changes are needed you’ll consider different solutions. Modifying the style and template of the ListBox comes to mind but it is not very clear how to achieve some of the customizations even if you are willing to modify the template of the ListBox. If the changes you need are substantial you may be willing to write a custom control but in the case of a ListBox this appears to be more difficult than expected. A ListBox is not just a simple control. It is a container that manages a collection. And it is more than a container in the sense that a Grid or a Canvas are containers. A ListBox has an ItemsSource that can be bound to a data source. Writing a custom ListBox is quite different than writing a custom Panel.

 If you recognize yourself in this, then this article is for you.
You will see that in most cases customizing a list is not that hard. A couple of things are worth mentioning from start. First, there are plenty of ways you can customize a ListBox without needing to write a custom control. Second, the main character in this story is the class ItemsControl and not ListBox. You may be more familiar with the ListBox but most of the concepts we are going to analyze belong to the ItemsControl. If you get to write a custom list it is much more likely that you’ll inherit your class from ItemsControl rather than from ListBox.
The examples discussed in this article are illustrated in a sample Silverlight application you can view at http://www.ladimolnar.com/Projects/ItemsControlDemo. You can download the code from http://www.ladimolnar.com/Sources/ItemsControlDemo.zip.


When you don’t need to customize anything at all
We’ll start with a very simple case but one that surprisingly gives headaches to a lot of people. Let’s suppose you need to show a ListBox that does not have any mouse over or selection effect. Actually your list does not even have the concept of “selected”. It seems that the otherwise useful features of the regular ListBox are just getting in your way.
The solution to this problem is very simple. All you have to do is to replace the ListBox with the ItemsControl. The ListBox itself is an ItemsControl with additional features that in this case you don’t need. As you see in Figure 1, the ItemsSource will allow you to bind to the data and the ItemTemplate will allow you to specify the visuals in the same way they do for a ListBox.
<ItemsControl
    ItemsSource="{Binding ProductList}"
    ItemTemplate="{StaticResource ProductItemTemplate}" />
Figure 1
The inner workings of an ItemsControl
Before we go any further, it will be useful to talk a little bit about how the ItemsControl class works. When things will be simpler to illustrate with a ListBox I will refer to it as well but all the fundamental concepts discussed here apply to both. Remember that ListBox inherits from ItemsControl.

Read more: LadiMolnar.com

Thursday, May 26, 2011

Things to consider when building a browser-based WPF application

Although WPF browser-based applications are not that popular with the growing interest in Silverlight, HTML5 and JavaScript (yes, I said JS), those still have a niche due to the capabilities offered by them. Not many developers know that the advantage of XBAP (WPF browser-based) applications is the fact that it is possible to directly invoke OS calls from the application that runs in the browser. Although with great power comes great responsibility, it is very possible to use XBAP apps in a much broader context compared to standard Silverlight applications.

So here are some points to remember when developing XBAP applications.
Full trust apps will require a certificate
In order to be able to access the OS capabilities (even components like the WebBrowser) will require the application to have a certificate installed on every client machine. This is not that big of an issue if the application is used internally, where people can set a specific security level and installing an internal certificate is not a problem. For external applications, users might be a bit hesitant if the certificate comes outside the trusted zone.
The default certificate that is assigned to an application will not be enough because it is assigned to a test machine and will only work for a short period of time. The solution here is to generate your own certificate and make it available to users who will use the app. Instructions on how to do this are available here.
Make sure that you re-size the application properly
When the application runs inside the browser, you never know what size it will have. That being said, implement  a simple re-sizing mechanism. For example, in one of the applications I was working on I did this:

The Page (content host) has no explicit size limits defined.
Using a Canvas control instead of the default Grid to define the page layout.
When the page is resized, I am handling this in the SizeChanged event handler:

this.SizeChanged += new SizeChangedEventHandler(Page1_SizeChanged);

The internals of the event handler look like this:

void Page1_SizeChanged(object sender, SizeChangedEventArgs e)
{
WHost.Height = this.ActualHeight;
WHost.Width = this.ActualWidth;
}

Here, WHost is a control inside the Canvas.
Be ready for deployment nuances
This is mainly tied to the fact that deployment is done through ClickOnce. Also, another important requirement for an XBAP application is the presence of .NET Framework 3.0 on the client machine. This might become a serious roadblock on *nix and Mac machines. That being said, Silverlight is less restrictive in this context, but some features will be removed (e.g. native access to the OS).
IE doesn't "like" XBAP applications by default. Other browsers - not so much, either.

Read more: .NET Zone

Tuesday, May 24, 2011

Simple WPF Page Transitions

Introduction / Background 
I have a little side project that I am working on which has multiple pages of information that need to be displayed, and I wanted a slicker way to transition between pages (UserControls) than just popping them into and out of existence (bad for the eyes).

My desire was to have better looking transitions, and this lead me to develop a very simple control library with several animations built in for more elegant page switches. 
The following page transition types are currently included in this version of the control:

Fade
Slide 
SlideAndFade
Grow
GrowAndFade
Flip 
FlipAndFade
Spin

The control itself is very simple... it consists of a UserControl (PageTransition), which contains all of the translation logic.  Inside this control, there are several animations in the UserControl.Resources tag, defining all of the available animations.  There is also an enum (PageTransitionType) which is mapped as a DependencyProperty that defines which animations are available to the users of the control.

Read more: Codeproject

Thursday, May 19, 2011

Шаблон проекта многоязычного WPF приложения

Введение
Локализация приложения на WPF — не легкое занятие. Практически любое пособие по локализации WPF изобилует деталями и ручными шагами для реализации локализованного приложения.

Существующие решения
Локализация с помощью утилиты LocBaml, описанная в руководстве по локализации от Microsoft имеет множество преимуществ, однако сложна для поддержки. André van heerwaarde, в своей статье предложил упростить это решение с помощью настроенного шага сборки, он же написал утилиты для слияния переведенных текстовых фрагментов. Однако, в его статье, так же много ручных шагов.

Шаблон проекта Visual Studio
Я предлагаю воспользоваться созданным мной шаблоном локализованного приложения, для начала работы над многоязычным WPF приложением. Проект, созданный с помощью этого шаблона, уже содержит все необходимые утилиты, для локализации, а так же максимально автоматизирует процедуры локализаци в процессе разработки.
В процессе разработки приложения вы добавляете новые XAML файлы, не заботясь о локализации. По завершению внесения изменений выполните сборку проекта. 
Настроенный шаг перед сборкой вызовет msbuild /t:updateuid [Имя проекта].csproj. Этот шаг автоматически добавляет x:Uid в каждый элемент, содержащий текстовые элементы. 
После чего в процессе сборки будет автоматически запущен LocBaml, который найдет все текстовые элементы в XAML файлах и создаст CSV файл, содержащий текстовые элементы. 
Следующий шаг запустит утилиту MergeLocBamlCsv от André van heerwaarde. В результате чего предыдущие переведенные фрагменты будут объединены с новыми. Утилита StripLocBamlCsv вырежет неиспользуемые элементы из CSV файлов. 
Единственное, что вам придется сделать вручную, это добавление новых языков и собственно сам перевод.

Добавление нового языка

Для добавления нового языка в проект вам придется:
скопировать локализацию нейтрального языка в новый CSV файл
copy Translation\Translate.csv Translation\Translate.ru-RU.csv 
открыть файл проекта в текстовом редакторе и после строчек:

<LocBamlCsv Include="Translation\Translate.de-DE.csv">
 <Culture>de-DE</Culture>
</LocBamlCsv>
добавить новый язык, например
<LocBamlCsv Include="Translation\Translate.ru-RU.csv">
 <Culture>ru-RU</Culture>
</LocBamlCsv>

После этого нужно переоткрыть проект в Visual Studio, если проект уже был открыт, то среда разработки спросит, желаете ли вы переоткрыть проект, для отражения внесенных изменений, ответьте 'Да'.
Если вы не допустили ошибок, то во вновь открытом проекте в папке Translation появится новый файл Translate.ru-RU.csv

Read more: Habrahabr.ru

Wednesday, May 18, 2011

A Complete Guide to Expression Blend 4 Shortcut Keys

In this post, I will share you some important Shortcut keys of Microsoft Expression Blend 4. If you are working with Expression Blend 4, this will definitely help you to improve your daily productivity work. Keep the list with you always to best use of the Shortcut keys in Blend 4 while designing your XAML page.

If you have more shortcuts, please share those to me and I will include them here as the key resource. Thanks for your support. If you are a XAML developer and using Expression Blend 4, this post will really help you. You will be able to download the free eCopy of the List at the end. Here is the list of important shortcut keys which can improve your productivity while working in Blend 4:


Shortcut KeyDescription
F1Open Expression Blend User Guide (Help File)
Ctrl + +Zoom in designer screen
Ctrl + -Zoom out designer screen
Ctrl + 0Fit entire page to designer screen
Ctrl + 1Zoom to Actual Size
Ctrl + 9Fit selection to the designer screen
F9Show Handles
Ctrl + Shift + HShow object boundaries
F11Switch Active document view
F2Edit text or Rename the selected control
Ctrl + EEdit control
Ctrl + Shift + ]Bring control to Front
Ctrl + ]Bring control Forward
Ctrl + Shift + [Send control to Back
Ctrl + [Send control Backward
Ctrl + GGroup into a Grid control

Read more: Codeproject

How to access Control Template parts from Code Behind

Here is the last chapter of the series for Silverlight Custom Control. In this article, we will learn how to access the template parts from code behind to do various operations in the UI front.
Hope you read the previous three articles and are familiar with the Custom control as of now. This article will help you to understand accessibility of the template parts from the code. So, let's start discussing now. I appreciate your feedback as always.

Background
I hope you read my previous three articles. Those will help you to understand the context of this one very easily. If you didn't read them or want to brush up before starting this chapter, find them here:
How to create a Custom Control in Silverlight?
How to design a Custom Control by editing the Part Template?
How to implement Template Binding in Silverlight Custom Control?
Once you are familiar with the previous code, let's start with this one. We will use the same example here which will give you better visualization on the sample code.
Brush up Previous Chapter on Parts
In our previous article, we discussed about template parts. These are the UI elements available in your style of the custom control. Generally, we prefix their name with PART_. In the control's class, we initialize them with the attribute called TemplatePart as shown below. This is to make sure that the metadata of the class shows them properly and your user can easily understand which UI elements you used there. Also, this is beneficial for you to easily access the parts in the file.

image%5B3%5D.png?imgmax=800

Once you marked the template parts in the class, you can declare the member variables to store the instance of those parts, so that you can access them easily. Remember that only get the instance whenever required. If you need them multiple times, better declare them as member variable and use throughout the life of the control.

Declaring Private Members for Part Instance

We need to declare the member variables now to store the instance of the template parts. In this example, we used three parts called Border, TextBlock and ContentPresenter. Declare the private instances of them. This is simple enough. The below screenshot will help you to understand:

Read more: Codeproject

Silverlight / WPF: Is it possible to bind to an explicit interface indexer implementation?

The WPF binding system allows you to bind to Indexers and properties and it also have a nice feature that allows you to bind to the explicit implementation of interfaces’ members, allowing you to resolve possible ambiguities if the properties have the same names, let’s consider this simple example you have the following two interfaces and a class that implements them:

public interface IFirst
{
   string this[string index] { get; }
   String Name { get; }
}
public interface ISecond
{
   string this[string index] { get; }
   String Name { get; }
}
public class Entity : IFirst, ISecond
{
   public string Name
   {
       get { return "Class Name"; }
   }
   
   public string this[string index]
   {
       get { return "Class Indexer"; }
   }

And you can bind them with a syntax like this:

<stackpanel>
   <textbox text="{Binding Path=Name, Mode=OneWay}">
   <textbox text="{Binding Path=(local:IFirst.Name), Mode=OneWay}">
   <textbox text="{Binding Path=(local:ISecond.Name), Mode=OneWay}">
   <textbox text="{Binding Path=[0], Mode=OneWay}">
   <!--binding attempt 1 -->
   <textbox text="{Binding Path=(local:IFirst)[0], Mode=OneWay}">
   <textbox text="{Binding Path=(local:ISecond)[0], Mode=OneWay}">
   <!--binding attempt 2 -->
   <textbox text="{Binding Path=(local:IFirst.Item)[0], Mode=OneWay}">
   <textbox text="{Binding Path=(local:ISecond.Item)[0], Mode=OneWay}">
</textbox></textbox></textbox></textbox></textbox></textbox></textbox></textbox></stackpanel>

....

Silverlight currently does not support binding to explicit interface implementations: when you try to write something similar to that the Xaml parser give you the E_UNEXPECTED error. I think this is one of the reasons why the Silverlight Team introduced a new interface for validation and error reporting like INotifyDataErrorInfo instead of just relying on the IDataErrorInfo typical to WPF: the IDataErrorInfo indexer (used to access the error’s collection) most of the time it’s implemented using explicit interface implementation; I would really like to see a porting of that interface in WPF soon cause I think it has a better design than the current IDataErrorInfo.

Read more: Windows Phone 7

DirectX for WPF

Project Description

C# DirectX samples, based on SharpDX and rendering within a WPF user interface.
Making it easy for a C# / WPF developer to start learning and programing with DirectX
The purpose of this project is to provide a set of sample showing off DirectX in C# from a WPF developer perspective.

It is intended to be a starting point for any C# / WPF developer curious about DirectX.
It provide some vanilla implementation that get DirectX up and running in WPF.
It runs on SharpDX (pure C# DirectX wrapper), Alexandre Mutel's blog
There is a base library named SharpDX.WPF (not affiliated with SharpDX, but on top of it), that provides the following
A DXImageSource : D3DImage class that has implement SetBackBuffer() for D3D10, D3D11 Texture2D
A DXElement : FrameworkElement class that can render arbitrary DirectX content
Some vanilla Direct3D Device wrapper classes (D3D and its subclass) that implement the interface to attach to DXElement
Some useful Direct3D utility class. So far: FPS, ConstantBuffer, DeviceUtil
I also added the source code from Nexus and Meshellator which I hope to do something with later on
Also note that (currently) this library is used a hacked version of SharpDX (as explained in the project README)..
WARNING You will need the DirectX SDK to compile and run those sample.

Read more: Codeplex

Monday, May 09, 2011

Merula shell

Project Description
Merula shell is a Windows shell replacement. Use the library of Merula Shell to create your own windows shell in WPF. Currently there is a DEMO avaible to show you wat Merula shell can do.

Read more: Codeplex

Sunday, May 08, 2011

PortableTPL for Silverlight / Windows Phone and XBox

Project Description
PortableTPL is a portable project inspired by the Task Parallel Library.
It can be used with .Net 4.0, Silverlight 4.0, XNA 4.0 for XBox 360 and Silverlight for Windows Phone.
PortableTPL supports following features:

Task
Task<T>
Task Continuation
Task Cancelleation with CancellationTokenSource
AggregationException
Parallel.For
Parallel.ForEach
Schedulers

Read more: Codeplex

Tuesday, May 03, 2011

Drop Shadow / Glow Effect using XAML

As most of know Silverlight has built in effects, however these effects can be pretty memory intensive. One solution would be is to use an image for the shadow, however if you’re planning for the object casting the shadow or glow to dynamically scale the image will either pixelate or not scale. The other solution is to create your drop shadows using rectangles in XAML.
Here I illustrate the memory usage of a drop shadow effect, a drop shadow built in XAML, and no drop shadow at all on a Dialog Window in Silverlight.

We can see that no drop shadow is the winner in terms of performance but a drop shadow built with XAML is a very close second using only an extra 12kb. The Built in effect in Silverlight uses over 3,000 kb more!

So how do you create a drop shadow effect in XAML? It’s actually very easy. Just create an offset grid with negative margins (this will be the distance from you object the drop shadow will cast) and add a series of Rectangles with varying corner radiuses, margins, and opacity.

<Grid Margin="-2,-2,-6,-6">
<Rectangle Stroke="Black" Margin="5" RadiusX="7" RadiusY="7" Opacity="0.3"/>
                <Rectangle Stroke="Black" Margin="4" RadiusX="8" RadiusY="8" Opacity="0.25"/>
                <Rectangle Stroke="Black" Margin="3" RadiusX="9" RadiusY="9" Opacity="0.2"/>
                <Rectangle Stroke="Black" Margin="2" RadiusX="10" RadiusY="10" Opacity="0.15"/>
                <Rectangle Stroke="Black" Margin="1" RadiusX="11" RadiusY="11" Opacity="0.1"/>

Read more: Infragistics

Sunday, May 01, 2011

How to Add WPF to VSTO

שילוב WPF באפליקציית VSTO מעשיר מאוד את חוויית המשתמש. לדוגמא:
VSTOAndWPF.png

להלן השלבים לשילוב Control של WPF באפליקציית VSTO ב-Visual Studio 2010:
1. יצירת פרוייקט Office Add-in לדוגמא Word Add-in
2. Add Item ובחירה של
Ribbon (Visual Designer)
3. Add Item ובחירה של
Windows Form
4. Add Item ובחירה של
User Control (WPF)
5. הוספת רכיב Button ל-Ribbon
6. הקוד של הכפתור, לדוגמא:
WindowsForm form = new WindowsForm();
form.Show();
7. מה-ToolBox, הוספת Control בשם ElementHost מתוך קבוצה בשם WPF Interoperability לתוך ה-Windows Form
8. נפתח Design לבחירת User Control של ה-WPF בפרוייקט.

Read more: Dudi Nissan's Blog

Thursday, April 28, 2011

InfoStrat Motion Framework

Project Description
InfoStrat Motion Framework enables you to easily use motion tracking in your WPF applications with depth sensors such as Kinect and PrimeSensor.

Read more: Codeplex

Wednesday, April 27, 2011

Various Clients and Forms Authentication

Scenarios
In each of the below scenarios, forms authentication is used to secure access to the ASP.NET MVC endpoints and WCF services.
WPF accessing WCF services
WPF accessing MVC endpoints
Windows Phone 7 accessing WCF services
Desktop and mobile browsers accessing ASP.NET MVC website pages
jQuery accessing MVC endpoints
While I have not included the code for a Windows Phone 7 to access MVC endpoints that is a supported scenario as well.
Requirements
Visual Studio 2010
SQL Express 2008
Windows Phone 7 tools
If you don’t have these and don’t want to see this project, you can just remove the Windows Phone 7 project from the solution.

Background
I’ve been working on Stuff v2; a movie, game, and books application. Its primary use case is, "I’m at the store and don’t remember if I have a particular movie, game, or book. I need to determine if I have it; if not, then check the online price and ratings before making the purchase."
Given the varied application clients and devices, ASP.NET forms authentication seemed like the natural choice for authentication for the website, MVC3 JSON endpoints, and WCF services.
The reason I have varied client software and devices is more of a learning experience than an application requirement. I have other applications I want to write that will need to access the application from all my devices.

When I started programming the WPF client, I ran into a stone wall with respect to WPF accessing WCF services that are secured by forms authentication. This blog post is about getting over that stone wall.
Identifying the Problem Space
At the end of the day, the problem that needs solving is managing the forms authentication cookie or ticket.

Managing means, that after authenticating, the client must be able to retrieve the ticket returned in the response and include it in future requests to secured resources.
As you will see, client API’s vary across scenarios not only in coding patterns but in complexity as well.
Regardless of which client is accessing resources that require forms authentication, the following steps outline the required workflow:

Log in
Cache the ticket returned in the response
Include the ticket in subsequent requests
Setting up Forms Authentication
When I created the ASP.NET MVC3 application, VariousClients.Web, I used the MVC3 Internet template with the Razor view engine. This template sets up forms authentication and provides a pretty good out-of-box SQL Express membership system for you.
The below snippet from the web.config shows a few required changes:

<authentication mode="Forms">
    <!-- cookieless="UseCookies" is required by non-browser clients
                to authenticate using forms authentication-->
    <!-- production applications, change to requiresSSL="true"-->
    <forms timeout="2880" cookieless="UseCookies" loginUrl="~/Account/LogOn"
            requireSSL="false" />
</authentication>

Setting up the AuthenticationService
The System.Web.ApplicationServices.AuthenticationService is a built-in service that you can expose as a service endpoint on your website. This service exposes log in, log out methods for clients that access WCF endpoints requiring forms authentication. This service uses the membership provider defined in the web.config. After logging in, the service returns a ticket in the response, similar to forms authentication log in.
Adding the service is easy. First add a folder to the root of the website named, "Services". Into that folder, add a WCF service named Authentication.svc. Delete the generated service contract and code-behind files. Next replace the contents of the Authentication.scv file with the below code snippet.
<%@ ServiceHost Language="C#" Service="System.Web.ApplicationServices.AuthenticationService" %>

Now add the following to your web.config:

<system.web.extensions>
    <scripting>
        <webServices>
            <!-- for production applications, change to requiresSSL="true"-->
            <authenticationService enabled="true" requireSSL="false"/>
        </webServices>
    </scripting>
</system.web.extensions>

Rebuild your web application.
The Authentication.svc will now appear in the Add Service Reference dialog when adding service references in your client applications.

Read more: Karl on WPF