Silverlight 2 Beta 2 all you need to start developing is here.
Posted in silverlight | Tags: Silverlight 2
Silverlight 2 Beta 2 all you need to start developing is here.
Posted in silverlight | Tags: Silverlight 2
Today I have received strange error when tried to add new Service Reference.
Here is resolution:
Posted in Uncategorized
Posted in WPF | Tags: Windows Presentation Foundation, WPF
This article is extending the latest one (DI with Unity and Asp.Net) by injecting properties to an Asp.Net page so than we do not have to use Unity container and resolve type we are using.
First try:
I have started by adding an property to page (MenuBL).
namespace UnityTest.WebApp
{
public partial class _Default : System.Web.UI.Page
{
public UnityTest.Interfaces.IMenuBL MenuBL { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
var mnuItems = MenuBL.GetUserMenuBL(System.Security.Principal.WindowsIdentity.GetCurrent().Name);
lvMenu.DataSource = mnuItems;
lvMenu.DataBind();
}
}
}
}
And adding to configuration file.
<unity>
<containers>
<container>
<types>
<type type="System.Web.UI.Page" mapTo="UnityTest.WebApp._Default" name="FirstPage">
<typeConfig extensionType="Microsoft.Practices.Unity.Configuration.TypeInjectionElement,Microsoft.Practices.Unity.Configuration">
<property name="MenuBL" propertyType="UnityTest.BLayer.MenuBL,UnityTest.BLayer">
</property>
</typeConfig>
</type>
<type type="UnityTest.Interfaces.IMenuBL,UnityTest.Interfaces" mapTo="UnityTest.BLayer.MenuBL,UnityTest.BLayer">
<typeConfig extensionType="Microsoft.Practices.Unity.Configuration.TypeInjectionElement,Microsoft.Practices.Unity.Configuration">
<property name="DALayer" propertyType="UnityTest.DALayer.MenuDB,UnityTest.DALayer"/>
</typeConfig>
</type>
<type type="UnityTest.Interfaces.IMenuDAL,UnityTest.Interfaces"
mapTo="UnityTest.DALayer.MenuDB,UnityTest.DALayer">
<typeConfig extensionType="Microsoft.Practices.Unity.Configuration.TypeInjectionElement,
Microsoft.Practices.Unity.Configuration">
<constructor>
<param name="connString" parameterType="System.String">
<value value="LFConnectionString"/>
</param>
</constructor>
</typeConfig>
</type>
</types>
</container>
</containers>
</unity>
After firing project I have received System.TypeLoadException for System.Web.UI.Page (unable to find type), hm ok…
What if I manually register type directly in the page (just for test).
Global.Container.RegisterType<System.Web.UI.Page, UnityTest.WebApp._Default>("FirstPage");
Page p= Global.Container.Resolve<System.Web.UI.Page>("FirstPage");
Setting breakpoint to the Page p… and it works… ok when configuring, type was not recognized and it can register an Page.
Second try:
Adding full assembly qualified name to the config. file
<type type="System.Web.UI.Page, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" mapTo="UnityTest.WebApp._Default, UnityTest.WebApp, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" name="FirstPage">
<typeConfig extensionType="Microsoft.Practices.Unity.Configuration.TypeInjectionElement,Microsoft.Practices.Unity.Configuration">
<property name="MenuBL" propertyType="UnityTest.BLayer.MenuBL,UnityTest.BLayer">
</property>
</typeConfig>
</type>
Now run and configuring goes well but property is not injected. Ok that was expected, Asp.Net is building the aspx and code behind file and pushing to the browser. I need to tell the container to look at System.Web.UI.Page to figure out what to inject.
Unity supports to inject an already create object using BuildUp<T>.
This can be done somewhere in the PageInit or PageLoad….
Third try:
namespace UnityTest.WebApp
{
public partial class _Default : System.Web.UI.Page
{
public UnityTest.Interfaces.IMenuBL MenuBL { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
if (MenuBL == null)
Global.Container.BuildUp(this, "FirstPage");
var mnuItems = MenuBL.GetUserMenuBL(System.Security.Principal.WindowsIdentity.GetCurrent().Name);
lvMenu.DataSource = mnuItems;
lvMenu.DataBind();
}
}
}
}
AND IT WORKS……………
Same approach can be applied registering Windows Forms and WPF(Windows, Pages, UC).
Updated source code is here
Here is a very cool WPF application called WorldWide Telescope created by Microsoft Research. It reminds me (zooming and image manipulation) to something I have seen before,… Deep Zoom
Posted in Uncategorized | Tags: Deep Zoom, Microsoft Research, WPF
In my previous post I was using Extension Method to “reuse” code when validating string arguments and throwing custom exception if string was null or empty.
Here is that example:
namespace UnityTest.Core
{
public static class ArgumentValidation
{
public static void IsEmptyOrNull(this string value, string parameterName)
{
if (String.IsNullOrEmpty(value))
throw new CoreException(String.Format("{0} is null or empty",parameterName));
}
}
}
To use it in you class you have to set
using UnityTest.Core;
public List<UnityTest.Models.Menu> GetUserMenuBL(string userName)
{
//will check for null or string.empty and
// throw custom exception if that is true.
userName.IsEmptyOrNull("userName");
try
{
return DALayer.GetUserMenuDB(userName);
}
catch (CoreException)
{ throw; }
catch (Exception)
{ throw; }
}
More information and advanced example can be found here
Posted in C# | Tags: Defensive programming, Extension Method
For two months ago pattern and practice team has released Unity 1.0 (Unity Application Block) which is, as they write, a lightweight dependency injection injection container. More information and download http://www.codeplex.com/unity.
More information about dependency injection can be found in this article http://martinfowler.com/articles/injection.html.
I got some free time to “play” with it and to compare with Spring.Net because I have been using Spring.Net before. Mostly I was curious how p&p team have implemented DI and what is the difference with in this case Spring.Net.
Examples that are following with Unity did not have an example how to use it with configuration file. Some examples and explanations can be found here http://www.pnpguidance.net/.
Because I was working on Web project I wanted to test Unity with Asp.Net 2.0 (3.5) and to implement dependency injection.
Here comes an simple example how to do it (with configuration file
). I an going to create an N-Tier application, not one project with bunch of code files, (separation…) which will retrieve menu from the database for specific user and show it on the page.
Data access is done with help of the Enterprise library 3.1.
Source code
Check updated article for adding DI to the page:V1.1
After creating basic code structure for the project here is the picture.
UnityTest.Interfaces contains interfaces for class implementations of the BLLayer and DALayer. UnityTest.Core contains helper classes like Extension methods more on that later, UnityTest.BLayer is implementation of the business logic and DALayer is database access layer.
After that I am adding Microsoft.Practices.ObjectBuilder2.dll, Microsoft.Practices.Unity.dll and Microsoft.Practices.Unity.Configuration.dll to the UnityTest.WebApp. These files can be found in the bin directory of the Unity 1.0.
Now we have to define interfaces for Data Access Layer and Business Logic Layer.
Here is and example of the Menu model and IMenuDAL.cs with just one method :).
Menu.cs
namespace UnityTest.Models
{
public class Menu
{
public decimal Id { get; set; }
public string MenuText { get; set; }
public string Description { get; set; }
public decimal ParentId { get; set; }
public string Url { get; set; }
}
}
IMenuDAL.cs
namespace UnityTest.Interfaces
{
public interface IMenuDAL
{
//string ConnectionString { get; set; }
/// <summary>
/// Gets the user menu from the database.
/// </summary>
/// <param name="userName">Name of the user.</param>
/// <returns></returns>
System.Collections.Generic.List<UnityTest.Models.Menu> GetUserMenuDB(string userName);
}
}
BLayer project
Code for MenuBL.cs
namespace UnityTest.BLayer
{
public class MenuBL:UnityTest.Interfaces.IMenuBL
{
#region Properties
public UnityTest.Interfaces.IMenuDAL DALayer { get;set; }
#endregion
#region IMenuBL Members
/// <summary>
/// Gets the user menu from data access layer.
/// </summary>
/// <param name="userName">Name of the user.</param>
/// <returns></returns>
public List<UnityTest.Models.Menu> GetUserMenuBL(string userName)
{
userName.IsEmptyOrNull("userName");
try
{
return DALayer.GetUserMenuDB(userName);
}
catch (CoreException)
{ throw; }
catch (Exception)
{ throw; }
}
#endregion
}
}
Code for MenuDB.cs
namespace UnityTest.DALayer
{
public class MenuDB:UnityTest.Interfaces.IMenuDAL
{
#region Properties
Database _db = null;
public Database DB
{
get
{
if (_db == null)
_db = DatabaseFactory.CreateDatabase(this.ConnectionString);
return _db;
}
}
public string ConnectionString { get; set; }
#endregion
public MenuDB(string connString)
{
if (connString != String.Empty)
{
this.ConnectionString = connString;
}
else
//here using resource strings...
throw new CoreException("DALayer.Resources.DBException.ConnectionStringEmpty");
}
#region IMenuDAL Members
/// <summary>
/// Gets the user menu from the database.
/// </summary>
/// <param name="userName">Name of the user.</param>
/// <returns></returns>
public List<UnityTest.Models.Menu> GetUserMenuDB(string userName)
{
//here using Extension method
userName.IsEmptyOrNull("userName");
try
{
List<UnityTest.Models.Menu> menuCollection = new List<UnityTest.Models.Menu>();
//Store Procedure name should be on one place ex. in resource
//string for easier change avoid harcoding!!
//Menu.GetMenusForUser
System.Data.Common.DbCommand cmd = DB.GetStoredProcCommand("Menu.GetMenusForUser", new object[] { userName });
DB.AddParameter(cmd, "@RETURN_VALUE", DbType.Int32, ParameterDirection.ReturnValue, "", DataRowVersion.Current, null);
using (System.Data.IDataReader dr = DB.ExecuteReader(cmd))
{
while (dr.Read())
{
UnityTest.Models.Menu menu = new UnityTest.Models.Menu
{
Id = dr.GetDecimal(0),
MenuText = dr.IsDBNull(1) ? String.Empty : dr.GetString(1),
Description = dr.IsDBNull(2) ? String.Empty : dr.GetString(2),
ParentId = dr.IsDBNull(3) ? -1 : dr.GetDecimal(3),
Url = dr.IsDBNull(4) ? String.Empty : dr.GetString(4)
};
menuCollection.Add(menu);
}
}
if (menuCollection.Count == 0)
{
int returnValue = (int)DB.GetParameterValue(cmd, "RETURN_VALUE");
if (returnValue == -10001)
throw new CoreException("Resources.Exceptions.UserResponsibleNotExists");
}
return menuCollection;
}
catch (CoreException)
{ throw; }
catch(Exception)
{ throw; }
}
#endregion
}
}
Observe yellow mark. This property will we set with property injection, and with constructor injection will we set value of the connString in the MenuDB constructor.
Now to be able to inject dependent object in our Web application first we need to define (write) in formation in the Web.Config.
<configSections>
<sectionGroup name="system.web.extensions" type="System.Web.Configuration.SystemWebExtensionsSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
<sectionGroup name="scripting" type="System.Web.Configuration.ScriptingSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
<section name="scriptResourceHandler" type="System.Web.Configuration.ScriptingScriptResourceHandlerSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
<sectionGroup name="webServices" type="System.Web.Configuration.ScriptingWebServicesSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
<section name="jsonSerialization" type="System.Web.Configuration.ScriptingJsonSerializationSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="Everywhere"/>
<section name="profileService" type="System.Web.Configuration.ScriptingProfileServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
<section name="authenticationService" type="System.Web.Configuration.ScriptingAuthenticationServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
<section name="roleService" type="System.Web.Configuration.ScriptingRoleServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
</sectionGroup>
</sectionGroup>
</sectionGroup>
<section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration"/>
</configSections>
<unity>
<containers>
<container>
<types>
<type type="UnityTest.Interfaces.IMenuBL,UnityTest.Interfaces" mapTo="UnityTest.BLayer.MenuBL,UnityTest.BLayer">
<typeConfig extensionType="Microsoft.Practices.Unity.Configuration.TypeInjectionElement,Microsoft.Practices.Unity.Configuration">
<property name="DALayer" propertyType="UnityTest.DALayer.MenuDB,UnityTest.DALayer"/>
</typeConfig>
</type>
<type type="UnityTest.Interfaces.IMenuDAL,UnityTest.Interfaces"
mapTo="UnityTest.DALayer.MenuDB,UnityTest.DALayer">
<typeConfig extensionType="Microsoft.Practices.Unity.Configuration.TypeInjectionElement,
Microsoft.Practices.Unity.Configuration">
<constructor>
<param name="connString" parameterType="System.String">
<value value="LFConnectionString"/>
</param>
</constructor>
</typeConfig>
</type>
</types>
</container>
</containers>
</unity>
<appSettings/>
Then add Global.asax to Web project and in the Application_start configure our container.
private static Microsoft.Practices.Unity.IUnityContainer _container = null;
public static Microsoft.Practices.Unity.IUnityContainer Container { get { return _container; } }
protected void Application_Start(object sender, EventArgs e)
{
if (_container == null)
_container = new Microsoft.Practices.Unity.UnityContainer();
UnityConfigurationSection section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity");
section.Containers.Default.Configure(_container);
}
protected void Application_End(object sender, EventArgs e)
{
_container.Dispose();
}
Now we need can show our menu on the Page. Page will have an simple ListView and data will be populate in the code behind.
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
UnityTest.Interfaces.IMenuBL ser = Global.Container.Resolve<UnityTest.Interfaces.IMenuBL>();
var mnuItems = ser.GetUserMenuBL(System.Security.Principal.WindowsIdentity.GetCurrent().Name);
lvMenu.DataSource = mnuItems;
lvMenu.DataBind();
}
}
}
Source Code is here.
Posted in C# | Tags: Dependency Injection, Pattern and Practices, Unity 1.0
What is REST?
Here are definitions:
“Representational State Transfer is intended to evoke an image of how a well-designed Web application behaves: a network of web pages (a virtual state-machine), where the user progresses through an application by selecting links (state transitions), resulting in the next page (representing the next state of the application) being transferred to the user and rendered for their use.”
Principles (taken from Wikipedia):
“REST’s proponents argue that the web has enjoyed the scalability and growth that it has as a result of a few key design principles:
Application state and functionality is divided into resources
Every resource is uniquely addressable using a universal syntax for use in hypermedia links
- All resources share a uniform interface for the transfer of state between client and resource, consisting of
A constrained set of well-defined operations
A constrained set of content types, optionally supporting code-on-demand
A protocol that is:
Client/Server
Stateless
Cacheable
Layered”
This is a contrast to a RPC (Remote Procedure Call) model, which is commonly implemented using SOAP or the simpler XML-RPC. There, you expose a range of methods or procedures that can be called and supply them with data to operate on. The focus here is on verbs - the operation that is being performed.
Let’s build a very simple REST-full WCF service. I am going to use Visual Studio 2008 and for testing service Fiddler.
Open Visual Studio and create new WCF service library.

