Monday, April 9, 2012

How to use ChannelFactory class in WCF client side code

ChannelFactory class is used in the way that create new channel with server side endpoints.
Msdn reference is here. http://msdn.microsoft.com/en-us/library/ms576132.aspx


The sample code is also here.
 static void Main(string[] args)  
 {  
   ChannelFactory<IEvalService> cf =   
     new ChannelFactory<IEvalService>("NetTcpBinding_IEvalService");  
   IEvalService channel = cf.CreateChannel();  

   Eval eval = new Eval();  
   eval.Submitter = "Shingo";  
   eval.Timesent = DateTime.Now;  
   eval.Comments = "I love WCF";  

   channel.SubmitEval(eval);  
   channel.SubmitEval(eval);  

   List<Eval> evals = channel.GetEvals();  

   Console.WriteLine("Number of evals : {0}", evals.Count);  
   ((IClientChannel)channel).Close();  

   Console.ReadLine();  
 }  

Simply, we can also write like this. EvalServiceClient class was generated when consuming  service reference.
 static void Main(string[] args)  
 {  
   EvalServiceClient channel = new EvalServiceClient("NetTcpBinding_IEvalService");  

   Eval eval = new Eval();  
   eval.Submitter = "Shingo";  
   eval.Timesent = DateTime.Now;  
   eval.Comments = "I love WCF";  

   channel.SubmitEval(eval);  
   channel.SubmitEval(eval);  

   List<Eval> evals = channel.GetEvals();  

   Console.WriteLine("Number of evals : {0}", evals.Count);  
   ((IClientChannel)channel).Close();  

   Console.ReadLine();  
 }  


In the code, I get the results of GetEvals method as List<>. You can set the results of collection type easily. The step is like this.

















You can choose here.


Friday, April 6, 2012

Running WCF with Console Application and introducing useful app.config editor tool

Usually, WCF runs on IIS Web server. But I studied that WCF can also run client application like console application, WPF application or more.

I also learned we can write service model element in app.config from code. (But we don't use usually.)

I'm gonna show you sample code.

 class Program  
 {  
   static void Main(string[] args)  
   {  
     ServiceHost host = new ServiceHost(typeof(EvalService));  
     host.AddServiceEndpoint(typeof(IEvalService),  
       new BasicHttpBinding(),  
       "http://localhost:8080/evals/basic");  
     host.AddServiceEndpoint(typeof(IEvalService),  
       new WSHttpBinding(),  
       "http://localhost:8080/evals/ws");  
     host.AddServiceEndpoint(typeof(IEvalService),  
       new NetTcpBinding(),  
       "net.tcp://localhost:8081/evals");  
     try  
     {  
       host.Open();  
       PrintServiceInfo(host);  
       Console.ReadLine();  
       host.Close();  
     }  
     catch (Exception ex)  
     {  
       Console.WriteLine(ex);  
       host.Abort();  
       Console.ReadLine();  
     }  
   }  
   static void PrintServiceInfo(ServiceHost host)  
   {  
     Console.WriteLine("{0} is up and running with these endpoints:",  
       host.Description.ServiceType);  
     foreach (ServiceEndpoint se in host.Description.Endpoints)  
       Console.WriteLine(se.Address);  
   }  
 }  

The result is like this.



So remarkably, you need run visual studio as Administrator.



  • WCF app.config Editor
You may feel pain to write app.config for WCF. There is excellent configuration tool for you.



You can easily edit app.config from GUI.


Thursday, April 5, 2012

Entry of Windows Communication Service (WCF)

I'm studying WCF. It's so nice and useful framework so that I'm going to log my understanding into the blog.


The simple WCF code is here.
 [DataContract]  
 public class Eval  
 {  
   [DataMember]  
   public string Submitter;  
   [DataMember]  
   public DateTime Timesent;  
   [DataMember]  
   public string Comments;  
 }  
 [ServiceContract]  
 public interface IEvalService  
 {  
   [OperationContract]  
   void SubmitEval(Eval eval);  
   [OperationContract]  
   List<Eval> GetEvals();  
 }  
[ServiceBehavior(InstanceContextMode=InstanceContextMode.Single, 
    ConcurrencyMode=ConcurrencyMode.Multiple)]
 public class EvalService : IEvalService  
 {  
   List<Eval> evals = new List<Eval>();  
   public void SubmitEval(Eval eval)  
   {  
     evals.Add(eval);  
   }  
   public List<Eval> GetEvals()  
   {  
     return evals;  
   }  
 }  

So, I studied new things about ServiceBehavior attribute.
ServiceBehavior has two enum parameters mainly that are InstanceContextMode and ConcurrencyMode.
InstanceContextMode has Single, Percall, and Persession that are about instanciation. Also ConcurrencyMode has Single, Multiple, and Reentrant that are about threading.


In detail, here is msdn documents.
http://msdn.microsoft.com/en-us/library/system.servicemodel.servicebehaviorattribute.aspx
http://msdn.microsoft.com/en-us/library/system.servicemodel.instancecontextmode.aspx
http://msdn.microsoft.com/en-us/library/system.servicemodel.concurrencymode.aspx


I'm going to continue this series depend on my study progress.
Thanks.

Monday, March 19, 2012

My memo app supports multilingualization in new version 1.7














http://windowsphone.com/s?appid=01fada6f-ff7e-451b-b0b0-3bf3a5c0f655

I'm really happy to announce my memo app's new release version 1.7 !
In new version, my memo app supports multilingualization that are English and Japanese.

And second feature is that you can choose character color (black or white). You can customize character color and background color as you want.

So, please check the function in bellow Yourtube video.



Please download my memo app in your Windows Phone ! 
Thanks.

Sunday, March 18, 2012

Cannot bind two types of data source to one UI target

I was also struggling the problem when I made binding between data source and UI ListBox target.
Today, I'd like to introduce the problem that we cannot bind "non-INotifyPropertyChanged property" and "INotifyPropertyChanged property" to same ListBox target.

First, I had written property binding like this. I had used "non-INotifyPropertyChanged property".

  • The xaml code is here.
 <ListBox Height="595" ItemsSource="{Binding}" HorizontalAlignment="Left" Margin="12,6,0,0" Name="listBox1" VerticalAlignment="Top" Width="438">  
   <ListBox.ItemTemplate>  
     <DataTemplate>  
       <StackPanel HorizontalAlignment="Stretch" Orientation="Horizontal">  
         <TextBlock x:Name="Name1" FontSize="35" Text="{Binding Text1}" Foreground="Black"/>  
         <TextBlock x:Name="Name2" FontSize="35" Text="{Binding Text2}" Foreground="Black"/>  
       </StackPanel>  
     </DataTemplate>  
   </ListBox.ItemTemplate>  
 </ListBox>  
  • The code behind is here.
 public partial class MainPage : PhoneApplicationPage  
 {  
   // Constructor  
   public MainPage()  
   {  
     InitializeComponent();  
     GetList();  
   }  

   public void GetList()  
   {  
     List<ItemProperties> items = new List<ItemProperties>();  
     items.Add(new ItemProperties { Text1 = "test01", Text2 = "test02" });  
     items.Add(new ItemProperties { Text1 = "test11", Text2 = "test12" });  
     listBox1.ItemsSource = items;  
   }  
 }  

 public class ItemProperties  
 {  
   private string m_Text1;  
   public string Text1  
   {  
     get { return m_Text1; }  
     set { m_Text1 = value; }  
   }  

   private string m_Text2;  
   public string Text2  
   {  
     get { return m_Text2; }  
     set { m_Text2 = value; }  
   }  
 }  


Second, I wanted to bind Foreground color in ListBox. So, I added "INotifyPropertyChanged property" as Foreground colors.
The code is like this. But I found I couldn't bind "INotifyPropertyChanged property" to Foreground color in this code.

  • The xaml code is here.
 <ListBox Height="595" ItemsSource="{Binding}" HorizontalAlignment="Left" Margin="12,6,0,0" Name="listBox1" VerticalAlignment="Top" Width="438">  
   <ListBox.ItemTemplate>  
     <DataTemplate>  
       <StackPanel HorizontalAlignment="Stretch" Orientation="Horizontal">  
         <TextBlock x:Name="Name1" FontSize="35" Text="{Binding Text1}" Foreground="{Binding Color1}"/>  
         <TextBlock x:Name="Name2" FontSize="35" Text="{Binding Text2}" Foreground="{Binding Color2}"/>  
       </StackPanel>  
     </DataTemplate>  
   </ListBox.ItemTemplate>  
 </ListBox>  
  • The code behind is here.
 public partial class MainPage : PhoneApplicationPage  
 {  
   public ObservableCollection<ItemProperties2> ItemCollection { get; private set; }  
   // Constructor  
   public MainPage()  
   {  
     InitializeComponent();  
     GetList();  
     GetList2();  
   }  

   public void GetList()  
   {  
     List<ItemProperties> items = new List<ItemProperties>();  
     items.Add(new ItemProperties { Text1 = "test01", Text2 = "test02" });  
     items.Add(new ItemProperties { Text1 = "test11", Text2 = "test12" });  
     listBox1.ItemsSource = items;  
   }  

   public void GetList2()  
   {  
     ItemCollection = new ObservableCollection<ItemProperties2>();  
     ItemCollection.Add(new ItemProperties2  
     {  
       Color1 = new SolidColorBrush(Colors.LightGray),  
       Color2 = new SolidColorBrush(Colors.Brown)  
     });  
     ItemCollection.Add(new ItemProperties2  
     {  
       Color1 = new SolidColorBrush(Colors.Cyan),  
       Color2 = new SolidColorBrush(Colors.Red)  
     });  
     DataContext = ItemCollection;  
   }  
 }  

 public class ItemProperties  
 {  
   private string m_Text1;  
   public string Text1  
   {  
     get { return m_Text1; }  
     set { m_Text1 = value; }  
   }  

   private string m_Text2;  
   public string Text2  
   {  
     get { return m_Text2; }  
     set { m_Text2 = value; }  
   }  
 }  

 public class ItemProperties2 : INotifyPropertyChanged  
 {  
   public event PropertyChangedEventHandler PropertyChanged;  
   public ItemProperties2() { }  

   private Brush m_Color1;  
   public Brush Color1  
   {  
     get { return m_Color1; }  
     set  
     {  
       m_Color1 = value;  
       OnPropertyChanged("Color1");  
     }  
   }  

   private Brush m_Color2;  
   public Brush Color2  
   {  
     get { return m_Color2; }  
     set  
     {  
       m_Color2 = value;  
       OnPropertyChanged("Color2");  
     }  
   }  

   protected void OnPropertyChanged(string name)  
   {  
     PropertyChangedEventHandler handler = this.PropertyChanged;  
     if (handler != null)  
       handler(this, new PropertyChangedEventArgs(name));  
   }  
 } 


It seems that "non-INotifyPropertyChanged property" is given priority over "INotifyPropertyChanged property".

I think the problem is a little foolish in now. But If your code is quite large amount, you may not be able to find the problem immediately.
I write previous blog post as the answer for the problem. Please check it also.

Wednesday, March 14, 2012

Suddenly my application crashes without errors when using property binding

I introduced property binding in a previous blog post. Today, I introduce a problem when I write code of property binding.


Property binding is easy to mistake property names. If you mistake property name, you can't bind property correctly but also an application suddenly crashes without any errors.


So, please look at this code attentively. If you write such code, you can pass build action, but your application crashes suddenly without errors.

 public class ItemProperties : INotifyPropertyChanged  
 {  
   public event PropertyChangedEventHandler PropertyChanged;  
   public ItemProperties() { }  

   private string m_Text1;  
   public string Text1  
   {  
     get { return Text1; }  
     set  
     {  
       m_Text1 = value;  
       OnPropertyChanged("Text1");  
     }  
   }  

   protected void OnPropertyChanged(string name)  
   {  
     PropertyChangedEventHandler handler = this.PropertyChanged;  
     if (handler != null)  
       handler(this, new PropertyChangedEventArgs(name));  
   }  
 } 


The wrong code is here. If you write like this, your application suddenly shutdown.
get { return Text1; }  

You need to write like this.
get { return m_Text1; }  


I don't know why debugger can't catch error, but I noticed we need to pay attention when we use property binding.

Friday, March 9, 2012

Property Binding using INotifyPropertyChanged and ObservableCollection

I was struggling against property binding using INotifyPropertyChanged and ObservableCollection.
Today, I introduce how to bind from properties in a class to UI properties by using INotifyPropertyChanged and ObservableCollection. And I'll show you the problem I encountered in next blog post.


  • Sample code of property binding
I introduce a sample code binding from properties in ItemProperties class to TextBlock's properties in ListBox (One Way).

































  • The xaml code is here.
 <ListBox Height="595" ItemsSource="{Binding}" HorizontalAlignment="Left" Margin="12,6,0,0" Name="listBox1" VerticalAlignment="Top" Width="438">  
   <ListBox.ItemTemplate>  
     <DataTemplate>  
       <StackPanel HorizontalAlignment="Stretch" Orientation="Horizontal">  
         <TextBlock x:Name="Name1" FontSize="35" Text="{Binding Text1}" Foreground="{Binding Color1}"/>  
         <TextBlock x:Name="Name2" FontSize="35" Text="{Binding Text2}" Foreground="{Binding Color2}"/>  
       </StackPanel>  
     </DataTemplate>  
   </ListBox.ItemTemplate>  
 </ListBox>  
- Point - 
You need to add ItemsSource="{Binding}" in ListBx to bind properties from code behind. You also should not add like ItemsSource="{Binding Collection}", just write "{Binding}".

When you use DataTemplate in ListBox, you can't write like this in code behind.

Name1.Foreground = new SolidColorBrush(Colors.LightGray);

So you need to bind from properties as a class to UI  properties. Almost all of UI element properties (ex. Foreground, Text, any more) are implemented as dependency property. You can bind from properties as a class to UI  properties using dependency property. You can't bind using usual property.


  • The code behind is here.
 public partial class MainPage : PhoneApplicationPage  
 {  
   public ObservableCollection<ItemProperties> ItemCollection { get; private set; }  
   // Constructor  
   public MainPage()  
   {  
     InitializeComponent();  
     GetList();  
   }  

   public void GetList()  
   {  
     ItemCollection = new ObservableCollection<ItemProperties>();  
     ItemCollection.Add(new ItemProperties  
     {  
       Text1 = "test01",  
       Text2 = "test01",  
       Color1 = new SolidColorBrush(Colors.LightGray),  
       Color2 = new SolidColorBrush(Colors.Brown)  
     });  

     ItemCollection.Add(new ItemProperties  
     {  
       Text1 = "test02",  
       Text2 = "test02",  
       Color1 = new SolidColorBrush(Colors.Cyan),  
       Color2 = new SolidColorBrush(Colors.Red)  
     });  

     ItemCollection.Add(new ItemProperties  
     {  
       Text1 = "test03",  
       Text2 = "test03",  
       Color1 = new SolidColorBrush(Colors.Orange),  
       Color2 = new SolidColorBrush(Colors.Purple)  
     });  

     DataContext = ItemCollection;  
   }  
 }  

 public class ItemProperties : INotifyPropertyChanged  
 {  
   public event PropertyChangedEventHandler PropertyChanged;  
   public ItemProperties() { }  

   private string m_Text1;  
   public string Text1  
   {  
     get { return m_Text1; }  
     set  
     {  
       m_Text1 = value;  
       OnPropertyChanged("Text1");  
     }  
   }  

   private string m_Text2;  
   public string Text2  
   {  
     get { return m_Text2; }  
     set  
     {  
       m_Text2 = value;  
       OnPropertyChanged("Text2");  
     }  
   }  

   private Brush m_Color1;  
   public Brush Color1  
   {  
     get { return m_Color1; }  
     set  
     {  
       m_Color1 = value;  
       OnPropertyChanged("Color1");  
     }  
   }  

   private Brush m_Color2;  
   public Brush Color2  
   {  
     get { return m_Color2; }  
     set  
     {  
       m_Color2 = value;  
       OnPropertyChanged("Color2");  
     }  
   }  

   protected void OnPropertyChanged(string name)  
   {  
     PropertyChangedEventHandler handler = this.PropertyChanged;  
     if (handler != null)  
       handler(this, new PropertyChangedEventArgs(name));  
   }  
 } 

  • Result



Monday, January 16, 2012

My memo app became No.1 in Japan region ranking !



















http://www.windowsphone.com/ja-JP/categories/toolsandproductivity?list=top&wa=wsignin1.0


My memo app became No.1 in "tools + productivity" in Japan region ranking !
I really want to say thanks so much and please download trial version if you don't use it yet.
The memo app is simple and you can note a short memo. (ex, buying list)

  • new feature in ver.1.3
























You can clip memo to tile from ver1.3. This is most fantastic feature in previous updates.
Please see the movie and check the feature.




  • If you can't download memo app,
Please visit this page on Windows Phone, and click "download trial version".

Or you can search memo app, "memos", "note", "notes", like this.

How to solve the problem that you can't display a imge file from IsolatedStorage to web browser

If you have a experience that you try to display a image from IsolatedStorage to web browser as img tag, you notice you can't make it.

For instance, a image file (test.jpg) doesn't display in like html source.
 string htmlSource = @"<?xml version='1.0' encoding='utf-8'?>  
             <html>  
             <head>  
               <meta http-equiv='Content-Type' content='text/html;charset=UTF-8' />  
             </head>  
             <body>  
               <img src='isostore:/Shared/ShellContent/test.jpg'>  
             </body>  
             </html>  
               ";  
 this.webBrowser1.NavigateToString(htmlSource);  


So, if you want to display a image file from IsolatedStorage, you need to generate Base64 String object from the image file and use Javascript to display a image file in html source code.


The sample code is like this.

  • First, generate Base64 String object from Image object.
 public string ImageToBase64(Image image, System.Drawing.Imaging.ImageFormat format)  
 {  
  using (MemoryStream ms = new MemoryStream())  
  {  
   // Convert Image to byte[]  
   image.Save(ms, format);  
   byte[] imageBytes = ms.ToArray();  
   // Convert byte[] to Base64 String  
   string base64String = Convert.ToBase64String(imageBytes);  
   return base64String;  
  }  
 }  

  • Second, display a image using Javascript.
string base64String = ImageToBase64(image, format);  
 string htmlSource = @"<html>  
             <head>  
             </head>  
             <body>  
               <img id='icon_here'>  
               <script>  
                 var data = 'data:image/gif;base64," + base64String + @"';  
                 var icon_elem = document.getElementById('icon_here');  
                 icon_elem.src = data;  
               </script>  
             </body>  
             </html>";  
 this.webBrowser1.NavigateToString(htmlSource);  


You can display a image like this.

























If you have a great idea about the problem, please reply comment.

  • Edit. 2011/01/16
I got a comment of great idea about the problem. You don't need to use Javascript. Simply, add BASE64 string to src attribute.
 string source = @"<html>  
           <head>  
           </head>  
           <body>  
             <img src='data:image/gif;base64," + base64String + @"'>  
           </body>  
          </html>";  
 this.webBrowser1.NavigateToString(source);  

Monday, January 9, 2012

Character Corruption of Japanese Language on Web Browser

You can use build-in web browser in your application on Windows Phone. Using web browser in your app, you can display like rich text page which has images, a few fonts, javascripts or etc.

The sample code is here. 

- xaml
 <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">  
   <phone:WebBrowser HorizontalAlignment="Left" Name="webBrowser1" VerticalAlignment="Top" Height="607" Width="456" />  
 </Grid>  

- code behind
 public MainPage()  
 {  
   InitializeComponent();  
   this.webBrowser1.NavigateToString(@"  
           <?xml version='1.0' encoding='utf-8'?>  
           <html>  
             <head>  
             <meta http-equiv='Content-Type' content='text/html;charset=UTF-8' />  
             </head>  
             <body>  
             テストページです。  
             </body>  
           </html>  
           ");  
 }  


In above sample, Japanese character is used in body in html source. If you run the program, the Japanese character should be character corruption like here.



























To solve the problem, you need to convert ASCII format to display Japanese correctly.
The sample method "ConvertExtendedASCII" is like this.
 private static string ConvertExtendedASCII(string HTML)  
 {  
   string retVal = "";  
   char[] s = HTML.ToCharArray();  
   foreach (char c in s)  
   {  
     if (Convert.ToInt32(c) > 127)  
       retVal += "&#" + Convert.ToInt32(c) + ";";  
     else  
       retVal += c;  
   }  
   return retVal;  
 }  

 public MainPage()  
 {  
   InitializeComponent();  
   string HTML = @"  
           <?xml version='1.0' encoding='utf-8'?>  
           <html>  
             <head>  
             <meta http-equiv='Content-Type' content='text/html;charset=UTF-8' />  
             </head>  
             <body>  
             テストページです。  
             </body>  
           </html>  
           ";  
   this.webBrowser1.NavigateToString(ConvertExtendedASCII(HTML));  
 }  

The result is here.



























The ConvertExtendedASCII method takes so much time if you convert big size html. So, you need to run the method in different thread from UI thread.