2015年4月11日土曜日

Dispatcher を利用した非同期処理


WPF でメインスレッドとは異なるスレッドで非同期処理を行う際には、Dispatcher を使います。
タイミングの問題で UI エレメントに正しくアクセス出来ない時に使っています。本来は並列処理など違う用途で威力を発揮するんだと思います。


C#
private void Button_Click(object sender, RoutedEventArgs e)
{
    Debug.WriteLine("メインスレッド1");
    
    this.Dispatcher.BeginInvoke(
     new Action(() =>
     {
         // 時間のかかる処理を実行
         Debug.WriteLine("別スレッド");
     })
    );

    Debug.WriteLine("メインスレッド2");
}

VB.NET
Private Sub Button_Click(sender As Object, e As RoutedEventArgs)
    Debug.WriteLine("メインスレッド1")
    Me.Dispatcher.BeginInvoke(
    Sub()
        ' Dispatcherを利用してUIスレッドに処理を配送
        ' 時間のかかる処理を実行
        Debug.WriteLine("別スレッド")
    End Sub)
    Debug.WriteLine("メインスレッド2")
End Sub

2015年4月4日土曜日

Eclipse と Tomcat で Java サーブレットアプリケーションを作成

Pleiades All in One の Eclipse を利用して簡易に Java サーブレットを作成する方法を記します。

----------------------------------------------------------------

Pleiades All in One のウェブサイトから Eclipse をダウンロードします。

Pleiades All in One ダウンロード
http://mergedoc.sourceforge.jp/

Eclipse を起動し、「パッケージ・エクスプローラー」上で右クリックします。表示されるコンテキストメニューから「新規」→「プロジェクト」を選択します。




ダイアログが開いたら、「プロジェクト名」に任意の名前(ここでは MyApp1)を入力します。




そのまま「次へ」を選択します。

続いて「完了」を選択します。



プロジェクトが生成されました。



続いてはプロジェクトにサーブレットを作成します。サーブレットのテンプレートはプロジェクトを右クリックして表示されるコンテキストメニューから、「新規」→「サーブレット」を選択します。


パッケージ名に「test」、クラス名に「TestServlet」とそれぞれ名前をつけます。


URL マッピングに 「/TestServlet」と表示されていることを確認します。「次へ」を選択します。



「完了」を選択します。



src フォルダ配下に test\TestServlet.java が生成されました。




doGet に下記の内容を記述し、レスポンスとしてブラウザに HTML を出力します。
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  // TODO Auto-generated method stub

  response.setContentType("text/html; charset=Windows-31J");
  PrintWriter out = response.getWriter();

     out.println("<html>");
     out.println("  <body>");
     out.println("  これは test です。");
     out.println("  </body>");
     out.println("</html>");
 }

続いて Tomcat をセットアップし、上記で作成した Java プロジェクトを実行できるようにします。
「サーバー」ビューから下記リンクをクリックします。


 ここでは Tomcat6 を選択します。


MyApp1 を追加します。


追加し、「完了」を選択します。





「http://localhost:8080/MyApp1/TestServlet」にアクセスして実行結果を確認します。

KB3033889 : エクスプローラやタスクバーが固まる不具合修正がリリース

Windows8 を使っていて、先日 WindowsUpdate を行ったらエクスプローラが固まる固まる。
現在は下記 URL より修正パッチを取得することができます。

Windows8
https://www.microsoft.com/ja-jp/download/details.aspx?id=46213
Windows8.1
https://www.microsoft.com/ja-jp/download/details.aspx?id=46199

2015年3月28日土曜日

INotifyPropertyChanged サンプル2

以前にもこちらの記事で INotifyPropertyChanged インターフェイスの例を紹介しましたが、改めて簡易なサンプルで実装内容を紹介します。

INotifyPropertyChanged インターフェイスとは:
バインドデータがプログラム側で変更された際に、ユーザーインターフェイス(UI)にその変更を通知する仕組みを提供します。例えば Label コントロールに DataItem クラスの Name プロパティをバインドする場合、下記のようにクラスの定義、初期化とユーザーコントロールの定義を行います。

データ用クラス
public class DataItem
{
    public string Name { get; set; }
}

データの初期化
public MainWindow()
{
    InitializeComponent();

    // データの生成
    DataItem item = new DataItem() { Name = "Josh" };
    // データを DataContext に割り当て
    this.DataContext = item;
}

ユーザーコントロール
<Label Name="label1" Content="{Binding Path=Name}"
    Margin="194,47,130,0"
    VerticalAlignment="Top" Height="41"
    Background="LightBlue"/>

上記で初動時には問題なく Label コントロールに 「Josh」 が表示されます。

ただし、次のように任意のイベントで動的にバインドデータである DataItem インスタンスの Name プロパティが書き換えられた場合、コンソールには「新しい名前」が出力されますが、UI の Label コントロールはバインドされているプロパティの変更が自動的に通知されないため「Josh」がそのまま残っています。

private void Button_Click(object sender, RoutedEventArgs e)
{
    DataItem item = this.DataContext as DataItem;
    item.Name = "新しい名前";

    Debug.WriteLine(item.Name);
}

INotifyPropertyChanged インターフェイスがなければ、バインドプロパティが変更されたタイミングで改めてユーザーコントロールに対しても明示的に新しい値を持つプロパティを割り当てる必要があり、ロジックと UI がより密結合な状態となってしまいます。ロジックと UI をより疎結合な状態にし、且つ値変更を自動的に通知する仕組みとして INotifyPropertyChanged インターフェイスを利用します。INotifyPropertyChanged インターフェイスはデータクラスに実装していきます。PropertyChangedEventHandler を定義し、OnPropertyChanged イベントをハンドルします。

/*
public class DataItem
{
    public string Name { get; set; }
}
*/
public class DataItem : INotifyPropertyChanged
{
    private string name;
    public string Name
    {
        get
        {
            return name;
        }
        set
        {
            name = value;
            OnPropertyChanged("Name");
        }
    }

    #region INotifyPropertyChanged

    public event PropertyChangedEventHandler PropertyChanged;

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

    #endregion
}

参考情報:
INotifyPropertyChanged インターフェイス

2014年12月20日土曜日

WPF Label の改行表示


方法1

LineBreak による改行
<label height="58" margin="10,10,0,0" name="label1" verticalalignment="Top" width="117">
    <textblock>Lorem<linebreak>ipsum</linebreak></textblock>
</label>


方法2

特殊文字を使った Content 内での改行
<label content="Lorem &amp;#10;ipsum" height="44" horizontalalignment="Left" margin="76,15,0,0" name="label2" verticalalignment="Top">
</label>

2014年11月15日土曜日

WPF Template を編集して Button コントロールの見た目をカスタマイズ

WPF では Template プロパティを書き換えることで、デフォルトの見た目を大きくカスタマイズすることができるようになっています。
ここでは Template プロパティを使って Button コントロールに画像を埋め込んでみます。なお、Visual Studio のバージョンは 2013 です。

1.Button コントロールを右クリックし、「テンプレートの編集」→「コピーして編集」を選択します。

2.「Style リソースの作成」ダイアログが表示されるので、「OK」をクリックします。


3.ButtonStyle1 というキーを持つ、Button をターゲットとするスタイルが生成されますので、<Setter Property="Template"> という箇所を探し出します。<Setter Property="Template"> には外観や振る舞いが記述されています。<ControlTemplate TargetType="{x:Type Button}"> 内に外観が定義されていて、contentPresenter というキーを持つ ContentPresenter 内にボタンのテキスト部分が定義されていますので、この ContentPresenter の横に画像を配置していきます。

編集前:
<Setter Property="Template">
    <Setter.Value>
        <ControlTemplate TargetType="{x:Type Button}">
            <Border x:Name="border" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" SnapsToDevicePixels="True">
                <ContentPresenter x:Name="contentPresenter" ContentTemplate="{TemplateBinding ContentTemplate}" Content="{TemplateBinding Content}" ContentStringFormat="{TemplateBinding ContentStringFormat}" Focusable="False" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" Margin="{TemplateBinding Padding}" RecognizesAccessKey="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
            </Border>
        ...

編集後:
<Setter Property="Template">
    <Setter.Value>
        <ControlTemplate TargetType="{x:Type Button}">
            <Border x:Name="border" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" SnapsToDevicePixels="True">
                <StackPanel Orientation="Horizontal">
                    <Image Source="BlueRect.PNG" Width="13px"/>
                    <ContentPresenter x:Name="contentPresenter" ContentTemplate="{TemplateBinding ContentTemplate}" Content="{TemplateBinding Content}" ContentStringFormat="{TemplateBinding ContentStringFormat}" Focusable="False" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" Margin="{TemplateBinding Padding}" RecognizesAccessKey="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
                </StackPanel>
            </Border>
        ...


実行結果:


今回は単純にボタン内の横に四角い画像を埋め込んだだけでしたが、Template プロパティを利用して様々なユーザーコントロールの見た目を自由にカスタマイズでき、Windows Forms では実現することのできないような柔軟なカスタマイズを行うことができます。