Change the name of the IService1 interface to IHelloRest and class Service1 to HelloRestService.
Add reference System.ServiceModel.Web to this project.
Remove all operations from the IHelloRest interface and add first test operation. Observe here WebGet attribute which allows clients to use your services using HTTP GET attribute. Also observe message format – JSON and UriTemplate.
IHelloRest.cs:
[System.ServiceModel.ServiceContract]
public interface IHelloRest
{
[System.ServiceModel.OperationContract]
[System.ServiceModel.Web.WebGet(UriTemplate = "helloto/{name}", ResponseFormat = System.ServiceModel.Web.WebMessageFormat.Json)]
string Hello(string name);
[System.ServiceModel.OperationContract]
[System.ServiceModel.Web.WebGet(UriTemplate = "isalive/{animal}", ResponseFormat = System.ServiceModel.Web.WebMessageFormat.Json)]
Animal CheckIfAlive(string animal);
[System.ServiceModel.OperationContract]
[System.ServiceModel.Web.WebInvoke(UriTemplate = "animals", ResponseFormat = System.ServiceModel.Web.WebMessageFormat.Xml)]
Animal[] PostAnimal(Animal animal);
[System.ServiceModel.OperationContract]
[System.ServiceModel.Web.WebGet(UriTemplate = "gallery/{pictureId}")]
System.IO.Stream GetPictureThumbnail(string pictureId);
}
[System.Runtime.Serialization.DataContract]
public class Animal
{
[System.Runtime.Serialization.DataMember]
public bool IsAlive { get; set; }
[System.Runtime.Serialization.DataMember]
public string Name { get; set; }
}
And HelloRestService.cs
public class HelloRestService : IHelloRest
{
#region IHelloRest Members
public string Hello(string name)
{
return String.Format("Hello:{0}", name);
}
public Animal CheckIfAlive(string name)
{
return new Animal { IsAlive = true, Name = name };
}
public Animal[] PostAnimal(Animal animal)
{
List<Animal> a = new List<Animal>();
a.Add(new Animal { IsAlive = false, Name = "mamut" });
a.Add(new Animal { IsAlive = true, Name = "dog" });
a.Add(new Animal { IsAlive = true, Name = "ape" });
return a.ToArray();
}
public System.IO.Stream GetPictureThumbnail(string pictureId)
{
System.IO.Stream stream = System.IO.File.Open(@"ow.jpg",System.IO.FileMode.Open);
// set the Content-Type to image/jpeg
System.ServiceModel.Web.WebOperationContext.Current.OutgoingResponse.ContentType = "image/jpeg";
return stream;
}
#endregion
}
Now add new Console Project to the same solution. Add also application configuration file to this project and insert.
Add System.ServiceModel, System.ServiceModel.Web and HelloRest(WCF Library) reference to console project.
Here is my app.config:
<configuration>
<system.serviceModel>
<bindings>
</bindings>
<services>
<service name="HelloRest.HelloRestService" behaviorconfiguration="Default">
<host>
<baseAddresses>
<add baseaddress="http://localhost:8081/json"></add>
</baseAddresses>
</host>
<endpoint address="" binding="webHttpBinding" contract="HelloRest.IHelloRest"></endpoint>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="Default">
<serviceMetadata httpgetenabled="true"></serviceMetadata>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
</configuration>
And here is Program.cs:
class Program
{
static void Main(string[] args)
{
using (WebServiceHost serviceHost = new WebServiceHost(typeof(HelloRest.HelloRestService)))
{
serviceHost.Open();
Console.WriteLine("WCF Service is running...");
Console.ReadLine();
serviceHost.Close();
}
Console.WriteLine("WCF Service has closed");
}
}
Now start console application and your service should be running.
Now we can use fiddler to test our service:
Open fiddler and type in the request builder url with inparameter({name} defined in the interface) to your REST service.
You should get something like this:

