關閉
標題:include.cs 最新
內容:
using System;
using System.Reflection;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Web;
using System.Data.SqlClient;
using System.Data;
using System.Web.Util;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Net;
using System.Web.Services;
using System.Web.Script.Serialization;
using System.Configuration;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using System.Globalization;
using Newtonsoft.Json.Linq;
using System.Text.RegularExpressions;
using System.Threading;
using System.Diagnostics;
//using System.Reflection;
/*
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="webservice.aspx.cs" Inherits="WaterRegion.Search.webservice.webservice" %>
<%@ Import Namespace="System.Collections.Generic" %>
<%@ Import Namespace="utility" %>
<%@ Import Namespace="Newtonsoft.Json" %>
<%@ import Namespace="Newtonsoft.Json.Linq" %>
<%@ Import Namespace="System.Linq" %>
*/
namespace utility
{
public class myinclude : System.Web.Services.WebService
{
private string connString = null;
private SqlConnection conn = null;
public bool isLinkToDB()
{
return (conn != null);
}
public bool linkToDB()
{
try
{
if (!isLinkToDB())
{
connString = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
connString = System.Configuration.ConfigurationManager.AppSettings["ConnectionString"];
connString = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
conn = new SqlConnection(connString);
conn.Open();
}
}
catch (Exception ex)
{
Console.Write(ex.Message);
return false;
}
return true;
}
public int rand(int min, int max)
{
Random rnd = new Random();
return rnd.Next(min, max);
}
public string pwd()
{
return AppDomain.CurrentDomain.BaseDirectory; //dirname(System.Web.HttpContext.Current.Request.PhysicalPath);
}
public bool is_dir(string path)
{
return Directory.Exists(path);
}
public bool is_file(string filepath)
{
return File.Exists(filepath);
}
public void myLog(String data)
{
string path = getSystemKey("LOG_PATH");
if (!is_dir(path))
{
mkdir(path);
}
string filename = String.Format("{0}.txt", date("Y-m-d"));
string fn = String.Format("{0}\\{1}", path, filename);
if (!is_file(fn))
{
touch(fn);
}
file_append_contents(fn, string.Format("\r\n\r\n{0} -\r\n{1}", date("Y-m-d H:i:s"), data));
}
public void touch(string fileName)
{
FileStream myFileStream = File.Open(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
myFileStream.Close();
myFileStream.Dispose();
File.SetLastWriteTimeUtc(fileName, DateTime.UtcNow);
}
public void file_append_contents(string filename, string data)
{
StreamWriter w = File.AppendText(filename);
w.Write(data);
w.Close();
}
public string get_between(string data, string s_begin, string s_end)
{
//http://stackoverflow.com/questions/378415/how-do-i-extract-a-string-of-text-that-lies-between-two-parenthesis-using-net
//string a = "abcdefg";
//MessageBox.Show(my.get_between(a, "cde", "g"));
//return f;
string s = data;
int start = s.IndexOf(s_begin);
if (start < 0)
{
return "";
}
string new_s = data.Substring(start + s_begin.Length);
int end = new_s.IndexOf(s_end);
if (end < 0)
{
return "";
}
return s.Substring(start + s_begin.Length, end);
}
public long find_string_appear_in_a_string_counts(string data, string find_string)
{
//尋找一個字出現了幾次
return Regex.Matches(data, find_string).Count;
}
public bool is_string_like(string data, string find_string)
{
return (data.IndexOf(find_string) == -1) ? false : true;
}
public bool is_istring_like(string data, string find_string)
{
return (data.ToUpper().IndexOf(find_string.ToUpper()) == -1) ? false : true;
}
public void include(string filename)
{
echo(b2s(file_get_contents(filename)));
}
public string getSystemKey(string keyindex)
{
return ConfigurationManager.AppSettings[keyindex];
}
public bool IsValidEmailAddress(string s)
{
if (string.IsNullOrEmpty(s))
return false;
else
{
var regex = new Regex(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*");
return regex.IsMatch(s) && !s.EndsWith(".");
}
}
public String FilterMetaCharacters(String s)
{
if (string.IsNullOrEmpty(s))
{
return "";
}
else
{
Regex re = new Regex("([^A-Za-z0-9@.' _-]+)");
String filtered = re.Replace(s, "_");
return filtered;
}
}
//大小寫
public string strtoupper(string input)
{
return input.ToUpper();
}
public string strtolower(string input)
{
return input.ToLower();
}
public string UTF8toBig5(string strInput)
{
byte[] strut8 = System.Text.Encoding.Unicode.GetBytes(strInput);
byte[] strbig5 = System.Text.Encoding.Convert(System.Text.Encoding.Unicode, System.Text.Encoding.Default, strut8);
return System.Text.Encoding.Default.GetString(strbig5);
}
string BIG5toUTF8(string strUtf)
{
Encoding utf81 = Encoding.GetEncoding("utf-8");
Encoding big51 = Encoding.GetEncoding("big5");
System.Web.HttpContext.Current.Response.ContentEncoding = utf81;
byte[] strBig51 = big51.GetBytes(strUtf.Trim());
byte[] strUtf81 = Encoding.Convert(big51, utf81, strBig51);
char[] utf8Chars1 = new char[utf81.GetCharCount(strUtf81, 0, strUtf81.Length)];
utf81.GetChars(strUtf81, 0, strUtf81.Length, utf8Chars1, 0);
string tempString1 = new string(utf8Chars1);
return tempString1;
}
public string dePWD_string(string input, string thekey)
{
input = b2s(base64_decode(input));
thekey = base64_encode(s2b(thekey));
string xored = "";
char[] input_arr = input.ToCharArray();
char[] thekey_arr = thekey.ToCharArray();
foreach (char ich in input_arr)
{
int a = (int)ich;
for (int j = thekey_arr.Length - 1; j >= 0; j--)
{
int k = (int)thekey_arr[j];
a = a ^ k;
}
xored = string.Format("{0}{1}", xored, Convert.ToChar(a));
}
xored = b2s(base64_decode(xored));
return xored;
}
public string urlencode(string value)
{
return Server.UrlEncode(value);
}
public string urldecode(string value)
{
return Server.UrlDecode(value);
}
public string addslashes(string value)
{
return value.Replace("'", "\'").Replace("\"", "\\\"");
}
public string stripslashes(string value)
{
return value.Replace("\\'", "'").Replace("\\\"", "\"");
}
public void alert(string value)
{
value = jsAddSlashes(value);
echo("<script language='javascript'>alert('" + value + "');</script>");
}
public void alert(int value)
{
alert(value.ToString());
}
public void alert(double value)
{
alert(value.ToString());
}
public void echo(double value)
{
echo(value.ToString());
}
public void echo(long value)
{
echo(value.ToString());
}
public void echo(int value)
{
echo(value.ToString());
}
public void echo(byte[] value)
{
echo(value.ToString());
}
public void echo(string value)
{
//System.Web.HttpContext.Current.Response.Write(value);
HttpContext.Current.Response.Write(value);
}
public void echoBinary(byte[] value)
{
HttpContext.Current.Response.BinaryWrite(value);
}
public void downloadHeader(string filename)
{
//HttpContext.Current.Response.Headers.Clear();
HttpContext.Current.Response.AppendHeader("ContentType", "application/octet-stream");
HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=\"" + filename + "\"");
}
public void allowAjaxHeader()
{
HttpContext.Current.Response.AppendHeader("Access-Control-Allow-Origin", "*");
HttpContext.Current.Response.AppendHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
{
//These headers are handling the "pre-flight" OPTIONS call sent by the browser
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
HttpContext.Current.Response.End();
}
}
public void setOutputHeader(string data)
{
// text/xml
// text/plain
// ...
HttpContext.Current.Response.AppendHeader("Content-Type", data);
}
//取得使用者IP
public string ip()
{
string ip = "";
if (System.Web.HttpContext.Current.Request.ServerVariables["HTTP_VIA"] != null)
{
if (System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] == null)
{
if (System.Web.HttpContext.Current.Request.ServerVariables["HTTP_CLIENT_IP"] != null)
{
ip = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_CLIENT_IP"].ToString();
}
else
{
if (System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"] != null)
{
ip = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"].ToString();
}
}
}
else
{
ip = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
}
}
else if (System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"] != null)
{
ip = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"].ToString();
}
return ip;
}
//UnixTimeToDateTime
public DateTime UnixTimeToDateTime(string text)
{
System.DateTime dateTime = new System.DateTime(1970, 1, 1, 0, 0, 0, 0);
// Add the number of seconds in UNIX timestamp to be converted.
dateTime = dateTime.AddSeconds(Convert.ToDouble(text));
return dateTime;
}
//仿php的date
public string time()
{
return strtotime(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
}
public string date()
{
return date("Y-m-d H:i:s", strtotime(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffffff")));
}
public string date(string format)
{
return date(format, strtotime(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffffff")));
}
public string date(string format, string unixtimestamp)
{
DateTime tmp = UnixTimeToDateTime(unixtimestamp);
tmp = tmp.AddHours(+8);
switch (format)
{
case "Y-m-d H:i:s":
return tmp.ToString("yyyy-MM-dd HH:mm:ss");
case "Y/m/d":
return tmp.ToString("yyyy/MM/dd");
case "Y/m/d H:i:s":
return tmp.ToString("yyyy/MM/dd HH:mm:ss");
case "Y/m/d H:i:s.fff":
return tmp.ToString("yyyy/MM/dd HH:mm:ss.fff");
case "Y-m-d_H_i_s":
return tmp.ToString("yyyy-MM-dd_HH_mm_ss");
case "Y-m-d":
return tmp.ToString("yyyy-MM-dd");
case "H:i:s":
return tmp.ToString("HH:mm:ss");
case "Y-m-d H:i":
return tmp.ToString("yyyy-MM-dd HH:mm");
case "Y_m_d_H_i_s":
return tmp.ToString("yyyy_MM_dd_HH_mm_ss");
case "Y_m_d_H_i_s_fff":
return tmp.ToString("yyyy_MM_dd_HH_mm_ss_fff");
case "w":
//回傳week, sun =0 , sat = 6, mon=1.....
return Convert.ToInt16(tmp.DayOfWeek).ToString();
case "Y":
return tmp.ToString("yyyy");
case "m":
return tmp.ToString("MM");
case "d":
return tmp.ToString("dd");
case "H":
return tmp.ToString("HH");
case "i":
return tmp.ToString("mm");
case "s":
return tmp.ToString("ss");
case "Y-m-d H:i:s.fff":
return tmp.ToString("yyyy-MM-dd HH:mm:ss.fff");
case "Y-m-d H:i:s.ffffff":
return tmp.ToString("yyyy-MM-dd HH:mm:ss.ffffff");
case "H:i:s.fff":
return tmp.ToString("HH:mm:ss.fff");
case "H:i:s.ffffff":
return tmp.ToString("HH:mm:ss.ffffff");
}
return "";
}
//strtotime 轉換成 Unix time
public string strtotime(string value)
{
//create Timespan by subtracting the value provided from
//the Unix Epoch
TimeSpan span = (Convert.ToDateTime(value) - new DateTime(1970, 1, 1, 0, 0, 0, 0).ToLocalTime());
//return the total seconds (which is a UNIX timestamp)
if (is_string_like(value, "."))
{
//有小數點
double sec = span.Ticks / (TimeSpan.TicksPerMillisecond / 1000.0) / 1000000.0;
return sec.ToString();
}
else
{
return span.TotalSeconds.ToString();
}
}
public string strtotime(DateTime value)
{
//create Timespan by subtracting the value provided from
//the Unix Epoch
TimeSpan span = (value - new DateTime(1970, 1, 1, 0, 0, 0, 0).ToLocalTime());
//return the total seconds (which is a UNIX timestamp)
return span.TotalSeconds.ToString();
}
//javascript用的吐js資料
public string jsAddSlashes(string value)
{
value = value.Replace("\\", "\\\\");
value = value.Replace("\n", "\\n");
value = value.Replace("\r", "\\r");
value = value.Replace("\"", "\\\"");
value = value.Replace("&", "\\x26");
value = value.Replace("<", "\\x3C");
value = value.Replace(">", "\\x3E");
return value;
}
public string print_r(object obj)
{
return print_r(obj, 0);
}
public string pre_print_r(object obj)
{
return "<pre>" + print_r(obj) + "</pre>";
}
public bool in_array(string find_key, List<string> arr)
{
return arr.Contains(find_key);
}
public bool in_array(string find_key, string[] arr)
{
return arr.Contains(find_key);
}
public bool in_array(string find_key, ArrayList arr)
{
return arr.Contains(find_key);
}
public bool is_numeric(object Expression)
{
if (Expression == null || Expression is DateTime)
return false;
if (Expression is Int16 || Expression is Int32 || Expression is Int64 || Expression is Decimal || Expression is Single || Expression is Double || Expression is Boolean)
return true;
try
{
if (Expression is string)
Double.Parse(Expression as string);
else
Double.Parse(Expression.ToString());
return true;
}
catch { } // just dismiss errors but return false
return false;
}
public string print_r(object obj, int recursion)
{
StringBuilder result = new StringBuilder();
// Protect the method against endless recursion
if (recursion < 5)
{
// Determine object type
Type t = obj.GetType();
// Get array with properties for this object
PropertyInfo[] properties = t.GetProperties();
foreach (PropertyInfo property in properties)
{
try
{
// Get the property value
object value = property.GetValue(obj, null);
// Create indenting string to put in front of properties of a deeper level
// We'll need this when we display the property name and value
string indent = String.Empty;
string spaces = "| ";
string trail = "|...";
if (recursion > 0)
{
indent = new StringBuilder(trail).Insert(0, spaces, recursion - 1).ToString();
}
if (value != null)
{
// If the value is a string, add quotation marks
string displayValue = value.ToString();
if (value is string) displayValue = String.Concat('"', displayValue, '"');
// Add property name and value to return string
result.AppendFormat("{0}{1} = {2}\n", indent, property.Name, displayValue);
try
{
if (!(value is ICollection))
{
// Call var_dump() again to list child properties
// This throws an exception if the current property value
// is of an unsupported type (eg. it has not properties)
result.Append(print_r(value, recursion + 1));
}
else
{
// 2009-07-29: added support for collections
// The value is a collection (eg. it's an arraylist or generic list)
// so loop through its elements and dump their properties
int elementCount = 0;
foreach (object element in ((ICollection)value))
{
string elementName = String.Format("{0}[{1}]", property.Name, elementCount);
indent = new StringBuilder(trail).Insert(0, spaces, recursion).ToString();
// Display the collection element name and type
result.AppendFormat("{0}{1} = {2}\n", indent, elementName, element.ToString());
// Display the child properties
result.Append(print_r(element, recursion + 2));
elementCount++;
}
result.Append(print_r(value, recursion + 1));
}
}
catch { }
}
else
{
// Add empty (null) property to return string
result.AppendFormat("{0}{1} = {2}\n", indent, property.Name, "null");
}
}
catch
{
// Some properties will throw an exception on property.GetValue()
// I don't know exactly why this happens, so for now i will ignore them...
}
}
}
return result.ToString();
}
public void execSQL(string SQL)
{
selectSQL(SQL);
}
/// <summary>
/// Will return the string contents of a
/// regular file or the contents of a
/// response from a URL
/// </summary>
/// <param name="fileName">The filename or URL</param>
/// <returns></returns>
public byte[] file_get_contents_retry(string url)
{
if (url.ToLower().IndexOf("http:") > -1 || url.ToLower().IndexOf("https:") > -1 )
{
// URL
ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
// URL
//http://social.msdn.microsoft.com/Forums/en-US/8050d80a-ca45-4b0c-82dc-81dd1eac496f/retry-catch
bool redo = false;
const int maxRetries = 10;
int retries = 0;
HttpWebRequest request = null;
HttpWebResponse response = null;
byte[] byteData = null;
do
{
try
{
request = (HttpWebRequest)WebRequest.Create(url);
request.Timeout = 30000;
request.Proxy = null;
request.UserAgent = "user_agent','Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.75 Safari/537.36";
//request.Referer = getSystemKey("HTTP_REFERER");
response = (HttpWebResponse)request.GetResponse();
Stream stream = response.GetResponseStream();
byteData = ReadStream(stream, 5000);
stream.Close();
}
catch (Exception e)
{
Console.Write(e.Message);
//Console.WriteLine(e.Message);
redo = true;
Thread.Sleep(5);
++retries;
//myLog("retry..." + retries);
}
} while (redo && retries < maxRetries);
response.Close();
return byteData;
}
else
{
System.IO.StreamReader sr = new System.IO.StreamReader(url);
string sContents = sr.ReadToEnd();
sr.Close();
return s2b(sContents);
}
}
public byte[] file_get_contents(string url)
{
if (url.ToLower().IndexOf("http:") > -1)
{
// URL
HttpWebRequest request = null;
HttpWebResponse response = null;
byte[] byteData = null;
request = (HttpWebRequest)WebRequest.Create(url);
request.Timeout = 60000;
request.Proxy = null;
request.UserAgent = "user_agent','Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.75 Safari/537.36";
//request.Referer = getSystemKey("HTTP_REFERER");
response = (HttpWebResponse)request.GetResponse();
Stream stream = response.GetResponseStream();
byteData = ReadStream(stream, 32765);
response.Close();
stream.Close();
return byteData;
}
else
{
/*System.IO.StreamReader sr = new System.IO.StreamReader(url);
string sContents = sr.ReadToEnd();
sr.Close();
return s2b(sContents);
*/
/*FileStream fs = new FileStream(url, FileMode.Open);
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
fs.Close();
return buffer;
*/
byte[] data;
using (StreamReader sr = new StreamReader(url))
{
using (MemoryStream ms = new MemoryStream())
{
sr.BaseStream.CopyTo(ms);
data = ms.ToArray();
ms.Close();
ms.Dispose();
}
sr.Close();
sr.Dispose();
};
}
}
private void ExecuteWithRetry(Action action)
{
// Use a maximum count, we don't want to loop forever
// Alternativly, you could use a time based limit (eg, try for up to 30 minutes)
const int maxRetries = 5;
bool done = false;
int attempts = 0;
while (!done)
{
attempts++;
try
{
action();
done = true;
}
catch (WebException ex)
{
if (!IsRetryable(ex))
{
throw;
}
if (attempts >= maxRetries)
{
throw;
}
// Back-off and retry a bit later, don't just repeatedly hammer the connection
Thread.Sleep(SleepTime(attempts));
}
}
}
private int SleepTime(int retryCount)
{
// I just made these times up, chose correct values depending on your needs.
// Progressivly increase the wait time as the number of attempts increase.
switch (retryCount)
{
case 0: return 0;
case 1: return 1000;
case 2: return 5000;
case 3: return 10000;
default: return 30000;
}
}
private bool IsRetryable(WebException ex)
{
return
ex.Status == WebExceptionStatus.ReceiveFailure ||
ex.Status == WebExceptionStatus.ConnectFailure ||
ex.Status == WebExceptionStatus.KeepAliveFailure;
}
public void file_put_contents(string filepath, string input)
{
file_put_contents(filepath, s2b(input));
}
public void file_put_contents(string filepath, byte[] input)
{
FileStream myFile = File.Open(@filepath, FileMode.Create);
myFile.Write(input, 0, input.Length);
myFile.Dispose();
}
public string b2s(byte[] input)
{
return System.Text.Encoding.UTF8.GetString(input);
}
public byte[] s2b(string input)
{
return System.Text.Encoding.UTF8.GetBytes(input);
}
private byte[] ReadStream(Stream stream, int initialLength)
{
if (initialLength < 1)
{
initialLength = 32768;
}
byte[] buffer = new byte[initialLength];
int read = 0;
int chunk;
while ((chunk = stream.Read(buffer, read, buffer.Length - read)) > 0)
{
read += chunk;
if (read == buffer.Length)
{
int nextByte = stream.ReadByte();
if (nextByte == -1)
{
return buffer;
}
byte[] newBuffer = new byte[buffer.Length * 2];
Array.Copy(buffer, newBuffer, buffer.Length);
newBuffer[read] = (byte)nextByte;
buffer = newBuffer;
read++;
}
}
byte[] bytes = new byte[read];
Array.Copy(buffer, bytes, read);
return bytes;
}
public string base64_encode(byte[] data)
{
//base64編碼
return Convert.ToBase64String(data);
}
public byte[] base64_decode(string data)
{
//base64解碼
return Convert.FromBase64String(data);
}
public string htmlspecialchars(string input)
{
return HttpContext.Current.Server.HtmlEncode(input);
}
public string htmlspecialchars_decode(string input)
{
return HttpContext.Current.Server.HtmlDecode(input);
}
public Dictionary<string, object> getGET_POST(string inputs, string method)
{
/*
string GETS_STRING="mode,id";
Dictionary<string, object> get = x.getGET_POST(GETS_STRING, "GET");
string vv=x.print_r(get,0);
foreach (string a in get.Keys)
{
Response.Write(a+":"+get[a]+"<br>");
}
sample:
string GETS_STRING="mode,id";
Dictionary<string, object> get = x.getGET_POST(GETS_STRING, "GET");
string POSTS_STRING ="abc,b,s_a,s_b[],ddd";
Dictionary<string, object> post = x.getGET_POST(POSTS_STRING, "POST");
string q = x.print_r(get, 0);
string p = x.print_r(post, 0);
Response.Write("<pre>" + q + "<br>" + p + "</pre>");
Response.Write("aaaaaaa->" + post["s_a"]+"<br>");
Response.Write("aaaaaab->" + post["s_b[]"] + "<br>");
*
*/
method = method.ToUpper();
Dictionary<string, object> get_post = new Dictionary<string, object>();
switch (method)
{
case "GET":
foreach (string k in inputs.Split(','))
{
if (this.Context.Request.QueryString[k] != null)
{
get_post[k] = addslashes(this.Context.Request.QueryString[k]);
}
else
{
get_post[k] = "";
}
}
break;
case "POST":
foreach (string k in inputs.Split(','))
{
if (this.Context.Request.Form[k] != null)
{
if (this.Context.Request.Form.GetValues(k).Length != 1)
{
//暫時先這樣,以後再修= =
//alert(this.Context.Request.Form.GetValues(k).Length.ToString());
get_post[k] = implode("┃", this.Context.Request.Form.GetValues(k));
}
else
{
get_post[k] = htmlspecialchars(addslashes(trim(this.Context.Request.Form[k])));
}
}
else
{
get_post[k] = "";
}
}
break;
}
return get_post;
}
public byte[] file_get_contents_post(string url, string postData)
{
HttpWebRequest httpWReq =
(HttpWebRequest)WebRequest.Create(url);
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] data = encoding.GetBytes(postData);
httpWReq.Method = "POST";
httpWReq.ContentType = "application/x-www-form-urlencoded";
httpWReq.UserAgent = "user_agent','Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.75 Safari/537.36";
httpWReq.Proxy = null;
httpWReq.Timeout = 60000;
httpWReq.Referer = HttpContext.Current.Request.ServerVariables["SERVER_NAME"];
//httpWReq.Referer = url;//getSystemKey("HTTP_REFERER");
httpWReq.ContentLength = data.Length;
using (Stream stream = httpWReq.GetRequestStream())
{
stream.Write(data, 0, data.Length);
stream.Close();
}
HttpWebResponse response = (HttpWebResponse)httpWReq.GetResponse();
Stream streamD = response.GetResponseStream();
byte[] byteData = ReadStream(streamD, 32767);
response.Close();
streamD.Close();
return byteData;
//byte[] responseString = new StreamReader(response.GetResponseStream()).ToArray();
}
public byte[] WMS_file_get_contents(string url)
{
if (url.ToLower().IndexOf("http:") > -1)
{
// URL
System.Net.WebRequest.DefaultWebProxy = null;
HttpWebRequest hwr = (HttpWebRequest)(WebRequest.Create(url));
hwr.Method = "GET";
hwr.Timeout = 50000;
hwr.Proxy = null;
HttpWebResponse hwro = (HttpWebResponse)(hwr.GetResponse());
System.Web.HttpContext.Current.Response.ContentType = hwro.ContentType;
using (var memoryStream = new MemoryStream())
{
byte[] buffer = new byte[16 * 1024]; // Fairly arbitrary size
int bytesRead;
while ((bytesRead = hwro.GetResponseStream().Read(buffer, 0, buffer.Length)) > 0)
{
memoryStream.Write(buffer, 0, bytesRead);
}
hwro.Close();
return memoryStream.ToArray();
}
}
else
{
System.IO.StreamReader sr = new System.IO.StreamReader(url);
string sContents = sr.ReadToEnd();
sr.Close();
return s2b(sContents);
}
}
public long insertSQL(string table, Dictionary<string, string> datas, bool isNeedLastID = false)
{
string SQL = "";
string[] field = new string[datas.Keys.Count];
string[] data = new string[datas.Keys.Count];
string[] question_marks = new string[datas.Keys.Count];
int i = 0;
foreach (string k in datas.Keys)
{
field[i] = k;
data[i] = datas[k].ToString();
question_marks[i] = "@" + k;
i++;
}
SQL = string.Format(@"
INSERT INTO {0}({1})VALUES({2});",
table,
implode(",", field),
implode(",", question_marks));
SqlCommand cmd = new SqlCommand(SQL, conn);
List<SqlParameter> param_now = new List<SqlParameter>();
param_now.Clear();
for (i = 0; i < data.Length; i++)
{
cmd.Parameters.AddWithValue(question_marks[i], data[i]);
}
cmd.ExecuteNonQuery();
if (isNeedLastID)
{
Dictionary<int, Dictionary<string, string>> ro = selectSQL("SELECT @@IDENTITY AS LastID");
int last_id = Convert.ToInt32(ro[0]["LastID"]);
return last_id;
}
else
{
return -1;
}
}
public void updateSQL(string table, Dictionary<string, string> datas, string WHERESQL)
{
string SQL = "";
string[] SQL_DATA = new string[datas.Keys.Count];
string[] field = new string[datas.Keys.Count];
string[] data = new string[datas.Keys.Count];
string[] question_marks = new string[datas.Keys.Count];
int i = 0;
foreach (string k in datas.Keys)
{
field[i] = k;
data[i] = datas[k].ToString();
question_marks[i] = "@" + k;
SQL_DATA[i] = String.Format(@" ""{0}"" = {1} ", field[i], question_marks[i]);
i++;
}
SQL = string.Format(@"
UPDATE ""{0}"" SET {1} WHERE {2} ;",
table,
implode(",", SQL_DATA),
WHERESQL);
SqlCommand cmd = new SqlCommand(SQL, conn);
List<SqlParameter> param_now = new List<SqlParameter>();
param_now.Clear();
for (i = 0; i < data.Length; i++)
{
cmd.Parameters.AddWithValue(question_marks[i], data[i]);
}
cmd.ExecuteNonQuery();
}
public Dictionary<int, Dictionary<string, string>> selectSQL(string select_query_cmd)
{
//SqlConnection conn = new SqlConnection(connString);
//conn.Open();
SqlCommand cmd = new SqlCommand(select_query_cmd, conn);
SqlDataReader dr = cmd.ExecuteReader();
int i = 0;
Dictionary<int, Dictionary<string, string>> datas = new Dictionary<int, Dictionary<string, string>>();
while (dr.Read())
{
Dictionary<string, string> data_list = new Dictionary<string, string>();
for (int j = 0; j < dr.FieldCount; j++)
{
data_list[dr.GetName(j)] = dr[dr.GetName(j)].ToString();
}
datas[i] = new Dictionary<string, string>(data_list);
i++;
}
dr.Close();
return datas;
}
public void db_close()
{
if (conn != null)
{
conn.Close();
conn = null;
}
}
public Dictionary<string, string> convert_dictionary(Dictionary<string, object> input)
{
Dictionary<string, string> tmp = new Dictionary<string, string>();
foreach (string k in input.Keys)
{
tmp[k] = input[k].ToString();
}
return tmp;
}
public string implode(string keyword, string[] arrays)
{
return string.Join(keyword, arrays);
}
public string implode(string keyword, List<string> arrays)
{
return string.Join<string>(keyword, arrays);
}
public string implode(string keyword, Dictionary<int, string> arrays)
{
string[] tmp = new String[arrays.Keys.Count];
int i = 0;
foreach (int k in arrays.Keys)
{
tmp[i++] = arrays[k];
}
return string.Join(keyword, tmp);
}
public string implode(string keyword, Dictionary<string, string> arrays)
{
string[] tmp = new String[arrays.Keys.Count];
int i = 0;
foreach (string k in arrays.Keys)
{
tmp[i++] = arrays[k];
}
return string.Join(keyword, tmp);
}
public string implode(string keyword, ArrayList arrays)
{
string[] tmp = new String[arrays.Count];
for (int i = 0; i < arrays.Count; i++)
{
tmp[i] = arrays[i].ToString();
}
return string.Join(keyword, tmp);
}
public string[] explode(string keyword, string data)
{
return data.Split(new string[] { keyword }, StringSplitOptions.None);
}
public string[] explode(string keyword, object data)
{
return data.ToString().Split(new string[] { keyword }, StringSplitOptions.None);
}
public string[] explode(string[] keyword, string data)
{
return data.Split(keyword, StringSplitOptions.None);
}
public string selectarray2table(Dictionary<int, Dictionary<string, string>> data, string style)
{
//將SELECT 出來的內容吐出table畫面
string tmp = "";
style = style.ToLower();
switch (style)
{
case "dot":
if (data.Count != 0)
{
foreach (string k in data[0].Keys)
{
tmp += k;
tmp += ",";
}
tmp = tmp.Substring(0, tmp.Length - 1);
tmp += "\n";
for (int i = 0; i < data.Count; i++)
{
tmp += implode(",", data[i]);
if (i != data.Count - 1)
{
tmp += "\n";
}
}
}
break;
case "normal":
if (data.Count != 0)
{
tmp += "<table>";
tmp += "<tr>";
tmp += "<th>";
string tmp_add = " </th><th>";
foreach (string k in data[0].Keys)
{
tmp += k;
tmp += tmp_add;
}
tmp = tmp.Substring(0, tmp.Length - tmp_add.Length - 1);
tmp += " </th></tr>";
for (int i = 0; i < data.Count; i++)
{
tmp += "<tr><td>";
tmp += implode(" </td><td>", data[i]);
tmp += " </td></tr>";
}
tmp += "</table>";
}
break;
case "normal_center":
if (data.Count != 0)
{
tmp += "<table>";
tmp += "<tr>";
tmp += "<th>";
string tmp_add = " </th><th align=\"center\">";
foreach (string k in data[0].Keys)
{
tmp += k;
tmp += tmp_add;
}
tmp = tmp.Substring(0, tmp.Length - tmp_add.Length - 1);
tmp += " </th></tr>";
for (int i = 0; i < data.Count; i++)
{
tmp += "<tr><td align=\"center\">";
tmp += implode(" </td><td align=\"center\">", data[i]);
tmp += " </td></tr>";
}
tmp += "</table>";
}
break;
case "normal_center_style":
if (data.Count != 0)
{
tmp += "<table cellpadding=\"5\" cellspacing=\"0\" class=\"table_3wa\">";
tmp += "<tr>";
tmp += "<th>";
string tmp_add = " </th><th align=\"center\">";
foreach (string k in data[0].Keys)
{
tmp += k;
tmp += tmp_add;
}
tmp = tmp.Substring(0, tmp.Length - tmp_add.Length - 1);
tmp += " </th></tr>";
for (int i = 0; i < data.Count; i++)
{
tmp += "<tr><td align=\"center\">";
tmp += implode(" </td><td>", data[i]);
tmp += " </td></tr>";
}
tmp += "</table>";
}
break;
}
return tmp;
}
public void location_href(string value)
{
echo("<script language='javascript'>location.href=\"" + value + "\";</script>");
}
public void location_replace(string value)
{
echo("<script language='javascript'>location.replace(\"" + value + "\");</script>");
}
public void history_go()
{
echo("<script language='javascript'>history.go(-1);</script>");
}
public void history_back()
{
echo("<script language='javascript'>history.back();</script>");
}
public void exit()
{
System.Web.HttpContext.Current.Response.Flush(); //強制輸出緩衝區資料
System.Web.HttpContext.Current.Response.Clear(); //清除緩衝區的資料
System.Web.HttpContext.Current.Response.End(); //結束資料輸出
//System.Web.HttpContext.Current.Response.StatusCode = 200;
}
public string EscapeUnicode(string input)
{
StringBuilder sb = new StringBuilder(input.Length);
foreach (char ch in input)
{
if (ch <= 0x7f)
sb.Append(ch);
else
sb.AppendFormat(CultureInfo.InvariantCulture, "\\u{0:x4}", (int)ch);
}
return sb.ToString();
}
public string unEscapeUnicode(string input)
{
return Regex.Unescape(input);
}
public string json_encode(object input)
{
return EscapeUnicode(JsonConvert.SerializeObject(input, Formatting.None));
}
public string json_format(string input)
{
JArray jdod = json_decode(input);
return EscapeUnicode(JsonConvert.SerializeObject(jdod, Formatting.Indented));
}
public string json_format_utf8(string input)
{
JArray jdod = json_decode(input);
return JsonConvert.SerializeObject(jdod, Formatting.Indented);
}
public string trim(string input)
{
return input.Trim();
}
public Dictionary<string, object> json_decode_output_dictionary(string input)
{
return jobjToDictionary(json_decode(input));
}
public Dictionary<string, object> jobjToDictionary(JToken obj, string name = null)
{
name = name ?? "obj";
if (obj is JObject)
{
var asBag =
from prop in (obj as JObject).Properties()
let propName = prop.Name
let propValue = prop.Value is JValue
? new Dictionary<string, object>()
{
{prop.Name, prop.Value}
}
: jobjToDictionary(prop.Name)
select new KeyValuePair<string, object>(propName, propValue);
return asBag.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
}
if (obj is JArray)
{
var vals = (obj as JArray).Values();
var alldicts = vals
.SelectMany(val => jobjToDictionary(name))
.Select(x => x.Value)
.ToArray();
return new Dictionary<string, object>()
{
{name, (object)alldicts}
};
}
if (obj is JValue)
{
return new Dictionary<string, object>()
{
{name, (obj as JValue)}
};
}
return new Dictionary<string, object>()
{
{name, null}
};
}
public JArray json_decode(string input)
{
input = trim(input);
if (input.Length != 0)
{
if (input.Substring(1, 1) != "[")
{
input = "[" + input + "]";
return (JArray)JsonConvert.DeserializeObject<JArray>(input);
}
else
{
return (JArray)JsonConvert.DeserializeObject<JArray>(input);
}
}
else
{
return null;
}
}
public string nl2br(string input)
{
return input.Replace("\n", "<br />");
}
public List<string> natsort(List<string> data)
{
//自然排序法
return natsort(data.ToArray()).ToList();
}
public string[] natsort(string[] data)
{
//自然排序法
Func<string, object> convert = str =>
{
try { return int.Parse(str); }
catch { return str; }
};
var sorted = data.OrderBy(
str => Regex.Split(str.Replace(" ", ""), "([0-9]+)").Select(convert),
new EnumerableComparer<object>()).OrderBy(
x => x.Length
);
return sorted.ToArray();
}
public string firstWordUpper(string data)
{
//首字大寫
data = strtolower(data);
if (data.Length > 0)
{
data = data.Substring(0, 1).ToUpper() + data.Substring(1, data.Length - 1);
}
return data;
}
public string basename(string path)
{
return Path.GetFileName(path);
}
public string mainname(string path)
{
return Path.GetFileNameWithoutExtension(path);
}
public string subname(string path)
{
return Path.GetExtension(path).TrimStart('.');
}
public long getfilesize(string path)
{
FileInfo f = new FileInfo(path);
return f.Length;
}
public string size_hum_read(long bytes)
{
string[] Suffix = { "B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB" };
int i = 0;
double dblSByte = Convert.ToDouble(bytes);
if (bytes > 1024)
for (i = 0; (bytes / 1024) > 0; i++, bytes /= 1024)
dblSByte = bytes / 1024.0;
return String.Format("{0:0.##} {1}", dblSByte, Suffix[i]);
}
public string[] glob(string path)
{
//string[] test = my.glob("c:\\tmp");
//my.echo(my.pre_print_r(test));
return Directory.GetFiles(path);
}
public string[] glob(string path, string patten)
{
//string[] test = my.glob("c:\\tmp");
//my.echo(my.pre_print_r(test));
return Directory.GetFiles(path, patten);
}
public void mkdir(string path)
{
Directory.CreateDirectory(path);
}
public void copy(string sourceFile, string destFile)
{
System.IO.File.Copy(sourceFile, destFile, true);
}
public string dirname(string path)
{
return Directory.GetParent(path).FullName;
}
public string basedir()
{
//取得專案的起始位置
return System.Web.HttpContext.Current.Request.PhysicalApplicationPath;
}
/// <summary>
/// 利用外部指令,將 SHP 轉換坐標系統
/// </summary>
/// <param name="shp_source">來源 SHP 完整路徑</param>
public bool shx_generator(string shp_source)
{
try
{
string SHX_FIXER = string.Format(@"{0}\\lib\\shpfile_fixer\\shapechk.exe", basedir());
string SHP_TMP_DIR = string.Format(@"{0}\\{1}", getSystemKey("SHP_TMP_DIR"), date("Y-m-d"));
string WORK_DISK = explode(":", SHP_TMP_DIR)[0];
string cmd = string.Format(@"{0}: && cd {1} && {2} {3} /auto ",
WORK_DISK,
SHP_TMP_DIR,
SHX_FIXER, shp_source
);
system(cmd);
if (File.Exists(string.Format(@"{0}\\{1}.shx", SHP_TMP_DIR, mainname(shp_source))))
{
return true;
}
else
{
return false;
}
}
catch (Exception ex)
{
Console.Write(ex.Message);
return false;
}
}
/// <summary>
/// 利用外部指令,將 SHP 轉換坐標系統
/// </summary>
/// <param name="shp_source">來源 SHP 完整路徑</param>
/// <param name="shp_output">目地 SHP 完整路徑</param>
/// <param name="s_srs">來源 SHP 坐標系統</param>
/// <param name="t_srs">目地 SHP 坐標系統</param>
/// <returns>true or false</returns>
public bool shp_projection_change(string shp_source, string shp_output, string s_srs, string t_srs)
{
try
{
string SHP_TMP_DIR = string.Format(@"{0}\\{1}", getSystemKey("SHP_TMP_DIR"), date("Y-m-d"));
string WORK_DISK = explode(":", SHP_TMP_DIR)[0];
string OGR2OGR_PATH = string.Format(@"{0}\\lib\\GDAL\\ogr2ogr.exe", basedir());
string cmd = string.Format(@"{0}: && cd {1} && {2} -s_srs ""{3}"" -t_srs ""{4}"" ""{5}"" ""{6}"" ",
WORK_DISK,
SHP_TMP_DIR,
OGR2OGR_PATH, s_srs, t_srs, shp_output, shp_source
);
system(cmd);
if (File.Exists(string.Format(@"{0}\\{1}", SHP_TMP_DIR, shp_output)))
{
return true;
}
else
{
return false;
}
}
catch (Exception ex)
{
Console.Write(ex.Message);
return false;
}
}
/// <summary>
/// 利用外部指令,將 SHP 轉成 JSON
/// </summary>
/// <param name="shp_source">來源 SHP 完整路徑</param>
/// <param name="json_output">目地 JSON 完整路徑</param>
/// <returns>true or false</returns>
public bool shp_to_json(string shp_source, string json_output)
{
try
{
string SHP_TMP_DIR = string.Format(@"{0}\\{1}", getSystemKey("SHP_TMP_DIR"), date("Y-m-d"));
string WORK_DISK = explode(":", SHP_TMP_DIR)[0];
string GDAL_PATH = string.Format(@"{0}\\lib\\GDAL\\ogr2ogr.exe", basedir());
string cmd = string.Format(@"{0}: && cd {1} && {2} -f GeoJSON ""{3}"" ""{4}"" ",
WORK_DISK,
SHP_TMP_DIR,
GDAL_PATH, json_output, shp_source);
//file_put_contents("c:\\LOGS\\NGIS\\a.txt", cmd);
system(cmd);
if (File.Exists(string.Format(@"{0}\\{1}", SHP_TMP_DIR, json_output)))
{
return true;
}
else
{
return false;
}
}
catch (Exception ex)
{
Console.Write(ex.Message);
//file_put_contents("c:\\LOGS\\NGIS\\b.txt", cmd+"\n"+ex.Message);
return false;
}
}
public string system(string command)
{
StringBuilder sb = new StringBuilder();
string version = System.Environment.OSVersion.VersionString;//读取操作系统版本
if (version.Contains("Windows"))
{
using (Process p = new Process())
{
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.UseShellExecute = false;//是否指定操作系统外壳进程启动程序
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.CreateNoWindow = true;//不显示dos命令行窗口
p.Start();//启动cmd.exe
p.StandardInput.WriteLine(command);//输入命令
p.StandardInput.WriteLine("exit");//退出cmd.exe
p.WaitForExit();//等待执行完了,退出cmd.exe
using (StreamReader reader = p.StandardOutput)//截取输出流
{
string line = reader.ReadLine();//每次读取一行
while (!reader.EndOfStream)
{
sb.Append(line).Append("<br />");//在Web中使用<br />换行
line = reader.ReadLine();
}
p.WaitForExit();//等待程序执行完退出进程
p.Close();//关闭进程
reader.Close();//关闭流
}
}
}
return sb.ToString();
}
/// <summary>
/// 儲存 NGIS_LOG 機制
/// </summary>
/// <param name="API_METHOD">Log 類型</param>
/// <param name="USER_IP">使用者IP</param>
/// <param name="DATETIME">觸發時間</param>
/// <param name="GET_REQUEST">傳入的GET參數(JSON)</param>
/// <param name="POST_REQUEST">傳入的POST參數(JSON)</param>
/// <returns>true or false</returns>
public long NGIS_LOG(string API_METHOD, string USER_IP, string DATETIME, string GET_REQUEST, string POST_REQUEST)
{
linkToDB();
Dictionary<string, string> m = new Dictionary<string, string>();
m["API_METHOD"] = API_METHOD;
m["USER_IP"] = USER_IP;
m["DATETIME"] = DATETIME;
//這二個傳值,用JSON吧
m["GET_REQUEST"] = GET_REQUEST;
m["POST_REQUEST"] = POST_REQUEST;
return insertSQL("NGIS_LOG", m, true);
}
/// <summary>
/// 儲存 Log 細節機制
/// </summary>
/// <param name="NGIS_LOG_ID">NGIS_LOG 對照ID</param>
/// <param name="TITLE">標題</param>
/// <param name="CONTENT">內容</param>
/// <param name="STIME">開始時間</param>
/// <param name="ETIME">結束時間</param>
/// <param name="SIZE">WFS回傳的大小,可有可無</param>
/// <returns>true or false</returns>
public long NGIS_LOG_DETAIL(string NGIS_LOG_ID, string CODE, string TITLE, string CONTENT, string STIME, string ETIME, string SIZE = null)
{
linkToDB();
Dictionary<string, string> m = new Dictionary<string, string>();
m["NGIS_LOG_METADATA_CODE"] = CODE;
m["NGIS_LOG_ID"] = NGIS_LOG_ID;
m["TITLE"] = TITLE;
m["CONTENT"] = CONTENT;
if (STIME != "" && STIME != null)
{
m["STIME"] = STIME;
}
if (ETIME != "" && ETIME != null)
{
m["ETIME"] = ETIME;
}
if (SIZE != "" && SIZE != null)
{
m["SIZE"] = SIZE;
}
return insertSQL("NGIS_LOG_DETAIL", m, true);
}
public string microtime()
{
System.DateTime dt = DateTime.Now;
System.DateTime UnixEpoch = new System.DateTime(1970, 1, 1, 0, 0, 0, 0);
TimeSpan span = dt - UnixEpoch;
long microseconds = span.Ticks / (TimeSpan.TicksPerMillisecond / 1000);
return microseconds.ToString();
}
}
/// <summary>
/// Compares two sequences.
/// </summary>
/// <typeparam name="T">Type of item in the sequences.</typeparam>
/// <remarks>
/// Compares elements from the two input sequences in turn. If we
/// run out of list before finding unequal elements, then the shorter
/// list is deemed to be the lesser list.
/// </remarks>
public class EnumerableComparer<T> : IComparer<IEnumerable<T>>
{
/// <summary>
/// Create a sequence comparer using the default comparer for T.
/// </summary>
public EnumerableComparer()
{
comp = Comparer<T>.Default;
}
/// <summary>
/// Create a sequence comparer, using the specified item comparer
/// for T.
/// </summary>
/// <param name="comparer">Comparer for comparing each pair of
/// items from the sequences.</param>
public EnumerableComparer(IComparer<T> comparer)
{
comp = comparer;
}
/// <summary>
/// Object used for comparing each element.
/// </summary>
private IComparer<T> comp;
/// <summary>
/// Compare two sequences of T.
/// </summary>
/// <param name="x">First sequence.</param>
/// <param name="y">Second sequence.</param>
public int Compare(IEnumerable<T> x, IEnumerable<T> y)
{
using (IEnumerator<T> leftIt = x.GetEnumerator())
using (IEnumerator<T> rightIt = y.GetEnumerator())
{
while (true)
{
bool left = leftIt.MoveNext();
bool right = rightIt.MoveNext();
if (!(left || right)) return 0;
if (!left) return -1;
if (!right) return 1;
int itemResult = comp.Compare(leftIt.Current, rightIt.Current);
if (itemResult != 0) return itemResult;
}
}
}
}
}