To my wish list for .Net 4.0: Linq to Entities


I am working with Entity Framework as model in a REST service, using the CollectionService<T> and i found a little issue in the behavior of Linq to Entities,this is well know but i hope a change in .Net 4.0

Currently Linq to Entities not supports projections that returns types with parameterized constructors, by instance for a method that return a IEnumerable<KeyValuePair<string, Course>> i wanna make

   1:  .Select(c => new KeyValuePair<string, CustomType>(c.StringProperty, c))
 

This projection for me is pretty natural, but thrown the next error: “Only parameterless constructors and initializers are supported in LINQ to Entities”

My workaround (model is an instance of my Entity Framework ObjectContext)

   1:  protected override IEnumerable<KeyValuePair<string, Course>> OnGetItems()
   2:          {
   3:                        
   4:              List<Course> Course = model.Courses.Select(c => new Course() { Code = c.Code, Description = c.Description, Name = c.Name, OpenDate = c.OpenDate }).ToList();
   5:              Dictionary<string, Course> returnCourse = new Dictionary<string, Course>();
   6:              Course.ForEach((Course item) =>
   7:              {
   8:                  returnCourse.Add(item.Code, item);
   9:              });
  10:   
  11:              return returnCourse;
  12:   
  13:   
  14:          }

See you

author: Juan Mestas J. (aka gotchas) | posted @ Sunday, October 11, 2009 11:18 PM | Feedback (0)

Microsoft TechCamp 09


Hi Folks,

This Tuesday 13th (yeah, i know good day for the supernatural) will be the first TechCamp at Lima-Peru, i am in charge of the session about Silverlight 3 in the develop of LOB Applications with Manuel Miranda (aka Mani) that will go to talk about UX (beyond decorations).

I would love hear your feedback for this session, what want you see? RIA Services? OOB Approach?

See you

author: Juan Mestas J. (aka gotchas) | posted @ Sunday, October 11, 2009 11:02 PM | Feedback (0)

Querying to XML structures that have a namespace


