Thursday, June 7, 2012

Writing a clone method using DataContractSerializer

Here is code sample which uses DataContractSerializer to Clone any DTO object which is used between WCF Service & Client.

It serializes source object into a XML string and then convert back sane XML string to another object of passed type.

 public static T Clone<T>(T source)     
        {
            string objectstr;
            
            using (MemoryStream memoryStream = new MemoryStream()) 
            { 
                DataContractSerializer serializer = new DataContractSerializer(source.GetType()); 
                serializer.WriteObject(memoryStream, source); 
                objectstr = Encoding.UTF8.GetString(memoryStream.ToArray()); 
            }
 
            using (MemoryStream memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(objectstr))) 
            { 
                XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader(memoryStream, Encoding.UTF8, new XmlDictionaryReaderQuotas(), null); 
                DataContractSerializer serializer = new DataContractSerializer(source.GetType()); 
                return (T) serializer.ReadObject(reader); 
            }
 
        } 

Friday, June 1, 2012

Windows 8 Metro : Playing Sound Files

While playing sound files using XAML in VS 11, you have to follow these steps:
1) VS 11 doesn't support Build Action as "Resource", so you have to add a sound file and set its Build as "Content" and set its "Copy to Output Directory" as "Copy if Newer"





















2) Add a MediaPlayer in your XAML , (it doesn't have sound player).
<MediaPlayer Height="100" x:Name="MediaPlayer" Canvas.Left="10" Canvas.Top="99" Width="100"/>

3) Now Because of some bug in Media Player , you have to set "Source" path in your code as shown below.

MediaPlayer.Source = new Uri(Board.Current.SoundPlayer.BaseUri, "/Sounds/Hit02.wav");



4) Now Call Play method on MediaPlayer to start playing your sound file.

MediaPlayer.Play();