ラベル C# の投稿を表示しています。 すべての投稿を表示
ラベル C# の投稿を表示しています。 すべての投稿を表示

木曜日, 10月 08, 2015

PowerBuilder 12.6, C#: データベースへの接続方法

PowerBuilder でデータベースへ接続する方法を示します。

DataObject が機能していることが前提です。


C# でいうと以下のようなコードとなります。



木曜日, 9月 24, 2015

C#: ハッシュテーブルをXML形式で書き出す・読み込む

C#でHashtableのデータをXML形式で読み書きするためのコードです。

忙しい貴方のため(将来の自分ですね)コピペできるようそのまま置いておきます。

  • writeXML(Hashtable directory, string fileName):
    Hashtable のデータをXML形式で保存します。

  • readXML(string fileName):
    XML形式のデータをHashtable 形式で読み込みます。


出来上がったXML形式のファイルです。

金曜日, 7月 03, 2015

配列をムダなく並び替える

ここでは配列をムダなく並び替える方法を提案します。

提案というより、いつもの「ループをまわして違う値が出るまで繰り返す」という方法をやめようという提案です。

何度もまわしていれば終わる作業ではあるはずですが、当然のごとくこのアルゴリズムだと終わるという確証がありません。

カウンタなどつけていれば無限ループという最悪の事態は防げるわけですが、ここでは「乱数は配列の大きさだけ計算すればいいはず」というアルゴリズムの提案です。

大げさなことはないわけなのですが、計算しなければならない乱数ってのは「まだ選択されていない数からのみ」なわけなので、その方法を示します。

まずはコード permute() をご覧ください。

… というわけです。選択されていない中から選ぶので乱数の計算が配列の大きさで済むというわけです。

どうでしょうか。

permute() の応用で、重複しない要素を選択する関数 withoutDuplicate(int n, int max) というのも作れます。

selectWithout(int n, int max, int excluded) は選択すべき要素から一定要素を除いた重複しない要素を選択する関数です。

よく使うアルゴリズムだと思います。

火曜日, 6月 23, 2015

コマンドラインでシカゴの気温を調べる(C# で JSON データを読む)

先日 Java での JSON データの読み方を紹介しました。

ここでは C# で JSON データを読む方法を紹介します。

DataContractJsonSerializer を使った方法です。

DataContractJsonSerializer.ReadObject() を使うと JSON データを読み、オブジェクトとして出力してくれます。

オブジェクトへの変換が「宣言」となっているところがいくらか分かりやすいといえるでしょうか。

まず、読み込みたいデータ構造をクラスとして宣言し、DataContract 属性を付加します。JSON データは DataMember 属性を付加します。ネストされているデータはクラスとして宣言しDataContract 属性を付加します。コードを参照してください。#配列データは配列として宣言します。

出来上がったデータクラスを DataContractJsonSerializer のコンストラクタの引数として渡します。

準備が出来たらHttpWebResponse として読んできたデータを、DataContractJsonSerializer.ReadObject() で読み込みます。

と、この手順を踏むとめでたく JSON データが読み込めます。あとは出力するだけ。

ここの気温の表示はデフォルト設定でなんとK(ケルビン)です。ので 273.15 を引いてやります。

#華氏(℉)か摂氏(℃)か迷ったんでしょうか(もめたんですかね)。

水曜日, 11月 09, 2011

C#: FontDialog unable to set font sizes; Firefox 8

The FontDialog class of C# is not overridable to change its settings. There are flags to remove underline and strike options, but there is no ways to limit font styles nor font sizes.

However, C# is a language that has ready-to-use off-the-shelf components that can replace the font dialog with ones of your own.



The new features in Firefox 8:
- twitter search
- delay loading tabs at start ups (when you set it the opening screen)
- WebGL, HTML5 improvements

月曜日, 11月 07, 2011

C#: WebBrowser.DocumentText does not support the += operator

WebBrowser.DocumentText does not support the += operator.

That is it. It does not. The String class should be formatted separately and assigned to that member variable.

金曜日, 11月 04, 2011

C# DataGridView's SetValue

When a DataTable is set for a DataGridView, the value can not be set
to DataGridViewCellFormattingEventArgs.Value, which is passed by to a
method that is hooked to CellFormatting event.

The way to avoid it, is to access to the cell value directly.
private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
  if(e.ColumnIndex==5)
    {
      // If set, the following will be shown in the cell.  The Cell's value typed as an int will not be set correctly.
      //e.Value = "1";
                        
      // Instead, directly access the Cell object.
      int row = e.RowIndex;
      int col = e.ColumnIndex;
      dataGridView1.Rows[row].Cells[col].Value = 1;
                   
      break;
    } 
}

木曜日, 10月 27, 2011

C#: TimeZoneInfo.GetSystemTimeZones()

TimeZoneInfo.GetSystemTimeZones() returns a reference to a same instance, no matter how many times it is called.

When the time zone list is added to combo boxes, they select the same values.

comboBox1.DataSource = TimeZoneInfo.GetSystemTimeZones();
comboBox2.DataSource = TimeZoneInfo.GetSystemTimeZones();

The Collection class must be copied to some other forms.

System.Collections.ObjectModel.ReadOnlyCollection list 
= TimeZoneInfo.GetSystemTimeZones();
TimeZoneInfo[] tzList = list.ToArray();
comboBox1.Items.AddRange(tzList);
comboBox2.Items.AddRange(tzList);

月曜日, 10月 10, 2011

C# field initializers

C# differs from Java in that the field initializers must be static.

This is perfectly OK in Java.

public class InitTest
{
    int test=0;
    InitTestClass testClass=new InitTestClass(test);
    
    public static void main(String args[])
    {
 InitTest test=new InitTest(); 
    }
}

class InitTestClass
{
    int test=0;
    InitTestClass(int test)
    {
 this.test=test;
    }
}

The following code, however, is not (C#).

namespace InitTest
{
    class Program
    {
        int test = 0;
        // Error
        InitTestClass testClass = new InitTestClass(test);

        static void Main(string[] args)
        {
        }
    }

    class InitTestClass
    {
        int test = 0;
        public InitTestClass(int test)
        {
            this.test = test;
        }
    }
}

木曜日, 9月 29, 2011

The merit of using C#

The code library in C#, comprised of classes that abstract and encapsulate such notions such as instruction set, font data, model number etc. What is good at this library is it runs threads and the 'server' takes commands and send them for number of times until they are passed to the module. Namely, the commands is queue until the event is processed.

A server is also called daemon that runs as a separate process along with the main procedure.

A queue is a FIFO that stack data for processing when the resources are available.

An event is a chunk of data that will be passed to the queue which contains the necessary data for each transaction.

Abstraction is a process that parameterize any variables that can be applied to same sort of procedure.

Encapsulation is a process to separate a set of data from direct manipulation so that any modification to the data will be monitored.

A thread is a process that can be processed pseudo simultaneously. The processor process each thread one at a time so it is pseudo-simultaneous.

With this library, commands are passed to the module in a safer and more secure manner. The server can wait, for sending data and receiving the data at the same time while queuing other data as well.

土曜日, 8月 06, 2011

C#の列挙型

C#の列挙型は特殊です。

列挙型は、Cなどでは定数程度としか使えませんが、C#では名前を取得したり、オブジェクトから列挙型の値を得ることができます。

FontStyle fontStyle = (FontStyle)Enum.Parse(typeof(FontStyle), (string)obj);




「今までと違う」列挙型は、なにも嫌がらせのためにあるわけではなく、これこそはコンピュータ科学の成果であり、技術の進歩...と声を大にして言いたいところですが、あまり主張すると「シカト」などの憂き目にあうのでリーマン稼業の人間には注意が必要です。

改革は、草の根から...ですね。

木曜日, 7月 28, 2011

C#: ComboBox をカスタマイズする

ComboBox リスト項目の描画をカスタマイズし、チェックマークなど描く方法を説明します。

ComboBox のリスト項目は、単なる Object クラスです。つまり、リスト項目クラスを継承などしてデータを追加することはできません。適宜、ComboBox クラスにリストなどデータ構造を用意してデータを保存します。

データの準備ができたら、ComboBox のプロパティで DrawMode を OwnerDrawVariable に変更してやります。ここを変更すると、リスト項目の描画イベントをオーバーライドすることができます。DrawItem イベントに、イベントハンドラを追加し、描画手順を記述します。

具体的にはこのように描画をすべて記述することになります。

private void comboBox1_DrawItem(object sender, DrawItemEventArgs e)
        {
            e.DrawBackground();

            if (e.Index < comboBox1.Items.Count)
            {
                e.Graphics.DrawString((string)comboBox1.Items[e.Index], e.Font, Brushes.Black, e.Bounds);

                if (e.Index < modifiedMessages.Count() && modifiedMessages[e.Index])
                {
                    Bitmap bmp = new Bitmap(Properties.Resources.checkMark);
                    int iconWidth = 16;
                    int iconHeight = 16;
                    e.Graphics.DrawImage(bmp, e.Bounds.Right - iconWidth, e.Bounds.Bottom - iconHeight, iconWidth, iconHeight);
                }
            }

            e.DrawFocusRectangle();
        }

水曜日, 6月 08, 2011

The formality problem: Java and C# -- extended class

Small things get in the way.

The way to write extended classes in Java and C# differs slightly.

Just for the record the following cases depicts the differences.


The extended class -- the case with Java:
public class NewClassTest
{
class A
 {
   int i=0;
   A(int i)
     {
        this.i=i;
     }
 }

class B extends A
 {
   B()
     {
        super(1);
     }
 }

public void test()
 {
   System.out.println(new B().i);
 }

public static void main(String args[])
 {
    new NewClassTest().test();
 }
}


The extended class -- the case with C#:
class Class1
    {
        protected string value = "to be overwritten";
        public Class1(string convert)
        {
            value = convert;
        }
    }

    class Class2 : Class1
    {
        public Class2(string additional, string convert)
            : base(convert)
        {
            value = convert + additional;
        }
        public string value { get; set; }
    }

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            Class2 test = new Class2(" additional text", "original text");
            label1.Text = test.value;
        }
    }

土曜日, 6月 04, 2011

C# プログレスバーの色を変える

C#のライブラリでは、プログレスバーの色を変えるメソッドが用意されていません。

そこで、「メモリ容量がいっぱいになりました」的な状態を示すために、プログレスバーの色を緑から赤に変える方法を紹介します。

using System.Runtime.InteropServices;

const int WM_USER = 0x400;
const int PBM_SETSTATE = WM_USER + 16;
const int PBM_GETSTATE = WM_USER + 17;

[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = false)]
public static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);

このように、Win32APIを呼び出す関数を用意して、エラー状態をセットしてやります。

public enum ProgressBarStateEnum : int
        {
            Normal = 1,
            Error = 2,
            Paused = 3,
        }

public static void SetState(ProgressBar pBar, ProgressBarStateEnum state)
        {
            SendMessage(pBar.Handle, PBM_SETSTATE, (IntPtr)state, IntPtr.Zero);
        }

SetState(progressBar1, ProgressBarStateEnum.Error);

もとの緑色に変更するには、ノーマル状態に戻してやります。

SetState(progressBar1, ProgressBarStateEnum.Normal);

追記: ここで注意せねばならないのは、プログレスバーのバグで、エラー状態を設定した時点では値が変更されません。

エラー状態を設定したら、値の変更を再度行う必要があります。

これはWindowsのバグらしいです。

if (progressBar1.Maximum * .9 < len)
       {
           progressBar1.Value = 0;
           SetState(progressBar1, ProgressBarStateEnum.Normal);
           progressBar1.Value = len;
           SetState(progressBar1, ProgressBarStateEnum.Error);
       }
else
       {
           progressBar1.Value = len;
           SetState(progressBar1, ProgressBarStateEnum.Normal);
       }

水曜日, 6月 01, 2011

フォームで、まとめてイベントを管理 AddMessageFilter()

Windows フォームで、まとめてイベントを管理したいとします。

その場でテキストエディターを立ち上げて、文字列を編集するときなど、部品全てについてイベント処理しなければなりません。

テキストエディターで編集して、コンポーネントからフォーカスが外れたとき、イベントを管理する必要があります。

これが意外な難関で、WinProcをオーバーライドしても、このメソッドではイベントが処理されません。個々のコンポーネントで処理しなければなりません。

そこで用意されているのが、ApplicationクラスにあるAddMessageFilter()メソッドです。

Application.AddMessageFilter(new MyMessageFilter())

このような形で、MessageFilter派生クラスを指定してやります。

イベント処理は、MessageFilterクラスのPreFilterMessage()メソッドで行います。

ここで、WM_NCLBUTTONDBLCLK 、WM_NCLBUTTONDOWN はタイトルバーでのイベントで、WM_LBUTTONDOWNはクライアントエリアで発生するイベントを指します。

こんな感じです。


       private const int WM_LBUTTONDOWN = 0x201;
       private const int WM_NCLBUTTONDBLCLK = 0x00A3;
       private const int WM_NCLBUTTONDOWN = 0x00A1;

       public bool PreFilterMessage(ref Message msg)
        {
            switch (msg.Msg)
            {
                case WM_NCLBUTTONDBLCLK:
                case WM_NCLBUTTONDOWN:
                case WM_LBUTTONDOWN:
                    {
                        int lparam = (int)msg.LParam;
                        int x = lparam & 0xffff;
                        int y = lparam >> 16;

                        Simulator simulator = (Simulator)sender;
                        Point pos = simulator.RichTextBox1.PointToClient(new Point(x, y));
                        Rectangle rect = new Rectangle(0, 0, simulator.RichTextBox1.Bounds.Width
                            , simulator.RichTextBox1.Bounds.Height + SystemInformation.HorizontalScrollBarThumbWidth);
                        if (!rect.Contains(pos))
                        {
                            simulator.focusOff();
                        }
                    }
                    break;
            }
            return false;
        }

日曜日, 5月 22, 2011

C# クラスのAPIレファレンスの自動生成

C#には、自動的にクラスのAPIレファレンスを作成する機能があります。

Visual Studioでは、プロジェクトのプロパティでXMLファイルを出力できます。



あとはSandcastle Help File Builderなどを使ってレファレンスの形にします。

土曜日, 5月 07, 2011

C#の、プリンタの状態を示すクラス

C#では、プリンタの状態を示すクラスがあって便利です。

プリンタサーバーを指定するクラス PrintServer 、プリンタキューのリストを返すクラス PrintQueueCollection が準備されています。

プリンタキューからジョブリストを得るメソッド GetPrintJobInfoCollection もあります。

LocalPrintServer myPrintServer = new LocalPrintServer();
PrintQueueCollection myPrintQueues = myPrintServer.GetPrintQueues();
string jobList = "";
foreach (PrintQueue pq in myPrintQueues)
{
   if (!pq.IsWaiting)
   {
      PrintJobInfoCollection jobs = pq.GetPrintJobInfoCollection();

      foreach (PrintSystemJobInfo job in jobs)
      {
          jobList = jobList + "Job: " + job.JobName + " ID: " + job.JobIdentifier+"\n";
      }
    }     
}

土曜日, 4月 09, 2011

C#の多次元配列

C#では、配列の宣言がJavaと異なります。

角カッコが、型のほうにつく。

(C#)
string[] nameList={"Ann","Chris","Freda","Darlene","Toni"};

こんな感じです。

これがJavaだと、変数名のほうにつきます。

(Java)
String list[]={"Brad","Alfie","Chris"};

こんなことでも、結構ストレスになるものです。

C#では、多次元配列がさらに特殊な形をとります。

(C#)
int[,] intList = { { 1, 2 }, { 3, 4 } };

あれ、というような意外感があるように思います。

さらに、Javaのように宣言する配列は、C#ではjagged配列という、また別なデータ構造を意味します。

これは、配列の配列という位置づけで、それぞれの配列の要素に、任意の配列を指定できます。

逆に言うと、それぞれの配列の要素に配列を指定しなければなりません。

(C#)
int[][] jaggedList =new int[2][];
jaggedList[0] = new int[2];
jaggedList[1] = new int[3];

注意が必要です。

土曜日, 4月 02, 2011

仕事でC#を使うことに。

C#は、Javaもどきとしか認識しておりませんでしたが、なんといってもマイクロソフトのVisual Studioつき。

IDEが完備しているのは強い。情報もある、といえるでしょう。

使いやすい。

イベントの処理の方法など、VC・C++などと同様に扱えます。

無意味な数値を極力使わないJava系のよさも引き継いています
リソースに「番号」を振り分ける悪趣味は、ここにはない。

コンポーネントに追加した順番ですべてが決まります。

--

Eclipse と比較すると、ヘルプやサンプルコードにすぐにアクセス出来ない、遠い感じがします。

情報はすべからくHTML形式にして、ネットに置いて欲しいものです。

Flask の Blueprint のテンプレート問題

  Flask の Blueprint は、ルート、静的ファイル、テンプレートをまとめて管理できます。しかし、テンプレートが指定できません。 ここでは、Blueprint の template_folder の問題点と回避策を説明します。 Blueprint のテンプレート問題...