WriteLine()で書き込んでも、フラッシュしないと読めない(場合がある)。
特に、長いデータを書き込んだとき、最後の方が一部だけ読めないときなどはこのパターン。
MemoryStream stream = new MemoryStream(); StreamWriter writer = new StreamWriter( stream ); writer.WriteLine("test"); writer.Flush(); // <= これが必要 |
忘れがちなので注意!!
WriteLine()で書き込んでも、フラッシュしないと読めない(場合がある)。
特に、長いデータを書き込んだとき、最後の方が一部だけ読めないときなどはこのパターン。
MemoryStream stream = new MemoryStream(); StreamWriter writer = new StreamWriter( stream ); writer.WriteLine("test"); writer.Flush(); // <= これが必要 |
Windowsでは通常GUI(WinForm)のプログラムを作成した場合、通常ではコンソールへの文字出力を行う事ができません。コンソールアプリケーションでの文字列出力メソッドのSystem.Console.WriteLine()を試しに呼び出してみても、残念ながら何も出力されません。
ですが、プログラムのデバッグなど、コンソールに文字出力ができると便利なな場合も有ります。
このような場合、Win32 APIをコールする事で出力が可能です。
using System; using System.Windows.Forms; using System.Runtime.InteropServices; //DllImport属性を使用するために必要 namespace WinFormTest1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); // コンソールにログを出力 writeConsole( "Form1() called" ); } private void Form1_Load( object sender, EventArgs e ) { // コンソールにログを出力 writeConsole( "Form1_Load called" ); } [DllImport("kernel32.dll")] public static extern bool AttachConsole(uint dwProcessId); [DllImport("kernel32.dll")] public static extern bool FreeConsole(); //********************************************************************* /// <summary> コンソールに文字を出力する /// /// </summary> /// <param name="msg"> 出力する文字列</param> /// <returns> true:成功, false:失敗</returns> //********************************************************************* private bool writeConsole( string msg ) { if ( !AttachConsole( System.UInt32.MaxValue ) ) { return false; } // stdoutのストリームを取得 System.IO.Stream stream = System.Console.OpenStandardOutput(); System.IO.StreamWriter stdout = new System.IO.StreamWriter( stream ); // 指定された文字列を出力 stdout.WriteLine( msg ); stdout.Flush(); FreeConsole(); return true; } } } |
[Parameters] dwProcessId [in] ATTACH_PARENT_PROCESS (DWORD)-1 Use the console of the parent of the current process. |

http://pukiwiki.cafelounge.net/plus/でPukiWikiを改造したPukiWiki Plus!というものが提供されています。
PukiWiki Plus!ではユーザ認証として、Digest認証や外部認証APIの利用ができるらしいですが、
これらの認証を使用したくない/使用できない場合や、そこまで本格的な認証は欲しくないけど簡易的なbot対策を行いたい場合があります。
このような場合のために、PukiWiki Plus!に対してページ編集時にパスワードを要求するようなパッチを当ててみました。
下記の変更を行う事で、パスワードを入力しないとコンテンツを編集できないようになります。
1.lib\html.phpのedit_form関数を変更
関数内の$body変数に対して、以下のタグ(パスワード入力欄)を追加します。
<textarea name="msg" rows="$rows" cols="$cols">$s_postdata</textarea> <br /> |
<textarea name="msg" rows="$rows" cols="$cols">$s_postdata</textarea> <br /> password:<input type="password" name="edit_password" maxlength="10" value="" /> <br /> |
$edit_passwd = isset($vars['edit_password']) ? $vars['edit_password'] : ''; if ($edit_passwd != "pass" ) { $retvars = array(); $retvars['msg'] = "auth error"; $retvars['body'] = "please input password."; return $retvars; } |
$edit_passwd = isset($vars['edit_password']) ? $vars['edit_password'] : ''; if ($edit_passwd != "pass" ) { return plugin_edit_honeypot(); } |
PukiWikiで管理者のパスワードを入力しないと、ページの編集不可にさせるよう、認証を行う方法です。
インストール先フォルダにあるpukiwiki.ini.phpを編集します。
$auth_usersの定義がされている場所を探し、既存のユーザをコメントアウトした後に、新しいユーザを作成します。
パスワードは安全のため、md5で変換した後の値をセットしておきます(下記のxxxxの場所)
また、md5の変換は、このページで行う事ができます。
$auth_users = array( // Username => password 'admin' => '{x-php-md5}xxxx', // 'foo' => 'foo_passwd', // Cleartext // 'bar' => '{x-php-md5}f53ae779077e987718cc285b14dfbe86', // PHP md5() 'bar_passwd' // 'hoge' => '{SMD5}OzJo/boHwM4q5R+g7LCOx2xGMkFKRVEx', // LDAP SMD5 'hoge_passwd' ); |
$auth_method_type = 'pagename'; // By Page name |
$edit_auth = 1; // 1:認証が必要 $edit_auth_pages = array( // Regex Username '##' => 'admin', // 全頁に対してadmin権限を要求 // '#BarDiary#' => 'bar', // '#HogeHoge#' => 'hoge', // '#(NETABARE|NetaBare)#' => 'foo,bar,hoge', ); |
StreamWriterを使用してファイルを書き込む場合、通常以下のような感じでコーディングを行う。
using( StreamWriter writer = new StreamWriter( stream, Encoding.GetEncoding(932) ) ) { writer.Write( ... ); } |
using( FileStream stream = new FileStream( filename, FileMode.Create, FileAccess.Write, FileShare.None ) ) using( StreamWriter writer = new StreamWriter( stream, Encoding.GetEncoding(932) ) ) { writer.Write( ... ); } |
DataGridViewコントロールに表示されているデータから,指定した条件に一致する行をLINQを使って取得するサンプルです。
ちょっと長いですが、1行で取得可能です。
string keyValue = "key1"; // 検索条件 DataGridViewRowCollection rowList = null; try { rowList = DataGridView1.Rows.Cast<DataGridViewRow>().Select( row => row.Cells[ "ColKey" ].Value.Equals( keyValue ) ); } catch( Exception ex ) { // 該当データなし時は、例外が発生する MessageBox.Show( ex.Message ); } |
string keyValue = "key1"; // 検索条件 DataGridViewRow row = null; try { row = DataGridView1.Rows.Cast<DataGridViewRow>().First( row => row.Cells[ "ColKey" ].Value.Equals( keyValue ) ); } catch( Exception ex ) { // 該当データなし時は、例外が発生する MessageBox.Show( ex.Message ); } |
FirefoxやIEには、画面上部のアドレス表示欄の右に、検索バーが有ります。
検索バーを使うと、人気のある検索エンジンを、そのサイトを開くことなく利用することができるので大変便利です。

今回は、この検索バーにWordPressで作ったblogサイトを検索できるようにする方法を説明します。
まず、下記のファイルを作成し、Webサーバ上の適当なフォルダに置きます。
(今回はhttp://nanoappli.com/nanoappli_blogsearch.xmlにおいたとして説明します)
<OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/">
<ShortName>nanoappli.com BlogSearch</ShortName>
<site>http://nanoappli.com/</site>
<InputEncoding>UTF-8</InputEncoding>
<Url type="text/html" template="http://nanoappli.com/blog/?s={searchTerms}" />
</OpenSearchDescription> |
<a onclick="window.external.AddSearchProvider("http://nanoappli.com/nanoappli_blogsearch.xml");">
nanoappli.com 検索プラグインを追加
</a> |



<link rel="search"
type="application/opensearchdescription+xml"
title="nanoappli.comサーチ"
href="http://nanoappli.com/nanoappli_blogsearch.xml"> |

Dan Kogai氏が下記のページで公開しているamazonの書籍情報取得APIが有ります。
Ajax – AWS Caching Proxy w/ Authentication Support
これを利用して、C#にて指定したASINの書籍情報を取得するサンプルです。
//********************************************************************* /// <summary> dan.co.jpのwebapiを使用してアマゾンの書籍情報を取得する /// /// </summary> /// <param name="asin"> 検索キー(ASIN)</param> /// <returns>書籍情報</returns> //*********************************************************************- private static XmlDocument searchItemInfoByAsin( string asin ) { string url = "http://api.dan.co.jp/asin/" + asin + ".xml"; using (XmlReader reader = XmlReader.Create(url)) { XmlDocument doc = new XmlDocument(); doc.Load( reader ); return doc; } } |
//----------------------- // 商品情報を取得する //----------------------- XmlDocument itemDoc = null; try { itemDoc = searchItemInfoByAsin( "4534045220" ); } catch ( Exception ex ) { MessageBox.Show( "商品データの取得に失敗しました id[" + id + "]\n" + ex.Message ); continue; } string asin = getNodeTextDef( itemDoc, "/opt/ASIN", "" ); string title = getNodeTextDef( itemDoc, "/opt/ItemAttributes/Title", "" ); string author = getNodeTextDef( itemDoc, "/opt/ItemAttributes/Author", "" ); string binding = getNodeTextDef( itemDoc, "/opt/ItemAttributes/Binding", "" ); string label = getNodeTextDef( itemDoc, "/opt/ItemAttributes/Label", "" ); string newPrice = getNodeTextDef( itemDoc, "/opt/ItemAttributes/ListPrice/FormattedPrice", "" ); string imageUrl = getNodeTextDef( itemDoc, "/opt/ImageSets/SwatchImage/URL", "" ); string linkUrl = getNodeTextDef( itemDoc, "/opt/DetailPageURL", "" ); System.Console.WriteLine( asin ); System.Console.WriteLine( title ); System.Console.WriteLine( author ); System.Console.WriteLine( binding ); System.Console.WriteLine( label ); System.Console.WriteLine( newPrice ); System.Console.WriteLine( imageUrl ); System.Console.WriteLine( linkUrl ); |
XmlDocumentから指定されたノードの情報(InnerText)をxpathで取得するメソッドです。
該当するノードが複数存在する場合は、最初のノードを取得します。
また、1つも存在しない場合は第三引数で指定された値を返します(これは,VCLのAnsiString::ToIntDefメソッド的な振る舞いです)。
//********************************************************************* /// <summary> XmlDocumentから指定されたノードの情報を取得する /// </summary> /// <param name="doc"> 取得対象のxml情報</param> /// <param name="xpath"> 取得するノードのxpath式</param> /// <param name="defaultValue"> 指定したノードが無かったときの値</param> /// <returns>ノードのテキスト(InnerXml)</returns> //********************************************************************* private static string getNodeTextDef( XmlDocument doc, string xpath, string defaultValue ) { XmlNode node = doc.SelectSingleNode( xpath ); if ( node == null ) { return defaultValue; } else { return node.InnerText; } } |
.NetFrameworkに用意されているSystem.Drawing.Imageクラスは、FromFile()メソッドで画像データをファイルから読み込む事ができますが、Web上に存在する画像をURL指定で読み込ませる事はできません。
そこで、urlを指定してImage型データを取得するメソッドを作成しました。
//--------------------------------------------------------------------------- /// <summary> /// 指定されたURLの画像をImage型オブジェクトとして取得する /// </summary> /// <param name="url">画像データのURL(ex: http://example.com/foo.jpg) </param> /// <returns> 画像データ</returns> //--------------------------------------------------------------------------- public static System.Drawing.Image loadImageFromURL( string url ) { int buffSize = 65536; // 一度に読み込むサイズ MemoryStream imgStream = new MemoryStream(); //------------------------ // パラメータチェック //------------------------ if ( url == null || url.Trim().Length <= 0 ) { return null; } //---------------------------- // Webサーバに要求を投げる //---------------------------- WebRequest req = WebRequest.Create( url ); BinaryReader reader = new BinaryReader( req.GetResponse().GetResponseStream() ); //-------------------------------------------------------- // Webサーバからの応答データを取得し、imgStreamに保存する //-------------------------------------------------------- while ( true ) { byte[] buff = new byte[ buffSize ]; // 応答データの取得 int readBytes = reader.Read( buff, 0, buffSize ); if ( readBytes <= 0 ) { // 最後まで取得した->ループを抜ける break; } // バッファに追加 imgStream.Write( buff, 0, readBytes ); } return new Bitmap( imgStream ); } |

CrystalReportsを使用して帳票印刷を行う際、印字するテキストが長すぎてフィールドの枠内に入りきらない場合、印字が欠けてしまいます。
このような場合、Excelだったら「縮小して全体を表示」という書式設定をしておくと、印字内容のデータ長に合わせて自動でフォントサイズを縮小させる事ができるのですが、残念ながらCrystal Reportsには、これと同じ機能は有りません。
そこで、今回はCrystal Reportsで、印字するデータの長さに応じてフォントサイズを調整させる方法を説明します。




If ( Length( {RepAddressLabel.Name} ) < 24 ) Then
12
Else If ( Length( {RepAddressLabel.Name} ) < 28 ) Then
10
Else
9 |

DataSet1.RepAddressLabelDataTable table = new DataSet1.RepAddressLabelDataTable(); [中略] dataRow = (DataSet1.RepAddressLabelRow)table.NewRow(); dataRow.Name = ...; dataRow.Name_LenB = Encoding.GetEncoding("Shift_JIS").GetByteCount( dataRow.Name ); |

If ( {RepAddressLabel.Name_LenB} < 24 ) Then
12
Else If ( {RepAddressLabel.Name_LenB} < 28 ) Then
10
Else
9 |

ヤマト運輸には厚さ2cm以内の商品を格安で配送する事ができるメール便というサービスがあります。
メール便の依頼はコンビニ受付が有名ですが、その他にも、ヤマト運輸のサイト上で集荷依頼を行い、家まで取りに来てもらう事もできるので便利です。
…ですが、ヤマト運輸のサイトより集荷依頼を行う場合、web上での操作が煩雑(5画面くらい作業する必要がある)で面倒くさいので、ブラウザを自動操作するプログラムを作成しました。





/UserId ユーザID
ユーザIDを指定します
/Password パスワード
パスワードを指定します
/SyukaDate 出荷日選択肢のindex
出荷日の選択肢の位置を指定します。
0を指定すると「選択してください」、1だと直近の日付になります。
/SyukaTime 出荷日選択肢のindex
0を指定すると「選択してください」、1だと「指定なし」になります。
/ItemName 商品名
商品名を指定します。 全角で指定してください。
/Suryo 数量
数量を指定します。 数量は半角で1以上の数値です。
/IsSlipReady
伝票用意済みにチェックが入ります。
/IsSlipNeed
伝票を集荷の時に用意してほしいにチェックが入ります。
/AutoClickConfirm
集荷受付画面で、次へボタンを自動クリックします。
/AutoClickSubmit
依頼内容確認画面で、確定する場短を自動クリックします。
※ヤマト運輸へ集荷依頼が実際に行われるので、本機能は
このプログラムの動作を十分に理解してから使用してください!!
/Silent 1
プログラム起動と同時に「集荷依頼を行う」画面が表示されます
/Silent 2
プログラム起動と同時に集荷依頼が行われます |
KuronekoRequest.exe /UserId user /Password pass /SyukaDate 1 /SyukaTime 1 /ItemName 書籍 /Suryo 10 /IsSlipNeed /Silent 1 |
VBScriptで以下のコマンドを実行する事で、ノートPCの残バッテリー容量を取得する事ができます。
データの取得にはwmiを使用しているのでC#など、他の言語への移植も簡単かと思います。
'--------------------------------------------------- ' ノートPCのバッテリ算容量を取得する ' usage: cscript /Nologo バッテリ容量.vbs '--------------------------------------------------- Set rows = GetObject("winmgmts:\\.\root\cimv2").ExecQuery("Select * from Win32_Battery",,48) For Each row in rows Wscript.Echo "バッテリ容量: " & row.EstimatedChargeRemaining & "%" Wscript.Echo "残り使用時間: " & row.EstimatedRunTime & "分" Next |
cscript.exe /Nologo バッテリ容量.vbs |
AVRのワンチップマイコンにはfuse bit(ヒューズビット)というものがあり、これによってチップの動作を設定することができます。fuse bitには各ビットごとに意味があり、その意味はチップの型番によって異なるので注意が必要です。
ATmega328Pチップの、各fuse bitの意味です。
(画像上部のNote:にも有りますが,チェックが入っていない時がON”=1″なので注意!!)
http://www.engbedded.com/fusecalc より
各fuse bitの初期値は以下の通りです。
Low : 0x62 High: 0xD9 Ext : 0xFF |
avrdude.exe -C ..\etc\avrdude.conf -c arduino -p m328p -t -B 4800 -P COM7 hfuse:w:0b11011001:m -U lfuse:w:0b01100010:m |
Usage: avrdude [options]
Options:
-p <partno> Required. Specify AVR device.
-b <baudrate> Override RS-232 baud rate.
-B <bitclock> Specify JTAG/STK500v2 bit clock period (us).
-C <config-file> Specify location of configuration file.
-c <programmer> Specify programmer type.
-D Disable auto erase for flash memory
-i <delay> ISP Clock Delay [in microseconds]
-P <port> Specify connection port.
-F Override invalid signature check.
-e Perform a chip erase.
-O Perform RC oscillator calibration (see AVR053).
-U <memtype>:r|w|v:<filename>[:format]
Memory operation specification.
Multiple -U options are allowed, each request
is performed in the order specified.
-n Do not write anything to the device.
-V Do not verify.
-u Disable safemode, default when running from a script.
-s Silent safemode operation, will not ask you if
fuses should be changed back.
-t Enter terminal mode.
-E <exitspec>[,<exitspec>] List programmer exit specifications.
-y Count # erase cycles in EEPROM.
-Y <number> Initialize erase cycle # in EEPROM.
-v Verbose output. -v -v for more.
-q Quell progress output. -q -q for less.
-? Display this usage. |

arduinoでAruduinoISPを使用してbootloaderを書き込み時に下記のエラーが出たので,その内容を調べたときのメモです。
Yikes! Invalid device signature. |
Why do I get errors about an invalid device signature when trying to upload a sketch?
If you get an error like:
avrdude: Yikes! Invalid device signature.
Double check connections and try again, or use -F to override
this check.
it can mean one of two things. Either you have the wrong board selected from
the Tools > Board menu or you're not using the right version of avrdude.
Arduino uses a slightly modified version of avrdude to upload sketches to
the Arduino board.
The standard version queries for the board's device signature in a way not
understood by the bootloader, resulting in this error. Make sure you're using
the version of avrdude that comes with Arduino. |
WebBrowserコントロールに表示されたラジオボタンに対して、特定の項目を選択する方法です。
サンプルとして、以下のようなhtmlがあった場合に…
<input type="radio" value="1" id="selId1">選択肢1</input> <input type="radio" value="2" id="selId2">選択肢2</input> <input type="radio" value="3" id="selId3">選択肢3</input> |
// 2番目の選択肢にチェックを入れる HTMLInputElementClass selectBoxObj; selectBoxObj = document.GetElementById( "selId2" ).DomElement as HTMLInputElementClass; selectBoxObj.setAttribute( "checked", "checked" ); |
下記のコードで、上から200pxの位置が画面の一番上になるようにスクロールされます。
横位置をずらしたい場合はPointの第一引数に値を指定します。
webBrowser1.Document.Window.ScrollTo( new Point(0,200) ); |
WinFormsを使用したプログラムで、指定したコントロールにフォーカスをセットするには、
通常ではSetFocus()メソッドを使用します。
button1.SetFocus(); |
1.親画面からForm.Show()メソッド(又はShowDialog)をコールする ↓ 2.子画面のOnLoad()イベントが指定されていたら、実行する ↓ 3.子画面に配置されているコントロールのTabStopをチェックし、初期フォーカスをセットする ↓ 4.子画面が開く |
private void Form1_Load(object sender, System.EventArgs e) { // 初期フォーカスをセット ActiveControl = button1; } |
VisualStudioでWinFormを使用したプログラムを作成する場合、Form_Load()処理などのイベントハンドラを作成しハンドラ内に処理を記述していきます。
この際、Form_Load()の呼び出し元側は、.Net Frameworkのイベントループ処理となるのですが、この処理は呼び出し履歴ウィンドウで確認しても”外部コード”と表示されているだけで、どんなメソッドが呼び出されているか分かりません。

今回は、デバッグ時に”外部コード”の中身を表示させ、呼び元側にジャンプできるようにする方法を説明します。
これには、ステップインができるように、VisualStudio設定を変更させる必要があります。











--------------- Overview --------------- The Microsoft Reference Source License (MS-RSL) is the most restrictive of the Microsoft source code licenses. The license prohibits all use of source code other than the viewing of the code for reference purposes. The intent of this license is to enable licensors to release, for review purposes only, more sensitive intellectual property assets. Microsoft commonly uses this license for developer libraries where modification is not required to make use of the source code. In these cases, the importance of transparency is based on the need for developers to more deeply understand the inner workings of the source code. In doing so, the licensees will be more effective in writing software that makes use of the licensed source code. The copyright and patent grants in this license are both royalty free, meaning that the licensee does not have to pay anything to the licensor to make use of the source code. The license limits the source code release to use on the Windows platform only. Microsoft cannot provide legal advice on the use or implications of this license. We recommend that developers obtain appropriate legal advice before deciding how to license their source code. The source code for the .NET Framework libraries are released under a modified Microsoft Reference Source License. --------------- Terms of Use --------------- Developers who wish to access source code under the Reference Source Program must agree to the license that accompanies the code. Licensees may use the source code to assist with the development of commercially distributed products. Licensees may not modify or redistribute the source code. ------------------------- Eligibility Requirements ------------------------- There are no eligibility requirements for this program. Everyone who agrees to the accompanying license may use the source code provided under the Reference Source Program. |