December 2009 - Artículos

TFS2008 y Las Malditas Fechas

Este post se lo dedico a El Bruno, fan numero uno de Silverlight y odio exacerbado al TFS (Ya me he vuelto a equivocar!!!). La cuestión es que llevábamos  unas cuantas horas con el famoso error 'TFS31003 your account does not have permissions to connect to the Team Foundation server'.

Y el usuario tenia acceso porque probábamos desde otro ordenador y conectábamos, pero desde ese ordenador ningún usuario tenia acceso al TFS, pruebas y pruebas de desinstalar el Team Client volver a instalar , borra cache del tfs, el SP1…, hasta que nos dimos cuenta que la fecha del ordenador estaba retrasada un día y el TFS al autenticarte comprueba que la fecha sea la misma entre el servidor y el cliente, pero en vez de decirte amablemente que las fechas no son correctas te da el bonito error de arriba.

Cuantas horas perdidas por una mal mensaje de error

Publicado por Oskar Alvarez | 4 comment(s)
Archivado en:

Deshabilitar uno o mas items de un ListBox en WPF

Después del puente una entrada sencillita. Esta fue una de las preguntas de MSDN, si se podía deshabilitar uno o mas items en una lista dependiendo del valor de una propiedad, y la respuesta por supuesto es si, lo tenemos que hacer con estilos pero es bien sencillo, solo hay que hacer un DataTrigger de  la propiedad que deshabilitara el item y poner la propiedad IsEnabled a False.

Aquí lo tenéis

 

  1. <ListBox>
  2.     <ListBox.ItemContainerStyle>
  3.         <Style TargetType={x:Type ListBoxItem}>
  4.             <Style.Triggers>
  5.                 <DataTrigger Binding={Binding YouProperty} Value="False">
  6.                     <Setter Property="IsEnabled" Value="False"/>
  7.                 </DataTrigger>
  8.             </Style.Triggers>
  9.         </Style>
  10.     </ListBox.ItemContainerStyle>
  11. </ListBox>

 

A disfrutarlo

Publicado por Oskar Alvarez | 1 comment(s)
Archivado en:

Reconocimiento del Texto de un Ink en WPF

En el proyecto que estamos realizando aparte de la entrada anterior necesitamos que en un Ink pasemos a texto lo que va escribiendo el usuario, esto es bastante sencillo si nos apoyamos en la clase InkAnalyzer que se encuentra en el assembly IAWinfx localizado en la ruta %ProgramFiles%\Reference Assemblies\Microsoft\Tablet PC\v1.7 y que solo se encuentra en los Tablet PC. Una vez añadido este assembly el código es muy sencillo.

 

El Xaml

 

  1. <Window x:Class="TestAnalyzer.Window1"
  2. xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  3. xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  4. Title="TestAnalyzer"
  5. SizeToContent="WidthAndHeight">
  6.     <Grid>
  7.         <StackPanel Orientation="Vertical">
  8.             <InkCanvas Name="inkCanvas" Width="600" Height="100" />
  9.             <TextBox Name="textBlock" />
  10.         </StackPanel>
  11.     </Grid>
  12. </Window>

 

Tenemos un InkCanvas y un TextBox donde se ira poniendo el texto que dibuje el usuario. para hacer el reconocimiento tenemos

 

  1. public partial class Window1 : System.Windows.Window
  2. {
  3.     InkAnalyzer _analyzer;
  4.     public Window1()
  5.     {
  6.         InitializeComponent();
  7.         inkCanvas.StrokeCollected +=
  8.         new InkCanvasStrokeCollectedEventHandler(inkCanvas_StrokeCollected);
  9.         inkCanvas.StrokeErasing +=
  10.         new InkCanvasStrokeErasingEventHandler(inkCanvas_StrokeErasing);
  11.         _analyzer = new InkAnalyzer();
  12.         _analyzer.ResultsUpdated +=
  13.         new ResultsUpdatedEventHandler(analyzer_ResultsUpdated);
  14.     }
  15.     void inkCanvas_StrokeErasing(object sender, InkCanvasStrokeErasingEventArgs e)
  16.     {
  17.         _analyzer.RemoveStroke(e.Stroke);
  18.         _analyzer.BackgroundAnalyze();
  19.     }
  20.     void inkCanvas_StrokeCollected(object sender,
  21.     InkCanvasStrokeCollectedEventArgs e)
  22.     {
  23.         _analyzer.AddStroke(e.Stroke);
  24.         _analyzer.SetStrokeType(e.Stroke, StrokeType.Writing);
  25.         _analyzer.BackgroundAnalyze();
  26.     }
  27.     void analyzer_ResultsUpdated(object sender, ResultsUpdatedEventArgs e)
  28.     {
  29.         textBlock.Text = _analyzer.GetRecognizedString();
  30.     }
  31. }

 

Y ya tenemos nuestro propio OCR

Publicado por Oskar Alvarez | 1 comment(s)
Archivado en:

ScreenCast de Silverlight

Hola hoy os vengo a presentar a mi compañero Javi Jimenez (Maquero convencido) al que arrastre hace mas o menos un año a este mundo de WPF y Silverlight, primero enseñaros su pagina web hecha en Silverlight donde se presenta profesionalmente y ver como un curriculum hecho en Silverlight queda de lo mas chulo (que mejor manera de presentarse uno mostrando que sabe hacer).

Podéis acceder a su pagina iamjavi.com

 

image

 

La segunda parte de este post enseñaros el ScreenCast que se ha currado cuyo titulo es  “Silverlight Creación de un UserControl"

Screencast.1 - Creación de un "UserControl" from IAMJAVI.com on Vimeo.

Echarle un vistazo, sobre todo aquellos que empezais en esta tecnología

Publicado por Oskar Alvarez | 4 comment(s)
Archivado en: ,

10 sesiones del PDC 09 que deberías ver

Del Blog de Pete Brown he sacado este extracto de las 10 sesiones (11 en realidad) que no debemos de dejar de ver acerca de nuestras tecnologias favoritas WPF y Silverlight

 

Top 10 11

1 CL09 How Microsoft Visual Studio 2010 Was Built with WPF 4

This is interesting both from a “how they did it” standpoint, as well as for the topic of putting a slick WPF user interface over C++ and dealing with things like Win32 interop

2 CL17 Building Sensor and Location-Aware Applications with Windows 7 and .NET Framework 4

The sensor and location platform is one of the coolest things to come out with Windows 7. I’ve had a ton of fun with the sensors, and will be trying out some of the location API stuff soon.

3 CL01 Microsoft Silverlight 4 Overview

Silverlight 4 was one of the big announcements at PDC. If you want an overview of all the new features in SL4, this is the session to watch. Plus, Karen is a great speaker and super smart.

4 CL21 Building Amazing Business Applications with Microsoft Silverlight and Microsoft .NET RIA Services

Brad Abrams and his team put together a great talk that covers all the new stuff in RIA Services. If you build Silverlight business apps, don’t miss this.

5 FT24 Building Extensible Rich Internet Applications with the Managed Extensibility Framework

This is the only session I was able to attend in-person at PDC. Glenn goes through what’s new in MEF and how to use it in Silverlight 4 applications. MEF also applies to desktop apps, Visual Studio add-ins, server-side apps etc, so make sure you watch this.

6 CL24 XAML Futures in Microsoft .NET Framework, Microsoft Silverlight and Tools

Rob and friends talk about some of the coolness in the new and upcoming Xaml stacks. They’ve done some awesome work here.

7 CL12 Developing with the Windows API Code Pack for the Microsoft .NET Framework

For folks using .NET 3.5SP1, the Windows API Code Pack provides access to the Windows 7 features offered in .NET 4, as well as a bunch of things (like sensors) that .NET 4 doesn’t include in the box.

8 CL10 Windows Presentation Foundation 4 Plumbing and Internals

If you want to understand the guts of WPF, this is the session.

9 FT03 Manycore and the Microsoft .NET Framework 4: A Match Made in Microsoft Visual Studio 2010

Most of us have multi-core CPUs with 2 as the norm, 4 pretty common and 6 coming to the mainstream in 2010. If you want to incorporate parallel computing into your apps, Stephen will show you how, and tell you about the support built into VS2010 to help you work with it.

10 CL15 Modern Graphics Using Windows 7 and Direct 3D 11 Hardware

DirectX 11 includes tons of cool new features. This talk focuses primarily on Direct 3D 11. If you code against Direct 3D for visualization, games or other apps, check this out.

11 SVC23 Using the Microsoft Sync Framework to Connect Apps to the Cloud

How do you connect desktop apps to the cloud, and handle synchronization and reliability concerns? If you’re considering tapping into the cloud from your existing or new local applications, check this out.

Publicado por Oskar Alvarez | 2 comment(s)
Archivado en:

Acceder a Word desde SilverLight

Con Silverlight 4 dentro de sus nuevas funcionalidades tenemos el acceso a objetos COM, aunque hay que indicar que solo podemos acceder con elevación de permisos. Esta nueva funcionalidad nos abre un nuevo camino de posibilidades, como por ejemplo interactuar con Word o Excel, y vamos a ver un ejmplo.

Añadimos la referencia al asembly Microsoft.CSharp.dll que se encuentra en Program Files/Microsoft SDKs/Silverlight/V4.0/Libraries/Client/ , creamos nuestro control

  1. <UserControl x:Class="SilverlightWord.MainPage"
  2.    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  3.    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  4.    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
  5.    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
  6.    mc:Ignorable="d"
  7.    d:DesignHeight="300" d:DesignWidth="400">
  8.     <Grid x:Name="LayoutRoot" Background="White">
  9.         <Button Content="Abrir Word" Width="100" Height="30" Click="Button_Click" />
  10.     </Grid>
  11. </UserControl>

Contiene un botón que abrirá Word e insertará un texto, tan sencillo como

 

 

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Net;
  5. using System.Windows;
  6. using System.Windows.Controls;
  7. using System.Windows.Documents;
  8. using System.Windows.Input;
  9. using System.Windows.Media;
  10. using System.Windows.Media.Animation;
  11. using System.Windows.Shapes;
  12. using System.Windows.Interop;
  13. namespace SilverlightWord
  14. {
  15.     public partial class MainPage : UserControl
  16.     {
  17.         public MainPage()
  18.         {
  19.             InitializeComponent();
  20.         }
  21.         private void Button_Click(object sender, RoutedEventArgs e)
  22.         {
  23.             dynamic word = ComAutomationFactory.CreateObject("Word.Application");
  24.             word.Visible = true;
  25.             dynamic doc = word.Documents.Add();
  26.             string insertText = "Aqui introducimos texto a Word desde Silverlight 4!";
  27.             dynamic range = doc.Range(0, 0);
  28.             range.Text = insertText;
  29.         }
  30.     }
  31. }

Si os fijáis estamos utilizando una nueva funcionalidad de C#4 que es dynamic que nos permite instanciar el objeto COM

 

Impresionante el camino que esta tomando Silverlight

Publicado por Oskar Alvarez | 3 comment(s)
Archivado en:

Como grabar Ink de WPF como BitMap

Hola, aparte de los enlaces interesantes que voy poniendo, seguiré con cosas de mi cosecha, lo siguiente me surgió en un proyecto y resumidamente tenemos un bitmap al cual le habíamos puesto un objeto Ink para que el usuario pintase por encima y a la hora de grabar grabase el Bitmap con lo dibujado por el usuario encima del Bitmap, es decir incrustar lo dibujado en el Bitmap creando un Bitmap nuevo (me explico como las gallinas)

 

Al grano, es muy sencillo aquí tenéis el código que renderiza como bitmap la problemática anterior

 

  1. // Renderiza el arbol visual de  InkCanvas' a RenderTargetBitmap
  2.             RenderTargetBitmap targetBitmap =
  3.                 new RenderTargetBitmap((int)inkCanvas1.ActualWidth,
  4.                                        (int)inkCanvas1.ActualHeight,
  5.                                        96d, 96d,
  6.                                        PixelFormats.Default);
  7.             targetBitmap.Render(inkCanvas1);
  8.             
  9.             BmpBitmapEncoder encoder = new BmpBitmapEncoder();
  10.             encoder.Frames.Add(BitmapFrame.Create(targetBitmap));
  11.             // Salva el fichero a disco
  12.             FileStream fs = File.Open(fileName, FileMode.OpenOrCreate);
  13.             encoder.Save(fs);
Espero que os sirva
Publicado por Oskar Alvarez | 1 comment(s)
Archivado en: