Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save iseebi/411424 to your computer and use it in GitHub Desktop.
Save iseebi/411424 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Text;
using EbiSoft.Imadoko.Plugins;
using System.Net;
using System.IO;
using System.Xml.Serialization;
namespace EbiSoft.Imadoko.FormData
{
[Plugin("汎用フォームデータ送信", "1.1")]
public class FormDataPlugin : PluginBase
{
private readonly string ConfigPath;
/// <summary>
/// コンストラクタ
/// </summary>
public FormDataPlugin()
{
ConfigPath = Path.Combine(EbiSoft.Imadoko.ImadokoUtility.ApplicationPath, "EbiSoft.Imadoko.FormData.xml");
LoadSetting();
}
#region 設定
private FormDataPluginSetting m_setting;
/// <summary>
/// ローカル設定
/// </summary>
internal FormDataPluginSetting LocalSetting
{
get { return m_setting; }
}
/// <summary>
/// 設定の読み込み
/// </summary>
internal void LoadSetting()
{
if (File.Exists(ConfigPath))
{
try
{
XmlSerializer serializer = new XmlSerializer(typeof(FormDataPluginSetting));
using (FileStream stream = new FileStream(ConfigPath, FileMode.Open, FileAccess.Read))
{
m_setting = (FormDataPluginSetting)serializer.Deserialize(stream);
}
}
catch (Exception)
{
m_setting = new FormDataPluginSetting();
}
}
else
{
m_setting = new FormDataPluginSetting();
}
if (m_setting.Profiles.Count == 0)
{
m_setting.Profiles.Add(new FormDataProfile("デフォルト"));
m_setting.ActiveProfileIndex = 0;
}
}
/// <summary>
/// 設定の保存
/// </summary>
internal void SaveSetting()
{
XmlSerializer serializer = new XmlSerializer(typeof(FormDataPluginSetting));
using (FileStream stream = new FileStream(ConfigPath, FileMode.Create, FileAccess.Write))
{
serializer.Serialize(stream, m_setting);
}
}
/// <summary>
/// アクティブなプロファイル
/// </summary>
public FormDataProfile ActiveProfile
{
get
{
if (LocalSetting.Profiles.Count > LocalSetting.ActiveProfileIndex)
{
return LocalSetting.Profiles[LocalSetting.ActiveProfileIndex];
}
else
{
return null;
}
}
}
#endregion
private string CreateUrl(string url, string latitude, string longitude)
{
url = url.Replace("%LAT%", latitude);
url = url.Replace("%LON%", latitude);
url = url.Replace("%POS%", EbiSoft.Imadoko.ImadokoUtility.FormatPosString(latitude, longitude));
return url;
}
public override UploadResult PostPicture(string filePath, string comment, string latitude, string longitude, bool[] additionalSwitch)
{
// プロファイル読み込み
FormDataProfile prof = ActiveProfile;
if (prof == null) return new UploadResult(false, "プロファイルなし。");
// URL作成
string url = CreateUrl(prof.PhotoUrl, latitude, longitude);
// リクエスト初期設定
Encoding encord = prof.GetEncoding();
string boundary = System.Environment.TickCount.ToString();
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.AllowAutoRedirect = true;
req.AllowWriteStreamBuffering = true;
if (prof.PhotoValues.Count > 0)
{
req.Method = "POST";
req.ContentType = "multipart/form-data; boundary=" + boundary;
// データ作成
string postData = string.Empty;
string CRLF = "\r\n";
FormValueEntry imageEntry = null;
foreach (FormValueEntry entry in prof.PhotoValues)
{
if (entry.Value == "%PHOTO%")
{
imageEntry = entry;
}
else
{
string val = entry.Value;
switch (val)
{
case "%LAT%": val = latitude; break;
case "%LON%": val = longitude; break;
case "%COM%": val = comment; break;
case "%POS%": val = ImadokoUtility.FormatPosString(latitude, longitude); break;
default: break;
}
postData += "--" + boundary + CRLF;
postData += "Content-Disposition: form-data; name=\"" + entry.Name + "\"" + CRLF + CRLF;
postData += val + CRLF;
}
}
if (imageEntry != null)
{
postData += "--" + boundary + CRLF;
postData += "Content-Disposition: form-data; name=\"" + imageEntry.Name + "\"; filename=\"imadokonavi.jpg\"" + CRLF;
postData += "Content-Type: image/jpeg" + CRLF;
postData += "Content-Transfer-Encoding: binary" + CRLF + CRLF;
byte[] startData = encord.GetBytes(postData);
postData = CRLF + "--" + boundary + CRLF;
byte[] endData = encord.GetBytes(postData);
//送信するファイルを開く
System.IO.FileStream fs = new System.IO.FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read);
req.ContentLength = startData.Length + endData.Length + fs.Length;
req.MaximumAutomaticRedirections = 3;
req.AllowWriteStreamBuffering = true;
req.PreAuthenticate = true;
//データをPOST送信するためのStreamを取得、送信するデータを書き込む
System.IO.Stream reqStream = req.GetRequestStream();
reqStream.Write(startData, 0, startData.Length);
byte[] readData = new byte[0x1000];
int readSize = 0;
while (true)
{
readSize = fs.Read(readData, 0, readData.Length);
if (readSize == 0)
break;
reqStream.Write(readData, 0, readSize);
}
fs.Close();
reqStream.Write(endData, 0, endData.Length);
reqStream.Close();
}
else
{
postData += CRLF + "--" + boundary + CRLF;
byte[] startData = encord.GetBytes(postData);
//データをPOST送信するためのStreamを取得、送信するデータを書き込む
System.IO.Stream reqStream = req.GetRequestStream();
reqStream.Write(startData, 0, startData.Length);
reqStream.Close();
}
}
else
{
req.Method = "GET";
}
//サーバーからの応答を受信するためのWebResponseを取得
HttpWebResponse res = (HttpWebResponse)req.GetResponse();
if (res.StatusCode == HttpStatusCode.Found)
{
string redirectDoc = string.Format("<html><head><meta http-equiv=\"Refresh\" content=\"0; URL={0}\"></head><body><a href=\"{0}\">リダイレクトしない場合</a></body></html>", res.Headers["Location"]);
return new UploadResult(true, redirectDoc);
}
else
{
//応答データを受信するためのStreamを取得
Stream resStream = res.GetResponseStream();
//受信して表示
StreamReader sr = new StreamReader(resStream, Encoding.GetEncoding("shift_jis"));
string document = sr.ReadToEnd();
//閉じる
sr.Close();
return new UploadResult(true, document);
}
}
public override UploadResult PostLocation(string latitude, string longitude)
{
// プロファイル読み込み
FormDataProfile prof = ActiveProfile;
if (prof == null) return new UploadResult(false, "プロファイルなし。");
// URL作成
string url = CreateUrl(prof.LocationUrl, latitude, longitude);
// リクエスト初期設定
Encoding encord = prof.GetEncoding();
string boundary = System.Environment.TickCount.ToString();
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.AllowAutoRedirect = true;
req.AllowWriteStreamBuffering = true;
if (prof.LocationValues.Count > 0)
{
req.Method = "POST";
req.ContentType = "multipart/form-data; boundary=" + boundary;
// データ作成
string postData = string.Empty;
string CRLF = "\r\n";
foreach (FormValueEntry entry in prof.LocationValues)
{
string val = entry.Value;
switch (val)
{
case "%LAT%": val = latitude; break;
case "%LON%": val = longitude; break;
case "%COM%": continue;
case "%POS%": val = ImadokoUtility.FormatPosString(latitude, longitude); break;
default: break;
}
postData += "--" + boundary + CRLF;
postData += "Content-Disposition: form-data; name=\"" + entry.Name + "\"" + CRLF + CRLF;
postData += val + CRLF;
}
postData += CRLF + "--" + boundary + CRLF;
byte[] startData = encord.GetBytes(postData);
//データをPOST送信するためのStreamを取得、送信するデータを書き込む
System.IO.Stream reqStream = req.GetRequestStream();
reqStream.Write(startData, 0, startData.Length);
reqStream.Close();
}
else
{
req.Method = "GET";
}
//サーバーからの応答を受信するためのWebResponseを取得
HttpWebResponse res = (HttpWebResponse)req.GetResponse();
if (res.StatusCode == HttpStatusCode.Found)
{
string redirectDoc = string.Format("<html><head><meta http-equiv=\"Refresh\" content=\"0; URL={0}\"></head><body><a href=\"{0}\">リダイレクトしない場合</a></body></html>", res.Headers["Location"]);
return new UploadResult(true, redirectDoc);
}
else
{
//応答データを受信するためのStreamを取得
Stream resStream = res.GetResponseStream();
//受信して表示
StreamReader sr = new StreamReader(resStream, Encoding.GetEncoding("shift_jis"));
string document = sr.ReadToEnd();
//閉じる
sr.Close();
return new UploadResult(true, document);
}
}
/// <summary>
/// 設定画面の生成
/// </summary>
/// <returns></returns>
protected override PluginSettingControl CreateSettingControlInstance()
{
return new FormDataSettingControl();
}
public override Uri TargetUri
{
get { return new Uri("http://www.google.com/"); }
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment