SQLの窓

2013年09月20日


VS2010 コンソール : Twitter ツイートとリツイート

SkyDrive へ移動

※ VS2010 用

■ テキストファイル(SHIFT_JIS)の内容を OpenFileDialog で開いて読み込む
■ 読み込んだテキストをツイートする
■ ツイートの結果の JSON 内の日本語を元に戻してインデント整形して UTF8N で出力
■ ツイートの結果の JSON を定義したクラスのインスタンスに一括投入後インデント整形して UTF8N で出力

以上の処理を リツイートに対しても行います



JSON の処理は、Json.NET を使用しています(テンプレートに同梱)

1) 整形
JObject jo = JObject.Parse(json);
string json_work = JsonConvert.SerializeObject(jo, Formatting.Indented);
2) デシリアライズと整形
TweetResult tr = JsonConvert.DeserializeObject(json);
json_work = JsonConvert.SerializeObject(tr, Formatting.Indented);
-----
private class TweetResult
{
	public string created_at { get; set; }
	public string id { get; set; }
	public string text { get; set; }
}
Program.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Reflection;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace TryApp_Tweet1
{
	public class Program
	{
		// 外部テキストファイルを読み込んだ内容
		static string text = "まだ読み込まれていません";
		static string json = "まだセットされていません";

		[STAThreadAttribute]
		static void Main(string[] args)
		{
			App app = new App();

			// イベントの追加
			app.ShowEnv += MyProc1;
			app.GetDir += (string path) =>
			{
				Console.WriteLine(path + " が選択されました");
				string[] filenames = null;
				if (path != "") {
					filenames = Directory.GetFiles(path);
					foreach (string value in filenames) {
						Console.WriteLine(value);
					}
				}
			};

			// ******************************************
			// ファイルを選択
			// ******************************************
			app.GetFile += (string path) =>
			{
				// 外部ファイルが SHIFT_JIS で書かれているという前提で読み込む
				StreamReader reader = new StreamReader(path, Encoding.GetEncoding("shift_jis"));
				// 一気に全て読み込み
				text = reader.ReadToEnd();
				reader.Close();
				Console.WriteLine(path + " が読み込まれました");
			};

			// ******************************************
			// テキストを表示
			// ******************************************
			app.DisplayText += (string cmd) =>
			{
				Console.WriteLine(text);
			};
			// ******************************************
			// JSONを表示
			// ******************************************
			app.DisplayJson += (string cmd) =>
			{
				JObject jo = JObject.Parse(json);
				string json_work = JsonConvert.SerializeObject(jo, Formatting.Indented);
				Console.WriteLine(json_work);
			};


			// ******************************************
			// ツイート処理の登録
			// ******************************************
			// メソッドによる実装
			app.Cmd += Tweet;
			// ラムダ式による実装
			app.Cmd += (string cmd) =>
			{
				Console.WriteLine(cmd + " が実行されました");
			};

			// ******************************************
			// 終了せずに、コマンドプロンプトを保持する。
			// ( "q" で終了 )
			// ******************************************
			app.Loop();

		}

		// ******************************************
		// 環境周りの情報
		// ******************************************
		static private void MyProc1(string[] data)
		{

			foreach (string value in data) {
				Console.WriteLine(value);
			}

		}

		// ******************************************
		// 処理のテンプレート
		// ******************************************
		static private void Tweet(string cmd)
		{

			VS2010_Twitter twitter =
				new VS2010_Twitter(
					"Consumer key",
					"Consumer secret",
					"Access token",
					"Access token secret"
			);

			switch (cmd) {
				case "tweet":
					// 投稿
					json = twitter.Tweet(text);
					break;
				// retweet:id でリツイート
				default:
					// id を取得する為に、":" で配列に分解
					string[] param = cmd.Split(new[] { ":" }, StringSplitOptions.None);
					// id でリツイート
					json = twitter.ReTweet(param[1]);
					break;
			}

			// 取得した JSON を utf8n で書き込む
			string thisPath = Assembly.GetExecutingAssembly().Location;
			string thisDir = Path.GetDirectoryName(thisPath);
			string path = thisDir + @"\" + "json.txt";
			StreamWriter writer = new StreamWriter(path, false, new UTF8Encoding(false));

			// JSON の日本語表示を元に戻して整形
			JObject jo = JObject.Parse(json);
			string json_work = JsonConvert.SerializeObject(jo, Formatting.Indented);
			// 書き込み
			writer.Write(json_work);
			writer.Close();

			// オブジェクトに直接投入
			TweetResult tr = JsonConvert.DeserializeObject<TweetResult>(json);
			Console.WriteLine(tr.created_at);
			Console.WriteLine(tr.id);
			Console.WriteLine(tr.text);

			// クラスに投入した内容を出力
			path = thisDir + @"\" + "json2.txt";
			writer = new StreamWriter(path, false, new UTF8Encoding(false));
			json_work = JsonConvert.SerializeObject(tr, Formatting.Indented);
			// 書き込み
			writer.Write(json_work);
			writer.Close();

		}

		private class TweetResult
		{
			public string created_at { get; set; }
			public string id { get; set; }
			public string text { get; set; }
		}


	}
}


App.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.IO;
using System.Windows.Forms;

namespace TryApp_Tweet1
{

	class App
	{

		// 引数が一つのイベント
		public delegate void AppHandler(string cmd);
		// 引数が文字列配列のイベント
		public delegate void AppHandlerResults(string[] data);

		// 環境周りの情報を取得するイベント
		public event AppHandlerResults ShowEnv = null;
		// フォルダ選択ダイアログ
		public event AppHandler GetDir = null;
		// ファイル選択ダイアログ
		public event AppHandler GetFile = null;
		// イベントのテンプレート
		public event AppHandler Cmd = null;

		// 追加イベント
		public event AppHandler DisplayText = null;
		public event AppHandler DisplayJson = null;


		// ******************************************
		// コンストラクタ
		// ******************************************
		public App()
		{
		}

		// ******************************************
		// 終了せずに、コマンドプロンプトを保持する。
		// ******************************************
		public void Loop()
		{
			while (true) {
				// ******************************************
				// 専用プロンプト
				// ******************************************
				Console.Write("app>");
				string line = Console.ReadLine();

				// ******************************************
				// 終了コマンド
				// ******************************************
				if (line == "q") {
					break;
				}

				// ******************************************
				// 環境周りの情報を取得するイベント
				// ******************************************
				if (line == "env") {
					if (ShowEnv != null) {
						// 実行ファイル
						string thisPath = Assembly.GetExecutingAssembly().Location;
						// 実行ファイルのあるディレクトリ
						string thisDir = Path.GetDirectoryName(thisPath);
						string[] result = { line, thisPath, thisDir };
						ShowEnv(result);
					}
				}

				// ******************************************
				// フォルダ選択
				// ******************************************
				if (line == "dir") {
					if (GetDir != null) {
						// フォルダ選択ダイアログ
						var dir = new FolderBrowserDialog();
						dir.SelectedPath = @"c:\";
						var result = dir.ShowDialog();
						string path = "";
						if (result == DialogResult.OK) {
							path = dir.SelectedPath;
						}
						GetDir(path);
					}
				}

				// ******************************************
				// フアイル選択
				// ******************************************
				if (line == "file") {
					if (GetFile != null) {
						// ファイル選択ダイアログ
						var file = new OpenFileDialog();
						file.Filter = "全て|*.*|テキスト|*.txt;*.log";
						file.FilterIndex = 0;
						file.FileName = "";
						var dr = file.ShowDialog();
						string path = "";
						if (dr == DialogResult.OK) {
							path = file.FileName;
						}
						GetFile(path);
					}
				}

				// ******************************************
				// イベントのテンプレート
				// ******************************************
				if (line == "tweet" || (line + "       ").Substring(0, 7) == "retweet") {
					if (Cmd != null) {
						Cmd(line);
					}
				}

				// ******************************************
				// 追加のイベント
				// ******************************************
				if (line == "text") {
					if (DisplayText != null) {
						DisplayText(line);
					}
				}

				if (line == "json") {
					if (DisplayJson != null) {
						DisplayJson(line);
					}
				}

			}
		}
	}
}

関連する記事VS2010_Twitter.csアプリケーションテスト用コンソールアプリ(TryApp)テンプレート


posted by lightbox at 2013-09-20 18:06 | VS(C#) | このブログの読者になる | 更新情報をチェックする

2013年09月15日


TryAppテンプレートを使って『The Zip, GZip, BZip2 and Tar Implementation For .NET』のテスト



The Zip, GZip, BZip2 and Tar Implementation For .NET より dll とサンプル をダウンロードして、サンプル内の 『CreateZipFile』と 『viewzipfile』 を実装してテストしました
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

using ICSharpCode.SharpZipLib.Zip;

namespace TryApp1
{
	public class Program
	{

		[STAThreadAttribute]
		static void Main(string[] args)
		{
			App app = new App();

			// イベントの追加
			app.ShowEnv += MyProc1;
			app.GetDir += (string path) =>
			{
				Console.WriteLine(path + " が選択されました");
				string[] filenames = null;
				if (path != "") {
					// 選択したディレクトリ内のファイル一覧
					filenames = Directory.GetFiles(path);
					try {
						// 対象ファイルと同じディレクトリに test.zip を作成
						using (ZipOutputStream s = new ZipOutputStream(File.Create(path + @"\test.zip"))) {

							s.SetLevel(9); // 0 - store only to 9 - means best compression

							byte[] buffer = new byte[4096];

							foreach (string file in filenames) {

								// 格納用のオブジェクトを作成
								ZipEntry entry = new ZipEntry(Path.GetFileName(file));

								// 格納時のタイムスタンプ
								entry.DateTime = DateTime.Now;
								// (ZipOutputStream に)格納
								s.PutNextEntry(entry);

								// 実体の格納
								using (FileStream fs = File.OpenRead(file)) {
									int sourceBytes;
									do {
										sourceBytes = fs.Read(buffer, 0, buffer.Length);
										s.Write(buffer, 0, sourceBytes);
									} while (sourceBytes > 0);
								}
							}

							// 後処理
							s.Finish();
							s.Close();
						}

					}
					catch (Exception ex) {
						Console.WriteLine(ex.Message);
					}

					Console.WriteLine(path + @"\test.zip を作成しました" );

				}
			};

			app.GetFile += (string path) =>
			{

				byte[] data = new byte[4096];

				using (ZipInputStream s = new ZipInputStream(File.OpenRead(path))) {

					ZipEntry theEntry;
					while ((theEntry = s.GetNextEntry()) != null) {
						Console.WriteLine("Name : {0}", theEntry.Name);
						Console.WriteLine("Date : {0}", theEntry.DateTime);
						Console.WriteLine("Size : (-1, if the size information is in the footer)");
						Console.WriteLine("      Uncompressed : {0}", theEntry.Size);
						Console.WriteLine("      Compressed   : {0}", theEntry.CompressedSize);

						if (theEntry.IsFile) {

							Console.Write("ファイルの内容を表示しますか (y/n) ?");
							// y のみ表示
							if (Console.ReadLine() == "y") {
								int size = s.Read(data, 0, data.Length);
								while (size > 0) {
									Console.Write(Encoding.ASCII.GetString(data, 0, size));
									size = s.Read(data, 0, data.Length);
								}
							}
							Console.WriteLine();
						}
					}

					// ZipInputStream を閉じる
					s.Close();
				}

			};

			// メソッドによる実装
			app.Cmd += MyProc2;
			// ラムダ式による実装
			app.Cmd += (string cmd) =>
			{
				Console.WriteLine(cmd + " が実行されました");
			};

			// ******************************************
			// 終了せずに、コマンドプロンプトを保持する。
			// ( "q" で終了 )
			// ******************************************
			app.Loop();

		}

		// ******************************************
		// 環境周りの情報
		// ******************************************
		static private void MyProc1(string[] data)
		{

			foreach (string value in data) {
				Console.WriteLine(value);
			}

		}

		// ******************************************
		// 処理のテンプレート
		// ******************************************
		static private void MyProc2(string cmd)
		{

			Console.WriteLine(cmd);
		}

	}
}


関連する記事

アプリケーションテスト用コンソールアプリ(TryApp)テンプレート



posted by lightbox at 2013-09-15 20:29 | VS(C#) | このブログの読者になる | 更新情報をチェックする

アプリケーションテスト用コンソールアプリ(TryApp)テンプレート

SkyDrive へ

VS2010用 TryApp.zip テンプレート



機能のテストをしたい場合、やはりコンソールアプリが手軽です。イベント単位で実装する事になるので、後から再利用する際にもわかり易くて良いと思います。
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace TryApp1
{
	public class Program
	{

		[STAThreadAttribute]
		static void Main(string[] args)
		{
			App app = new App();

			// イベントの追加
			app.ShowEnv += MyProc1;
			app.GetDir += (string path) =>
			{
				Console.WriteLine(path + " が選択されました" );
				string[] filenames = null;
				if (path != "") {
					filenames = Directory.GetFiles(path);
					foreach (string value in filenames) {
						Console.WriteLine(value);
					}
				}
			};

			app.GetFile += (string path) =>
			{
				Console.WriteLine(path + " が選択されました");
			};

			// メソッドによる実装
			app.Cmd += MyProc2;
			// ラムダ式による実装
			app.Cmd += (string cmd) =>
			{
				Console.WriteLine(cmd + " が実行されました");
			};

			// ******************************************
			// 終了せずに、コマンドプロンプトを保持する。
			// ( "q" で終了 )
			// ******************************************
			app.Loop();

		}

		// ******************************************
		// 環境周りの情報
		// ******************************************
		static private void MyProc1( string[] data ) {

			foreach (string value in data) {
				Console.WriteLine( value );
			}

		}

		// ******************************************
		// 処理のテンプレート
		// ******************************************
		static private void MyProc2( string cmd ) {

			Console.WriteLine( cmd );
		}
	
	}
}

STAThreadAttribute は、ダイアログを開く時に必要でした

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.IO;
using System.Windows.Forms;

namespace TryApp1
{

	class App
	{

		// 引数が一つのイベント
		public delegate void AppHandler(string cmd);
		// 引数が文字列配列のイベント
		public delegate void AppHandlerResults(string[] data);

		// 環境周りの情報を取得するイベント
		public event AppHandlerResults ShowEnv = null;
		// フォルダ選択ダイアログ
		public event AppHandler GetDir = null;
		// ファイル選択ダイアログ
		public event AppHandler GetFile = null;
		// イベントのテンプレート
		public event AppHandler Cmd = null;

		// ******************************************
		// コンストラクタ
		// ******************************************
		public App()
		{
		}

		// ******************************************
		// 終了せずに、コマンドプロンプトを保持する。
		// ******************************************
		public void Loop()
		{
			while (true) {
				// ******************************************
				// 専用プロンプト
				// ******************************************
				Console.Write("app>");
				string line = Console.ReadLine();

				// ******************************************
				// 終了コマンド
				// ******************************************
				if (line == "q") {
					break;
				}

				// ******************************************
				// 環境周りの情報を取得するイベント
				// ******************************************
				if (line == "env") {
					if (ShowEnv != null) {
						// 実行ファイル
						string thisPath = Assembly.GetExecutingAssembly().Location;
						// 実行ファイルのあるディレクトリ
						string thisDir = Path.GetDirectoryName(thisPath);
						string[] result = { line, thisPath, thisDir };
						ShowEnv(result);
					}
				}

				// ******************************************
				// フォルダ選択
				// ******************************************
				if (line == "dir") {
					if (GetDir != null) {
						// フォルダ選択ダイアログ
						var dir = new FolderBrowserDialog();
						dir.SelectedPath = @"c:\";
						var result = dir.ShowDialog();
						string path = "";
						if (result == DialogResult.OK) {
							path = dir.SelectedPath;
						}
						GetDir(path);
					}
				}

				// ******************************************
				// フアイル選択
				// ******************************************
				if (line == "file") {
					if (GetFile != null) {
						// ファイル選択ダイアログ
						var file = new OpenFileDialog();
						file.Filter = "全て|*.*|テキスト|*.txt;*.log";
						file.FilterIndex = 0;
						file.FileName = "";
						var dr = file.ShowDialog();
						string path = "";
						if (dr == DialogResult.OK) {
							path = file.FileName;
						}
						GetFile(path);
					}
				}

				// ******************************************
				// イベントのテンプレート
				// ******************************************
				if (line == "cmd") {
					if (Cmd != null) {
						Cmd(line);
					}
				}

			}
		}
	}
}

AppHandler または AppHandlerResults を使うか、デリゲートを増やして event を作成して機能追加します。

関連する記事コンソールアプリケーション(C#) で、クラス、デリゲート、イベント、ラムダ式の振舞いを理解するTryAppテンプレートを使って『The Zip, GZip, BZip2 and Tar Implementation For .NET』のテスト


posted by lightbox at 2013-09-15 19:45 | VS(C#) | このブログの読者になる | 更新情報をチェックする

2013年09月14日


Android をテストするのにほんの少し楽になるかもしれないクラス



例えばここでテストしたいのは、Twitter の投稿なのですが、そのたびに一からイベントやらキャストやらファイル読み書きとか面倒なので作りました。
2013-09-12 : 初回投稿
2013-09-14 : ダイアログ処理とラベル(TextView)処理を追加しました
メソッドの引数でクラスのオブジェクトが必要なところで new と 入力して CTRL+SPACE で Eclipse が匿名のインナー型の候補を出してくれる事を期待しています。
util.buttonClick(R.id.button1, new OnClickListener() {
			
	@Override
	public void onClick(View v) {
		// TODO 自動生成されたメソッド・スタブ
				
	}
});
util. と 最後のセミコロンを除いて、殆ど Eclipse が候補を出してくれます。 Util.java
package com.example.textfile;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Calendar;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.content.DialogInterface;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class Util {
	
	public Activity cur = null;
	public final Calendar c = Calendar.getInstance();
	public final int year = c.get(Calendar.YEAR);
	public final int month = c.get(Calendar.MONTH);
	public final int day = c.get(Calendar.DAY_OF_MONTH);

	public Util(Activity ma) {
		cur = ma;
	}
	
	// ******************************************
	// その他
	// ******************************************
	public void toast(String message) {
        Toast.makeText(cur, message, Toast.LENGTH_LONG).show();    	
	}
	
	// ******************************************
	// 入力
	// ******************************************
	public String getFieldStr(int id) {
		
		return ((EditText)cur.findViewById(id)).getText().toString();
		
	}
	public void setFieldStr(int id,String text) {
		
		((EditText)cur.findViewById(id)).setText(text);
		
	}

	// ******************************************
	// ラベル
	// ******************************************
	public String getViewStr(int id) {
		
		return ((TextView)cur.findViewById(id)).getText().toString();
		
	}
	public void setViewStr(int id,String text) {
		
		((TextView)cur.findViewById(id)).setText(text);
		
	}
	
	// ******************************************
	// ボタン
	// ******************************************
	public Button getButton(int id) {

		return (Button) cur.findViewById(id);

	}
	public void buttonClick(int id,OnClickListener I) {

		((Button) cur.findViewById(id)).setOnClickListener(I);

	}
	
	// ******************************************
	// テキストファイル
	// ******************************************
	public void saveText( String name, String text) throws Exception  {
        
		FileOutputStream outStream = cur.openFileOutput(name, android.content.Context.MODE_PRIVATE);
        OutputStreamWriter writer = new OutputStreamWriter(outStream);
		writer.write(text);
        writer.flush();
        writer.close();
		
	}
	public String getText( String name ) throws Exception {
		
        FileInputStream fis = cur.openFileInput(name);
        int size = fis.available();
        InputStreamReader isr = new InputStreamReader( fis );
        BufferedReader br = new BufferedReader(isr);
        StringBuffer all_string = new StringBuffer( size ); 
        String str;
        while((str = br.readLine()) != null){
        	all_string.append(str);
        }
        br.close();
        
        return all_string.toString();
		
	}
	
	// ******************************************
	// ダイアログ
	// ******************************************
	public DatePickerDialog dateDialog(OnDateSetListener listener) {
	
			return new DatePickerDialog(cur,listener,year,month,day);
			
	}
	
	public AlertDialog messageBox(String title,String message,DialogInterface.OnClickListener onClickListener1,DialogInterface.OnClickListener onClickListener2) {

		AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(cur);
		alertDialogBuilder.setTitle(title);
		alertDialogBuilder.setMessage(message);
		
		alertDialogBuilder.setPositiveButton("YES",onClickListener1);
		alertDialogBuilder.setNegativeButton("NO", onClickListener2);
		alertDialogBuilder.setCancelable(true);

		return alertDialogBuilder.create();
		
	}

}


MainActivity.java
package com.example.textfile;

import com.example.textfile.Android_Twitter.Tweeted;

import android.os.Bundle;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.content.DialogInterface;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.DatePicker;

public class MainActivity extends Activity {

	private Util util = new Util( this );
	
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // ボタンイベント
        util.buttonClick(R.id.button1,new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				
				// Twitter 投稿
				new Android_Twitter(
					"",
					"",
					"",
					"").Tweet(
							util.getFieldStr(R.id.editText1), new Tweeted() {
			
					// 投稿結果
					@Override
					public void onTweetResult(String result) {
						try {
							// 内部ストレージへのファイル保存
							util.saveText("json.txt", result);
						}
						catch( Exception ex ) {
							ex.printStackTrace();
						}
					}
		        });    	

				// メッセージ
				util.toast("投稿しました!!");
				
			}
		});

        // 初期処理として、内部ストレージから文字列を取得
        try{
            util.setFieldStr(R.id.editText1, util.getText("file1.txt"));
        }
        catch(Exception ex){
			ex.printStackTrace();
        }
        
        // ボタンイベント
        util.buttonClick(R.id.button2, new OnClickListener() {
			
			@Override
			public void onClick(View v) {

				// 日付ダイアログ
				util.dateDialog(new OnDateSetListener() {
					
					@Override
					public void onDateSet(DatePicker view, int year, int monthOfYear,
							int dayOfMonth) {

						// 結果を表示
						util.setViewStr(R.id.textView1, year + "/" + (monthOfYear+1)+"/"+dayOfMonth);
						
					}
				}).show();	// 表示
				
			}
		});

        // ホダンイベント
        util.buttonClick(R.id.button3, new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				
				// 選択肢応答ダイアログ
				util.messageBox("メッセージボックス", "Yes または No による選択処理",
						// YES の処理
						new DialogInterface.OnClickListener() {
					
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								System.out.println("YES");
								
							}
							
						},
						// NO の処理
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								System.out.println("NO");
								
							}
						}
				).show();	// 表示
			}
		});
    }

    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
    
}



posted by lightbox at 2013-09-14 16:33 | Android | このブログの読者になる | 更新情報をチェックする

2013年09月12日


Framework4.5(C#) のコンソールアプリケーションで、とても簡単に HTTP サーバーを作成できます

SkyDrive へ移動

※ VS2012 用

スレッドを使ってサーバー部分を常駐しますので、プログラムにはコンソールとブラウザと両方からコマンドを送る事になります。

Framework4.5 になって、非同期処理がイベントを作成せずに行単位で処理が継続できるようになったので、コードが簡潔に書けるようになりました。( この処理の場合非同期で行う必要は無いと思いますが )

ブラウザは、IE を使って行うといいと思います。設定で『ウェブサイトを表示するたびに確認する』としておけば、キャッシュによるトラブルも避けられます。

そもそもの目的は、Windows8 ストアアプリよりデータベースアクセスをする為のサーバーとしての利用なので、データベースアクセス用の簡単なテンプレートを用意しています。実際は、Json.NET を使って http で結果を返すつもりにしています。
using System;
using System.Collections.Generic;
using System.Data.Odbc;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace CHttpServer1
{
	public class Program
	{
		// 引数
		public static string[] args;
		// DB接続文字列
		static string cs = "Driver={MySQL ODBC 5.2 Unicode Driver};" +
			"Server=localhost;" +
			"Database=lightbox;" +
			"Uid=root;" + 
			"Pwd=パスワード;";

		static void Main(string[] args)
		{
			App app = new App();

			// イベントの追加
			app.OpenDb += open;

			// ラムダ式による実装
			app.Select += (string cmd) =>
			{
				Console.WriteLine(cmd + " が実行されました");

				// select の結果を表示する
			};

			// スレッドイベントを登録
			app.ThreadServer += MyThread;

			// ******************************************
			// 終了せずに、コマンドプロンプトを保持する。
			// ( "q" で終了 )
			// ******************************************
			app.Loop();

		}

		// ******************************************
		// データーベースを開くイベント
		// ******************************************
		static private void open(string cmd )
		{
			Console.WriteLine(cmd + " が実行されました");

			using (OdbcConnection cn = new OdbcConnection(Program.cs))
			{
				try
				{
					cn.Open();
				}
				catch (Exception ex)
				{
					Console.WriteLine(ex.Message);
				}
				Console.WriteLine("State={0}", cn.State);
			}
			Console.WriteLine("処理が終了しました");
		}

		// ******************************************
		// http サーバーとしてのイベント( スレッド )
		// ******************************************
		static private async void MyThread()
		{
			Console.WriteLine("スレッドが開始されました");

			// HTTP プロトコル用リスナー
			TcpListener tl = new TcpListener(System.Net.IPAddress.Any, 8080);
			tl.Start();

			TcpClient tc = null;
			NetworkStream stream = null;
			StreamReader reader = null;
			StreamWriter writer = null;
			string line = null;
			string lineall = null;
			bool DataAvailable = true;

			while (true)
			{
				if (DataAvailable)
				{
					Console.WriteLine("受信を待機しています.....");
				}
				// HTTP の受信待ち
				tc = tl.AcceptTcpClient();

				// 以下は、受信した場合に処理されます
				// データの入り口 ( NetworkStream )
				stream = tc.GetStream();

				Thread.Sleep(500);

				// ストリームを読み込むオブジェクトを取得
				reader = new StreamReader(stream);
				// 実際にデータを読み込んで処理したかどうか
				DataAvailable = false;
				// 一回の受信で朱徳した全文字列
				lineall = "";

				// 実際の全てのデータ取得
				if (stream.DataAvailable)
				{
					// 非同期で一行取得
					while (true)
					{
						line = await reader.ReadLineAsync();
						// 空でチェックするしかないようです。
						if (line == "")
						{
							break;
						}
						lineall += line + "\n";
					}

					DataAvailable = true;
				}

				// http の返信用の書き込みオブジェクトを SHIFT_JIS で作成
				writer = new StreamWriter(stream, Encoding.GetEncoding("shift_jis"));

				// HTTP プロトコルに従って、ヘッダと本文を返す
				writer.WriteLine("HTTP/1.1 200 OK");
				writer.WriteLine("Content-Type:text/plain; charset=Shift_JIS");
				int length = (Encoding.GetEncoding("shift_jis")).GetByteCount(lineall);
				writer.WriteLine("Content-Length: " + length);

				writer.WriteLine();
				writer.WriteLine(lineall);

				// オブジェクトを閉じる
				writer.Close();
				reader.Close();
				stream.Close();

				if (lineall == "")
				{
					// Console.WriteLine("データがありません");
					continue;
				}
				Console.WriteLine(lineall);

				// アドレスバーで、http://localhost:8080/q と入力した場合はスレッドを終了
				if ( (lineall+"       ").Substring(0, 7) == "GET /q ")
				{
					tl.Stop();
					break;
				}
			}

			Console.WriteLine("スレッドが終了しました");
		}
	
	}
}

Framework 4.0 でも、static private async void MyThread() の async を削除して、line = await sr.ReadLineAsync(); を line = sr.ReadLine(); にすればビルドできます。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace CHttpServer1
{
	class App
	{
		public delegate void AppHandler( string cmd );
		public event AppHandler OpenDb = null;
		public event AppHandler Select = null;
		public delegate void ThreadHandler();
		public event ThreadStart ThreadServer = null;

		// ******************************************
		// コンストラクタ
		// ******************************************
		public App()
		{
		}

		// ******************************************
		// 終了せずに、コマンドプロンプトを保持する。
		// ******************************************
		public void Loop()
		{

			while (true)
			{
				// 専用プロンプト
				Console.Write("app>");
				string line = Console.ReadLine();

				// 終了コマンド
				if (line == "q")
				{
					break;
				}

				// スレッドを開始
				if (line == "server")
				{
					if (ThreadServer != null)
					{
						Thread ts = new Thread(ThreadServer);
						ts.Start();
					}

				}

				// DBを開く
				if (line == "open")
				{
					if (OpenDb != null)
					{
						OpenDb(line);
					}
				}

				// select 実行の表示
				if (line == "select")
				{
					if (Select != null)
					{
						Select(line);
					}
				}

			}
		}
	}
}

関連する記事コンソールアプリケーション(C#) で、クラス、デリゲート、イベント、ラムダ式の振舞いを理解するVB.net : クライアントが送ったヘッダを表示するだけの HTTPサーバーUHTTP コマンド・リスナー :【VB.NET】



posted by lightbox at 2013-09-12 16:10 | VS(C#) | このブログの読者になる | 更新情報をチェックする

2013年09月08日


初心者用ファイルアップロード用テンプレート( 含 HTML5 の multiple="true" )



PHP を使用してファイルをアップロードする標準的な方法に加えて、HTML5 の input 要素で multiple="true"(要するに、ファイル選択ダイアログでファイルを複数選択が可能になります) を指定したサンプルです

Google Chrome



Firefox



IE10


<?
header( "Content-Type: text/html; Charset=utf-8" );
header( "pragma: no-cache" );
header( "Expires: Wed, 31 May 2000 14:59:58 GMT" );
header( "Cache-control: no-cache" );

foreach( $_POST as $Key => $Value ) {
	$_POST[$Key] = str_replace("\\\\", "\\", $Value );
	$_POST[$Key] = str_replace("\\'", "'", $_POST[$Key] );
	$_POST[$Key] = str_replace("\\\"", "\"", $_POST[$Key] );
}

require_once("html_head.php");

print "<pre>";
print_r( $_FILES );
print "</pre>";

$target = $_FILES['file_1']['name'];

$upload = "./upload_file/";
$upload .= $target;
print $upload . "<br>";

if ( move_uploaded_file( $_FILES['file_1']['tmp_name'], $upload ) ) {
	print "アップロードに成功しました\n";
}
else {
	print "アップロードに失敗しました\n";
}

?>

更新履歴
2011-05-22 : 初回投稿
2013-09-08 : IE10 でテスト( 表示等を少し変更 )



タグ:HTML5
posted by lightbox at 2013-09-08 22:03 | PHP + ベーシック | このブログの読者になる | 更新情報をチェックする
Seesaa の各ページの表示について
Seesaa の 記事がたまに全く表示されない場合があります。その場合は、設定> 詳細設定> ブログ設定 で 最新の情報に更新の『実行ボタン』で記事やアーカイブが最新にビルドされます。

Seesaa のページで、アーカイブとタグページは要注意です。タグページはコンテンツが全く無い状態になりますし、アーカイブページも歯抜けページはコンテンツが存在しないのにページが表示されてしまいます。

また、カテゴリページもそういう意味では完全ではありません。『カテゴリID-番号』というフォーマットで表示されるページですが、実際存在するより大きな番号でも表示されてしまいます。

※ インデックスページのみ、実際の記事数を超えたページを指定しても最後のページが表示されるようです

対処としては、このようなヘルプ的な情報を固定でページの最後に表示するようにするといいでしょう。具体的には、メインの記事コンテンツの下に『自由形式』を追加し、アーカイブとカテゴリページでのみ表示するように設定し、コンテンツを用意するといいと思います。


※ エキスパートモードで表示しています

アーカイブとカテゴリページはこのように簡単に設定できますが、タグページは HTML 設定を直接変更して、以下の『タグページでのみ表示される内容』の記述方法で設定する必要があります

<% if:page_name eq 'archive' -%>
アーカイブページでのみ表示される内容
<% /if %>

<% if:page_name eq 'category' -%>
カテゴリページでのみ表示される内容
<% /if %>

<% if:page_name eq 'tag' -%>
タグページでのみ表示される内容
<% /if %>
この記述は、以下の場所で使用します
container 終わり



フリーフォントで簡単ロゴ作成
フリーフォントでボタン素材作成
フリーフォントで吹き出し画像作成
フリーフォントではんこ画像作成
ほぼ自由に利用できるフリーフォント
フリーフォントの書体見本とサンプル
画像を大きく見る為のウインドウを開くボタンの作成

CSS ドロップシャドウの参考デモ
イラストAC
ぱくたそ
写真素材 足成
フリーフォント一覧
utf8 文字ツール
右サイド 終わり
base 終わり