Now if you click on result to the left and open Session View you should see this:

Your Rest service worksJ
Now test other operations returning complex types:
If you test http://localhost:8081/json/isalive/dog, you should get animal object in JSON like this:
{”IsAlive”:true,”Name”:”dog”}
Now let’s try to get an image with GetPictureThumbnail
operation. Add an image to the console project and under properties in the project for the image change “Copy to Output Directory” to copy if newer.
You should also change in the code for the operation to the name of your image.
Write http://localhost:8081/json/gallery/1 in the fiddler or the browser and you should get back image. This operation could be used by passing picture id and returning thumbnail when generating gallery.
At the end we will test post with PostAnimal operation. In the Request Builder (Fiddler) write in the Request Header and change Get TO POST:
User-Agent: Fiddler
Host: localhost:8081
Content-Type: application/json; charset=utf-8
Content-Length: 0
See image:
Result should be something like this:
That was simple……
Posted in JSON, REST, WCF | Tags: JSON, Representational State Transfer, REST, Visual Studio 2008, WCF, Windows Communication Foundation
Two weeks ago I wanted to convert a WPF user control which I have created for one year ago with WPF 3.0. The user control was a simple video player showing thumbnails of the videos from the server and has an nice “mirror” reflection.
When control was loaded video part and reflection were animated for better user experience (wow effect). Most of the control was created using Microsoft Expression Blend preview.
The reflection was created using VisualBrush, and not like I saw at that time on many examples on the internet by adding separate MediaElement. With two MediaElements you have to load the same video and it is not recommended.
Main part of the WPF XAML is show here:
<Width:Grid x:Name="videoPart" xmlns:Width="http://schemas.microsoft.com/winfx/2006/xaml/presentation" Width="328" Height="248" Background="#FFFFFFFF" RenderTransformOrigin="1,1">
<Width:Grid.RenderTransform>
<Width:TransformGroup>
<Width:ScaleTransform ScaleX="1" ScaleY="1"/>
<Width:SkewTransform AngleX="0" AngleY="0"/>
<Width:RotateTransform Angle="0"/>
<Width:TranslateTransform X="0" Y="0"/>
</Width:TransformGroup>
</Width:Grid.RenderTransform>
<MediaElement Name="player" Margin="4,4,4,4" LoadedBehavior="Manual"/>
</Width:Grid>
<Rectangle Width="328" Height="248" x:Name="rectangle">
<Rectangle.Fill>
<VisualBrush Visual="{Binding ElementName=videoPart}">
<VisualBrush.Transform>
<TransformGroup>
<ScaleTransform ScaleY="-1"/>
<TranslateTransform Y="248"/>
</TransformGroup>
</VisualBrush.Transform>
</VisualBrush>
</Rectangle.Fill>
<Rectangle.OpacityMask>
<LinearGradientBrush EndPoint="0.506,0.609" StartPoint="0.5,0.161">
<GradientStop Color="#4C000000" Offset="0"/>
<GradientStop Color="#00FFFFFF" Offset="1"/>
</LinearGradientBrush>
</Rectangle.OpacityMask>
<Rectangle.RenderTransform>
<TransformGroup>
<ScaleTransform ScaleX="1" ScaleY="1"/>
<SkewTransform AngleX="0" AngleY="0"/>
<RotateTransform Angle="0"/>
<TranslateTransform X="0" Y="0"/>
</TransformGroup>
</Rectangle.RenderTransform>
</Rectangle>
</StackPanel>
</Grid>
How to recreate this in Silverlight? I have seen community requests that Microsoft include VisualBrush for the Silverlight which at that time was not the case.
To achive this effect (for video) we could use VideoBrush element. VideoBrush paints an area with video content provided by MediaElement.
When MediaElement loads media and that MediaElement is used by a VideoBrush as its SourceName, the video referenced as the MediaElement
Source is downloaded and decoded only one time. You do not suffer significant performance penalties by using a MediaElement and VideoBrush together, even if you choose to have both the MediaElement and VideoBrush display the video.
Source is downloaded and decoded only one time. You do not suffer significant performance penalties by using a MediaElement and VideoBrush together, even if you choose to have both the MediaElement and VideoBrush display the video.
SilverLight XAML:
<Width:Grid x:Name="videoGrid" xmlns:Width="http://schemas.microsoft.com/winfx/2006/xaml/presentation" Width="328" Height="248" RenderTransformOrigin="1,1"> <Width:Grid.RenderTransform> <Width:TransformGroup> <Width:ScaleTransform/> <Width:SkewTransform/> <Width:RotateTransform/> <Width:TranslateTransform Y="15"/> </Width:TransformGroup> </Width:Grid.RenderTransform> <Width:MediaElement x:Name="video" Width="328" Height="248"/> </Width:Grid> <Rectangle Width="328" Height="248" x:Name="rectangle"> <Rectangle.Fill> <VideoBrush SourceName="video"/> </Rectangle.Fill> <Rectangle.OpacityMask> <LinearGradientBrush EndPoint="0.506,0.609" StartPoint="0.5,0.161"> <GradientStop Color="#4C000000" Offset="1"/> <GradientStop Color="#00FFFFFF" Offset="0"/> </LinearGradientBrush> </Rectangle.OpacityMask> <Rectangle.RenderTransform> <TransformGroup> <ScaleTransform ScaleX="1" ScaleY="-1"/> <SkewTransform AngleX="0" AngleY="0"/> <RotateTransform Angle="0"/> <TranslateTransform X="0" Y="263"/> </TransformGroup> </Rectangle.RenderTransform> </Rectangle>
Here is the finally example with same principle and link (for now):
Posted in silverlight | Tags: silverlight, VideoBrush, WPF
My headline was at first Rest with WCF and JSON there I wanted to show how “easy” this can be implemented and used later in “real life” with WCF. But when started to write I thought much about JSON and XML and decided to split article in two, three parts.
I am a big fan of Restful design. The whole World Wide Web is built on the same principle. Simply explained, with REST, every piece of information has its own URL. But more about REST in the next article.
Remembering the old days when we used SOAP to send messages over the wire, with .Net 1.0/1.1 Web Services. Because of the poor performance due to the large messages transferring, with schemas of DataSets (bad design) and bad connection we had to zip messages with GZip and unzip it before showing the end user.
Since then I have seen many application/services sending large xml messages (SOAP) and there was still same design faults (including schemas definition in each response/request).
There was a misperception that with just using XML every problem will be solved. People, read designers, architects and developers thought that xml message format was the “Holy Grail”, and it was really abused.
When technique freaks rediscovered AJAX (Asynchronous Java Script and Xml), yes rediscovered, since we could use it since release of the Internet Explorer 5 back in 1998, they thought, o we can use Web Services with SOAP and bunch of xml messages, and call it directly from the browser using XmlHttpRequest very simply and again all our problems are solved, o great Web 2.0 is here.
Again messages send with soap where too large, in some cases, system was bad designed (again) and it took too long time to retrieve them and now and then you would get timeout with response, the SOP or Same Origin Problem also arise because of the use of the XMLHttpRequest object, which involve the browser restriction that prohibits pulling data from another domain.
The limitation of the client (read browser) was also parsing messages and retrieving information from message, which also took time. Here in one great article by Jens Riboe about performance Web Service Performance (written for 5-6 years). There are some interesting thoughts with measured performance and the result shows that when sending messages in different formats one significant bottleneck can be parsing mechanism when exchanging data.
Now the JSON popularity is together with the AJAX phenomenon, most AJAX implementations focus soley on XML as the delivery mechanism for data.
My thought was that XML is good for an envelope, but not necessarily the best choice for transmitting large amounts of data, as it is too verbose. JSON offers a lightweight format, is easily serialisable/deserialisable and maps nicely to native datatypes. Microsft Ajax is using also JSON to exchange data.
To investigate performance of Json and Xml, I made simple test comparing them. My first thoughts were that JSON may be something like x faster to parse than XML in today’s browsers, JSON parsing ends up with something akin to a typed “business object” rather than an untyped DOM tree, I also thought that serialized Javascript objects will fit better client side scripting (which is primary done in Javascript).
With XML you can use the responseXML property of the XMLHTTPRequest object to get an XML object:
var xml = xhttp.responseXML;
var elements = xml.getElementsByTagName("name");
alert(elements[0].firstChild.textContent);
Apparently, to process the response data, you need to walk the DOM tree. This is a very tedious exercise, and is error prone. Unfortunately, DOM is what we are left with on the browser side.
Alternatively the JSON string can be accessed using the responseText property of the XMLHTTPRequest object.
var customer = eval(xhttp.responseText);
alert(customer.name);
With a simple eval(), you could evaluate the response to a JavaScript object. Once this step is done, to access the data, you just access the properties of the evaluated object. This is the most elegant part of JSON.
The test showed that there was no significant difference. Still I was using Internet Explorer 7 and maybe because I was using MSXML object and JSON is using Javascript there was some overhead there. Again this was an really simple test but again I did not expect this result.
XML is built for giving semantic meaning two text within documents. JSON is built for data structures. Unfortunately, most developers have not understood this, and just used whatever that felt was the most popular. Yes, XML can describe data structures, but when you start really looking at the syntax for describing simple things like empty arrays in XML, it should be obvious to people, that JSON is much more naturally built for data structures. var person = eval(xhr.responseText);
JSON is important because it is better supported in the browser than XML. alert(person.firstName); var xml = xhr.responseXML; var elements = xml.getElementsByTagName(”firstName”);
With JSON there are still some potential security features built into modern browsers that prevent web pages from initiating certain classes of communication with web servers on domains other than the one hosting the page. This “problem” is accurately described in the article Fixing AJAX: XMLHttpRequest Considered Harmful. But also badly escaped XML can also lead to cross-site scripting attacks.
Again it is upp to you to fix security either using xml or json or other.
At the end I will recommend use of the binary format where possible.
Use JSON when representing data structures or when having data oriented applications.
Use xml when sending message like a document than a structure, or if the order of the data matters, or if the data is potentially long-lived
Also check out SXML which is SXML is particularly suitable for Scheme-based XML/HTML authoring, which is a complete representation of arbitrary DTDless XML in standard S-expressions.