Yesterday working in a demo about WCF-REST Starter Kit (http://www.asp.net/downloads/starter-kits/wcf-rest/) i had a little issue to make a query to a XML Structure that includes a xml namespace (aka xmlns), the trick is very simple to get the value from each element in the structure, you should pass the XName in Elements method including the XNamespace

This is my XML structure

<ItemInfoList xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
- <ItemInfo>
  <EditLink>http://localhost:17673/Services/Courses.svc/S02</EditLink> 
- <Item xmlns:a="http://schemas.datacontract.org/2004/07/DotNetUniversity">
  <a:Code>S02</a:Code> 
  <a:Description>La Transferencia de Estado Representacional (Representational State Transfer) o REST es una técnica de arquitectura software para sistemas hipermedia distribuidos como la World Wide Web. El término se originó en el año 2000, en una tesis doctoral sobre la web escrita por Roy Fielding, uno de los principales autores de la especificación del protocolo HTTP y ha pasado a ser ampliamente utilizado por la comunidad de desarrollo.</a:Description> 
  <a:Name>REST</a:Name> 
  <a:OpenDate i:nil="true" /> 
  </Item>
  </ItemInfo>
- <ItemInfo>
  <EditLink>http://localhost:17673/Services/Courses.svc/S01</EditLink> 
- <Item xmlns:a="http://schemas.datacontract.org/2004/07/DotNetUniversity">
  <a:Code>S01</a:Code> 
  <a:Description>La Arquitectura Orientada a Servicios (en inglés Service Oriented Architecture), es un concepto de arquitectura de software que define la utilización de servicios para dar soporte a los requisitos del negocio.</a:Description> 
  <a:Name>SOA</a:Name> 
  <a:OpenDate i:nil="true" /> 
  </Item>
  </ItemInfo>
  </ItemInfoList>

My custom collection

   1:  private ObservableCollection<CourseViewModel> courses = new ObservableCollection<CourseViewModel>();

 

This is the code to query this structure and populate a collection of a custom entities, BTW i’m using Silverlight 3 with MVVM approach

   1:  public void LoadCatalog()
   2:          {
   3:              courses.Clear();
   4:              WebClient client = new WebClient();
   5:              client.DownloadStringCompleted += (source, args) =>
   6:              {
   7:                  if (args.Error == null)
   8:                  {
   9:                      IEnumerable<XElement> coursesXml = XElement.Load(new StringReader(args.Result)).Descendants("ItemInfo");
  10:                      foreach (var item in coursesXml.Descendants("Item"))
  11:                      {
  12:                          XNamespace ns = "http://schemas.datacontract.org/2004/07/DotNetUniversity";
  13:   
  14:                          bool hasOpenDate = !String.IsNullOrEmpty(item.Element(ns + "OpenDate").Value);
  15:                          DateTime openDate = default(DateTime);
  16:                          if (hasOpenDate)
  17:                          {
  18:                              DateTime.TryParse(item.Element(ns + "OpenDate").Value, out openDate);
  19:                          }
  20:   
  21:                          courses.Add(
  22:                              new CourseViewModel(
  23:                                  new Course()
  24:                                  {
  25:                                      Name = item.Element(ns + "Name").Value,
  26:                                      Code = item.Element(ns + "Code").Value,
  27:                                      Description = item.Element(ns + "Description").Value,
  28:                                      OpenDate = openDate,
  29:                                      OpenDateSpecified = hasOpenDate
  30:                                  }));
  31:                      }
  32:                  }
  33:              };
  34:              client.DownloadStringAsync(new Uri("http://localhost:17673/Services/Courses.svc/"));
  35:          }

 

See you

author: Juan Mestas J. (aka gotchas) | posted @ Sunday, October 11, 2009 10:50 PM | Feedback (0)

Webcast MSDN: Integrating IE8 Features: Accelerators, Web Slices, Search Providers with our Web Sites / Integrando nuestros sitios con Windows Internet Explorer 8 usando Aceleradores, Web Slices y Proveedores de Búsqueda


Internet Explorer 8 exposes new ways for deliver features from our sites directly to our users. In this session we learn to use the new features of IE8 such as accelerators, web slices and search providers and how to integrate it with our sites

Internet Explorer 8 expone nuevas formas de entregar la funcionalidad que su sitio ofrece directamente a sus usuarios. Venga a esta sesión para aprender cómo usar nuestras nuevas actividades, Web slices y mucho más e integrarlas con nuestros sitios

Webcast Link

http://www.mslatam.com/latam/mediacenter/wcdetail.aspx?EventID=1032422247&p=&a=&k=&f=&t=

See you

author: Juan Mestas J. (aka gotchas) | posted @ Monday, October 05, 2009 3:14 PM | Feedback (0)

Extending Type class to get a type that implements an interface <IsImplementationOf>


Is really simple know if any type implements an interface in the traditional way we can use the “is” keyword to know if the class instance implements the interface, by instance

Interface

Code Snippet
  1. public interface IMarkable
  2.     {
  3.         void Mark();
  4.     }

 

Class that implements the interface

Code Snippet
  1. public class Marker : IMarkable
  2.     {
  3.         #region IMarkable Members
  4.  
  5.         public void Mark()
  6.         {
  7.             Console.Write("Do Mark!!");
  8.         }
  9.  
  10.         #endregion
  11.     }

 

Interface validation

Code Snippet
  1. Marker marker = new Marker();
  2.             if (marker is IMarkable)
  3.             {
  4.                 //Implements IMarkable
  5.             }

 

But if are we working with an instance of Type class, not exists a built-in method to determinate if the type implements the interface

A simple way to get this is extend the Type class using the Extensions Method feature, we can write something like this

Code Snippet
  1. public static class TypeExtension
  2.     {
  3.         public static Boolean IsImplemetationOf(this Type type, Type interfaceType)
  4.         {
  5.             Boolean returnBool = false;
  6.             Type[] interfaces = type.GetInterfaces();
  7.             for (int i = 0; i < interfaces.Length; i++)
  8.             {
  9.                 if (interfaces[i] == interfaceType)
  10.                 {
  11.                     returnBool = true;
  12.                     break;
  13.                 }
  14.             }
  15.             return returnBool;
  16.         }
  17.     }

In this manner we can make this validation when works with an instance of Type class

Code Snippet
  1. Assembly currentAssembly = Assembly.GetExecutingAssembly();
  2.             Type[] assemblyTypes = currentAssembly.GetTypes();
  3.             for (int i = 0; i < assemblyTypes.Length; i++)
  4.             {
  5.                 Type type = assemblyTypes[i];
  6.                 if (type.IsClass && type.IsImplemetationOf(typeof(IMarkable)))
  7.                 {
  8.                     //Implements IMarkable
  9.                 }
  10.             }

 

See you

author: Juan Mestas J. (aka gotchas) | posted @ Wednesday, September 30, 2009 12:21 AM | Feedback (2)

How to Load Application Templates dynamically from Resources files


Well on my last post, i talk about changes on controls in #Silverlight3, while i tried to use a demo about Navigation and Styles, Corrina and her team had developed 7 additional application templates, for the community to consume and they’ve put them up on the Expression Community Gallery for download:

Aurora

Frosted Cinnamon Toast

Lime Shocker

Pinky

Retro

Sky Line

Subdued

 

All templates are terrific and very easy to use only change the reference to the resource in the styles.xaml code file. But if we want work with all templates and load them, based on some policy or the user preference, in the same way that custom styles on ASP.Net? The easy way is get the template from the application host (ASP.Net), and pass it to Silverlight using the init parameters

Copy the styles.xaml files that you want use to the Assets folder in your project, rename each one of the files with a descriptive name, after define the logic for set the current theme in the Application Host (ASP.Net)

 

   1:  using System;
   2:  using System.Collections.Generic;
   3:  using System.Linq;
   4:  using System.Web;
   5:  using System.Web.UI;
   6:  using System.Web.UI.WebControls;
   7:   
   8:  namespace UIOne.Web
   9:  {
  10:    public partial class _Default : System.Web.UI.Page
  11:    {
  12:      protected void Page_Load(object sender, EventArgs e)
  13:      {
  14:          //Some sort of policy or user preference for get the current Theme
  15:          string applicationTheme = "Frosted.xaml";
  16:          this.Silverlight1.InitParameters = String.Format("applicationTheme={0}", applicationTheme);
  17:      }
  18:    }
  19:  }

 

Get the parameter in Silverlight code and rewrite the constructor of the Main class to receive one parameter

 
   1:    private void Application_Startup(object sender, StartupEventArgs e)
   2:          {
   3:              string applicationTheme = e.InitParams["applicationTheme"];
   4:              this.RootVisual = new MainPage(applicationTheme);
   5:          }

 

In the constructor of the Main class, get the resource file using the GetResourceStream method, create a StreamReader within the result and load the read content using the Load method from the XamlReader class

 

   1:   public MainPage(string applicationTheme)
   2:          {
   3:              string resurceUri = String.Concat("<<assembly>>;component/Assets/", applicationTheme);
   4:              StreamResourceInfo resourceInfo =
   5:                  App.GetResourceStream(new Uri(resurceUri, UriKind.Relative));
   6:              StreamReader resourceReader = new StreamReader(resourceInfo.Stream);
   7:              string xaml = resourceReader.ReadToEnd();
   8:              ResourceDictionary resourceTheme =
   9:                  XamlReader.Load(xaml) as ResourceDictionary;
  10:              App.Current.Resources.MergedDictionaries.Add(resourceTheme);
  11:   
  12:              InitializeComponent();
  13:          }

 

Now test the project, modifying the value for applicationTheme variable

See you

author: Juan Mestas J. (aka gotchas) | posted @ Thursday, July 30, 2009 3:17 AM | Feedback (2)

The tag 'XxX' does not exist in XML namespace 'clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls and other movements on Silverlight 3


I just downloaded the application styles from here and try to use, but thrown the unexpected error: “The tag 'Expander' does not exist in XML namespace 'clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls”

According to Ensuring That Your Silverlight 2 Applications Work with Silverlight 3, in the entry 3.1:

3.1 DockPanel, WrapPanel, Expander, HeaderedContentControl, Viewbox, DataForm moved to the Silverlight Toolkit

The following controls and types have been removed from the Silverlight SDK:

  • DockPanel

  • WrapPanel

  • Expander

  • HeaderedContentControl

  • Viewbox

  • DataForm

  • ExpandDirection

  • ExpanderAutomationPeer

  • LengthConverter

  • StretchDirection

These controls are now in the Silverlight Toolkit, which is available at http://www.codeplex.com/Silverlight.

Then i have change from this…

   1:  <controls:ChildWindow  x:Class="UIOne.ErrorWindow"
   2:      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
   3:      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
   4:      xmlns:controls="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls"    
   5:      DataContext="{Binding RelativeSource={RelativeSource Self}}"
   6:      Title="Error" >
   7:      
   8:      <Grid x:Name="LayoutRoot" Width="400" Margin="2">
   9:   
  10:          <Grid.RowDefinitions>
  11:              <RowDefinition Height="Auto" />
  12:              <RowDefinition Height="Auto"/>
  13:              <RowDefinition />
  14:              <RowDefinition Height="Auto"/>
  15:          </Grid.RowDefinitions>
  16:          
  17:          <TextBlock Grid.Row="0" Text="Sorry, an unknown error occurred in this application." />
  18:          
  19:          <TextBlock Grid.Row="1" Text="Please contact your administrator for more information." />
  20:                  
  21:          <controls:Expander Grid.Row="2" Header="Details" Margin="0, 10, 0, 0" >
  22:              
  23:              <TextBox Text="{Binding ErrorDetails}"                      
  24:                       Height="100"
  25:                       TextWrapping="Wrap" IsReadOnly="True" 
  26:                       VerticalScrollBarVisibility="Auto" />
  27:              
  28:          </controls:Expander>
  29:          
  30:          <Button x:Name="OKButton" Content="OK" Click="OKButton_Click" Width="75" Height="23" HorizontalAlignment="Right"  Margin="0,12,0,0" Grid.Row="3" TabIndex="0" />
  31:          
  32:      </Grid>
  33:      
  34:  </controls:ChildWindow>

….to this

   1:  <controls:ChildWindow 
   2:      x:Class="UIOne.ErrorWindow"
   3:      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
   4:      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
   5:      xmlns:controls="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls"    
   6:      xmlns:controlsToolkit="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Toolkit"                      
   7:      DataContext="{Binding RelativeSource={RelativeSource Self}}"
   8:      Title="Error" >
   9:      
  10:      <Grid x:Name="LayoutRoot" Width="400" Margin="2">
  11:   
  12:          <Grid.RowDefinitions>
  13:              <RowDefinition Height="Auto" />
  14:              <RowDefinition Height="Auto"/>
  15:              <RowDefinition />
  16:              <RowDefinition Height="Auto"/>
  17:          </Grid.RowDefinitions>
  18:          
  19:          <TextBlock Grid.Row="0" Text="Sorry, an unknown error occurred in this application." />
  20:          
  21:          <TextBlock Grid.Row="1" Text="Please contact your administrator for more information." />
  22:                  
  23:          <controlsToolkit:Expander Grid.Row="2" Header="Details" Margin="0, 10, 0, 0" >
  24:              
  25:              <TextBox Text="{Binding ErrorDetails}"                      
  26:                       Height="100"
  27:                       TextWrapping="Wrap" IsReadOnly="True" 
  28:                       VerticalScrollBarVisibility="Auto" />
  29:              
  30:          </controlsToolkit:Expander>
  31:          
  32:          <Button x:Name="OKButton" Content="OK" Click="OKButton_Click" Width="75" Height="23" HorizontalAlignment="Right"  Margin="0,12,0,0" Grid.Row="3" TabIndex="0" />
  33:          
  34:      </Grid>
  35:      
  36:  </controls:ChildWindow>

 

Now this works fine :)

See you

author: Juan Mestas J. (aka gotchas) | posted @ Thursday, July 30, 2009 1:14 AM | Feedback (0)

Dynamics Simulation and Geometric Modeling Using D* Symbolic Differentiation


Symbolic Lagrangian formulations of the equations of motion of tree structured constrained mechanical systems have the potential to be both more efficient and more numerically robust than formulations which use nonlinear kinematic constraint equations.

D* is a program for efficiently computing symbolic derivatives, derive a simple recursive factorization of the Lagrangian equations of motion which, along with our extended implementation of the D* symbolic differentiation algorithm, yields empirically measured O(n) inverse dynamics and O(n3) forward dynamics.

More: http://research.microsoft.com/en-us/downloads/4714703d-782c-4e37-830d-0e3b7662f743/default.aspx

See you

author: Juan Mestas J. (aka gotchas) | posted @ Sunday, July 26, 2009 8:44 AM | Feedback (0)

Kerberos Interoperability Testing Workshop hosted by Microsoft


A few weeks ago Microsoft’s Kerberos team participated in the Kerberos Interop Workshop organized by the MIT Kerberos Consortium, being hosted here at the Microsoft campus here in Redmond. I had a chance to spend some time with the Microsoft folks (Michiko Short, Jeremy Viegas, Larry Zhu and Yi Zeng from the Microsoft’s Kerberos team) who participated in the event to discuss what happened. We thought it would be interesting to share a quick summary.

This sort of interoperability workshop is an effort to gather developers together in a single location, to actually plug them into a network environment together and help each other work through the interoperability challenges associated with their current development efforts. In attendance were representatives from Cornell University, Centrify, Microsoft, MIT, Safe Mashups, and Sun Microsystems.

More: http://blogs.msdn.com/interoperability/archive/2009/05/27/kerberos-interoperability-testing-workshop-hosted-by-microsoft.aspx

 

See you

author: Juan Mestas J. (aka gotchas) | posted @ Saturday, July 25, 2009 7:30 PM | Feedback (0)

Microsoft announced the Live Services Plug-in for Moodle


Microsoft announced the Live Services Plug-in for Moodle, a free download released under the General Public License v2 that integrates Microsoft's Live@edu services such as email, calendar, instant messaging and search directly into the Moodle experience.

The complete article

http://port25.technet.com/archive/2009/07/21/the-live-services-plug-in-for-moodle-debuts.aspx

 

See you

author: Juan Mestas J. (aka gotchas) | posted @ Saturday, July 25, 2009 7:25 PM | Feedback (0)