void CleanUp() { myappconfig = null; frmCrosshair?.Close(); frmCrosshair?.Dispose(); frmCrosshair = null; streamImg?.Close(); streamImg?.Dispose(); streamImg = null; }
public void CloseStream() { mStream?.Close(); mStream = null; }
public void Unload() { _stream?.Dispose(); _stream?.Close(); _stream = null; }
/// <summary> /// Run reports is used for scheduled reports. /// </summary> /// <param name="reportModel"></param> /// <param name="userId"></param> /// <returns></returns> public static FileHelper Run(ReportModel reportModel, string userId) { string URL = reportServerPathRunner + reportModel.SSRSReportName.Replace(".rdl", ""); string Command = "Render"; string Query = ""; FileHelper file = new FileHelper((!string.IsNullOrWhiteSpace(reportModel.FileName) ? reportModel.FileName : reportModel.SSRSReportName.Replace(".rdl", "")), userId); //Replace filename parameters. foreach (ReportParameterModel reportParameter in reportModel.ReportParameters) { //Setup the query if (!string.IsNullOrWhiteSpace(reportParameter.DefaultValue)) { Query += $"&{reportParameter.Name}={reportParameter.DefaultValue}"; } //Replace any parameter in the name. if (file.FileName.Contains("{" + reportParameter.Name + "}")) { string defaultValue = reportParameter.DefaultValue; //If the parameter is a date make sure we format it so its fiel friendly. if (!string.IsNullOrWhiteSpace(reportParameter.DataType) && reportParameter.DataType.Equals(ReportParameterModel.dateTimeType)) { DateTime dateTimeValue; DateTime.TryParse(reportParameter.DefaultValue, out dateTimeValue); defaultValue = (dateTimeValue != null ? dateTimeValue.ToString("yyyyMMdd") : ""); } file.FileName = file.FileName.Replace("{" + reportParameter.Name + "}", defaultValue); } } file.FileName = Regex.Replace(file.FileName, "-{2,}", "-"); file.FileName = file.FileName + "." + ReportModel.Extensions[reportModel.Format]; //Delete existing file if (file.Delete()) { URL = URL + "&rs:Command=" + Command + "&rs:Format=" + reportModel.Format + Query; System.Net.HttpWebRequest Req = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(URL); NetworkCredential credential = new NetworkCredential(userName, password, domain); Req.Credentials = credential; Req.Method = "GET"; //Specify the path for saving. //Do File Service here and return FileService fileService = new FileService(); //file.FilePathAndName = string.Format("{0}{1}{2}", file.FilePath, file.FileName, @".pdf"); System.Net.WebResponse objResponse = Req.GetResponse(); System.IO.FileStream fs = new System.IO.FileStream(file.FilePathAndName, System.IO.FileMode.Create); System.IO.Stream stream = objResponse.GetResponseStream(); byte[] buf = new byte[1024]; int len = stream.Read(buf, 0, 1024); while (len > 0) { fs.Write(buf, 0, len); len = stream.Read(buf, 0, 1024); } stream.Close(); fs.Close(); BaseModelContext <ReportUserActivityLogModel> reportUserActivityLogDb = new BaseModelContext <ReportUserActivityLogModel>(); ReportUserActivityLogModel reportUserActivityModel = new ReportUserActivityLogModel() { ReportId = reportModel.Id, UserId = userId, Activity = ReportUserActivityLogModel.RunActivity, Parameters = Query }; reportUserActivityLogDb.Models.Add(reportUserActivityModel); reportUserActivityLogDb.SaveChanges(userId); BaseModelContext <ReportModel> reportDb = new BaseModelContext <ReportModel>(); reportModel.LastRun = DateTime.Now; reportDb.Entry(reportModel); reportDb.SaveChanges(userId); } return(file); }
public override void Close() { in_Renamed.Close(); }
/// <summary> /// 访问URL地址,获得页面内容 /// add by guoxu 2012-05-29 /// </summary> /// <param name="url"></param> /// <param name="postDataStr"></param> /// <param name="Encod"></param> /// <returns></returns> public static string getUrlbody(string url, string postDataStr, Encoding Encod) { string rStr = ""; System.Net.WebRequest req = null; System.Net.WebResponse resp = null; System.IO.Stream os = null; System.IO.StreamReader sr = null; try { //创建连接 req = System.Net.WebRequest.Create(url); //设置访问方式和发送的请求数据的内容类型 if (string.IsNullOrEmpty(postDataStr)) { req.ContentType = "application/x-www-form-urlencoded"; req.Method = "GET"; } else { req.ContentType = "application/x-www-form-urlencoded"; req.Method = "POST"; if (Encod == null) { Encod = System.Text.Encoding.Default; } byte[] bytes = Encod.GetBytes(postDataStr); req.ContentLength = bytes.Length; os = req.GetRequestStream(); os.Write(bytes, 0, bytes.Length); os.Close(); } //读取返回结果 resp = req.GetResponse(); sr = new System.IO.StreamReader(resp.GetResponseStream(), Encod); rStr = sr.ReadToEnd(); } catch (Exception ex1) { } finally { try { //关闭资源 if (os != null) { os.Dispose(); os.Close(); } if (sr != null) { sr.Dispose(); sr.Close(); } if (resp != null) { resp.Close(); } if (req != null) { req = null; } } catch (Exception ex2) { } } return(rStr); }
//Send data to server in background via HTTP //void sendDataBackground(object sender, EventArgs e) void sendDataBackground(string serverURL, string data, string apiKey) { List <TagCollection> tagPingsRemove = new List <TagCollection>(); StringBuilder postData = new StringBuilder(); postData.Append("{\"value\":" + data + "}"); /* * //Go through all tags in the list * int tagno = 0; * foreach (TagCollection tagCollectionItem in tagPings) * { * * //Check if the tag was last seen over 1.5 second ago * DateTime firstSeenCheck = tagCollectionItem.firstSeen.AddSeconds(1.5); * * //If tag was last seen over limit * if (firstSeenCheck.Ticks < DateTime.UtcNow.Ticks) * { * * //Console.WriteLine(tagCollectionItem.firstSeen); * * //Add tag to post data * postData.Append("tags[" + tagno.ToString() + "][addr]=" + System.Uri.EscapeDataString(tagCollectionItem.tagAddr) + "&"); * postData.Append("tags[" + tagno.ToString() + "][firstseen]=" + System.Uri.EscapeDataString(firstSeenCheck.ToString("yyyy-MM-dd HH:mm:ss")) + "&"); * //http://msdn.microsoft.com/en-us/library/system.globalization.datetimeformatinfo(VS.71).aspx * * //Go through each reader / signal and adding it to the post data array * int readerno = 0; * foreach (TagReaderCollection reader in tagCollectionItem.readers) * { * postData.Append("tags[" + tagno.ToString() + "][readers][" + readerno.ToString() + "][addr]=" + System.Uri.EscapeDataString(reader.readerAddr) + "&"); * postData.Append("tags[" + tagno.ToString() + "][readers][" + readerno.ToString() + "][signal]=" + System.Uri.EscapeDataString(reader.signal.ToString()) + "&"); * readerno++; * } * * //Increment post data tag no counter * tagno++; * * //Add tag to the remove list * tagPingsRemove.Add(tagCollectionItem); * * } * * } * * //Go through all tags in the remove (just processed) list * foreach (TagCollection tagCollectionItem in tagPingsRemove) * { * //Remove tag * tagPings.Remove(tagCollectionItem); * } */ //If there is post data available if (postData.Length > 0) { //If there is a server specified if (serverURL != "") { //Send data via HTTP post to server //Console.WriteLine(postData.ToString()); //http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.aspx const int bufSizeMax = 65536; const int bufSizeMin = 8192; StringBuilder sb; // A WebException is thrown if HTTP request fails try { //bgWorker.ReportProgress(0, "Posting data to server"); //Convert post data to bytes byte[] bytes = Encoding.ASCII.GetBytes(postData.ToString()); // Create an HttpWebRequest using WebRequest.Create (see .NET docs)! HttpWebRequest request = (HttpWebRequest)WebRequest.Create(serverURL); request.Method = "post"; request.Headers.Add("U-ApiKey: " + apiKey); request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = bytes.Length; request.Timeout = 1000 * 5; //Send post data System.IO.Stream sendStream = request.GetRequestStream(); sendStream.Write(bytes, 0, bytes.Length); sendStream.Close(); // Execute the request and obtain the response stream HttpWebResponse response = (HttpWebResponse)request.GetResponse(); System.IO.Stream responseStream = response.GetResponseStream(); //Responses longer than int size will throw an exception here int length = (int)response.ContentLength; //Use Content-Length if between bufSizeMax and bufSizeMin int bufSize = bufSizeMin; if (length > bufSize) { bufSize = length > bufSizeMax ? bufSizeMax : length; } // Allocate buffer and StringBuilder for reading response byte[] buf = new byte[bufSize]; sb = new StringBuilder(bufSize); // Read response stream until end while ((length = responseStream.Read(buf, 0, buf.Length)) != 0) { sb.Append(Encoding.UTF8.GetString(buf, 0, length)); } //Check the http status code if (response.StatusCode == HttpStatusCode.OK) { //bgWorker.ReportProgress(0, "Posted data to server OK."); bgWorker.ReportProgress(0, "数据已上传至服务器, 收到响应: " + sb.ToString() + "\n\n"); } else { bgWorker.ReportProgress(0, "数据上传错误: 服务器响应HTTP Status Code " + response.StatusCode.ToString()); bgWorker.ReportProgress(0, "HTTP数据: " + sb.ToString() + "\n\n"); } } catch (Exception ex) { bgWorker.ReportProgress(0, "数据上传错误: " + ex.Message); } } } }
private void bOpenFileDialog_Click(object sender, RoutedEventArgs e) { // Create an instance of the open file dialog box. OpenFileDialog openFileDialog1 = new OpenFileDialog(); // Set filter options and filter index. openFileDialog1.Filter = "Binary Files (.bin)|*.bin|All Files (*.*)|*.*"; openFileDialog1.FilterIndex = 1; openFileDialog1.Multiselect = false; // Call the ShowDialog method to show the dialog box. bool?userClickedOK = openFileDialog1.ShowDialog(); // Process input if the user clicked OK. if (userClickedOK == true) { SendEvent("TryFile", openFileDialog1.File.Name); var ext = openFileDialog1.File.Extension.ToLower(); if (ext == ".dmg") { MessageBox.Show("Please open the DMG file and select the .BIN file inside"); return; } if (ext == ".exe") { MessageBox.Show("Please open the .EXE file and select the .BIN file inside"); return; } if (ext != ".bin") { MessageBox.Show("The files to be a Nikon Firmware .BIN file"); return; } Clear(); // Open the selected file to read. System.IO.Stream fileStream = openFileDialog1.File.OpenRead(); SendEvent("OpenFile", openFileDialog1.File.Name); if (fileStream.Length > (48 * 1024 * 1024)) { fileStream.Close(); return; } byte[] data = new byte[fileStream.Length]; if (data == null) { fileStream.Close(); return; } fileStream.Read(data, 0, (int)fileStream.Length); fileStream.Close(); // Test in valid firm = PatchControl.FirmwareMatch(data, App.AllowedPatchLevel); if (firm != null) { tFirmwareName.Text = firm.Model; tFirmwareVersion.Text = firm.Version; firm.ModelVersion = string.Format("{0}_{1}", firm.Model, firm.Version); if (firm.Patches.Count == 0) { tFeature.Text = "No Patches presently exist for this 'Model/Firmware Version'"; } else { var text = firm.TestPatch(); if (text == "") { lstFeatures.ItemsSource = firm.Patches; PatchSet.SetListBox(lstFeatures); tFeature.Text = ""; } else { // hash matched, but patches did not match tFeature.Text = "A sub-patch failed to map to this 'Model/Firmware Version' - Please Report " + text; } } foreach (var p in firm.Patches) { p.PropertyChanged += PatchSetChanged; } } else { tFeature.Text = "No matching 'Model/Firmware Versions' were found"; } } }
private void Login(System.Net.IWebProxy proxy) { if (cookie == null) { //获取SessionId和post_key System.Net.HttpWebRequest req = (System.Net.HttpWebRequest)System.Net.WebRequest.Create("https://accounts.pixiv.net/login?lang=zh&source=pc&view_type=page&ref=wwwtop_accounts_index"); var rsp = (System.Net.HttpWebResponse)req.GetResponse(); var cookieContainer = new System.Net.CookieContainer(); cookieContainer.SetCookies(rsp.ResponseUri, rsp.Headers["Set-Cookie"]); //这里是失败的尝试……跳过就好 /* * //cookieContainer.Add(phpsessidCookie); * //cookieContainer.Add(p_ab_idCookie); * cookie = rsp.Headers.Get("Set-Cookie"); * if (cookie == null) * { * throw new Exception("获取初始PHPSESSID失败"); * } * //Set-Cookie: PHPSESSID=3af0737dc5d8a27f5504a7b8fe427286; expires=Tue, 15-May-2012 10:05:39 GMT; path=/; domain=.pixiv.net * int sessionIndex = cookie.LastIndexOf("PHPSESSID"); * string phpsessid = cookie.Substring(sessionIndex + 10, cookie.IndexOf(';', sessionIndex + 10) - sessionIndex - 9); * int p_ab_idIndex = cookie.LastIndexOf("p_ab_id"); * string p_ab_id = cookie.Substring(p_ab_idIndex + 8, cookie.IndexOf(';', p_ab_idIndex + 8) - p_ab_idIndex - 8); * rsp.Close(); * var phpsessidCookie = new System.Net.Cookie("p_ab_id", p_ab_id); * var p_ab_idCookie = new System.Net.Cookie("PHPSESSID", phpsessid); */ var loginPageStream = rsp.GetResponseStream(); System.IO.StreamReader streamReader = new System.IO.StreamReader(loginPageStream); string loginPageString = streamReader.ReadToEnd(); streamReader.Dispose(); loginPageStream.Dispose(); rsp.Close(); HtmlDocument loginPage = new HtmlDocument(); loginPage.LoadHtml(loginPageString); HtmlNode postKeyNode = loginPage.DocumentNode.SelectSingleNode("//input[@name='post_key']"); string postKey = postKeyNode.Attributes.Where(p => p.Name == "value").Select(p => p.Value).ToList()[0]; //模拟登陆 req = (System.Net.HttpWebRequest)System.Net.WebRequest.Create("https://accounts.pixiv.net/api/login?lang=zh"); req.UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)"; req.Proxy = proxy; req.Timeout = 8000; req.Method = "POST"; //prevent 302 req.AllowAutoRedirect = false; //user & pass int index = rand.Next(0, user.Length); string data = "captcha=&g_recaptcha_response=&pixiv_id=" + user[index] + "&password="******"&source=pc" + "&post_key=" + postKey + "&ref=wwwtop_accounts_index" + "&return_to=http%3A%2F%2Fwww.pixiv.net%2F"; byte[] buf = Encoding.UTF8.GetBytes(data); req.ContentLength = buf.Length; req.ContentType = "application/x-www-form-urlencoded; charset=UTF-8"; req.KeepAlive = true; req.Referer = "https://accounts.pixiv.net/login?lang=zh&source=pc&view_type=page&ref=wwwtop_accounts_index"; req.Accept = "application/json, text/javascript, */*; q=0.01"; req.CookieContainer = cookieContainer; System.IO.Stream str = req.GetRequestStream(); str.Write(buf, 0, buf.Length); str.Close(); var getRsp = req.GetResponse(); //HTTP 302然后返回实际地址 cookie = getRsp.Headers.Get("Set-Cookie"); if (/*rsp.Headers.Get("Location") == null ||*/ cookie == null) { throw new Exception("自动登录失败"); } //Set-Cookie: PHPSESSID=3af0737dc5d8a27f5504a7b8fe427286; expires=Tue, 15-May-2012 10:05:39 GMT; path=/; domain=.pixiv.net int sessionIndex = cookie.LastIndexOf("PHPSESSID"); int device_tokenIndex = cookie.LastIndexOf("device_token"); cookie = cookie.Substring(sessionIndex, cookie.IndexOf(';', sessionIndex) - sessionIndex) + "; " + cookie.Substring(device_tokenIndex, cookie.IndexOf(';', device_tokenIndex) - device_tokenIndex); rsp.Close(); } }
public static void Run() { // Connect to iCUE using CgSDK -- Now done via the pipe server //StateTracking.SetupCgSDK(); // Setup and start the listener, add more prefixes for multiple access points HttpListener listener = new HttpListener(); string prefix = string.Format("http://{0}:{1}/", boundIP, port); listener.Prefixes.Add(prefix); listener.Start(); Console.WriteLine(pre + "HTTP Server listening to {0}", prefix); // Core processing loop for HTTP Requests while (Program.isRunning) { try { HttpListenerContext context = listener.GetContext(); HttpListenerRequest request = context.Request; HttpListenerResponse response = context.Response; // Process Request //ShowRequestProperties(request); // Extract information from url Dictionary <string, string> parameters = new Dictionary <string, string>(); List <string> suburls = new List <string>(); foreach (string key in request.QueryString.AllKeys) { parameters.Add(key, request.QueryString.Get(key)); } // Splitting the url up by '/' characters Regex rx = new Regex(@"(?:\/([^\/^\?]+))"); MatchCollection matches = rx.Matches(request.RawUrl); foreach (Match match in matches) { GroupCollection groups = match.Groups; suburls.Add(groups[1].Value); } // Logic for handling the request string responseString = ProcessRequest(suburls, parameters); // Send the appropriate response byte[] buffer = Encoding.UTF8.GetBytes(responseString); response.ContentLength64 = buffer.Length; System.IO.Stream output = response.OutputStream; output.Write(buffer, 0, buffer.Length); output.Close(); } catch (HttpListenerException e) { // Do f**k all, we don't really care, but it probably will break the program } } listener.Stop(); StateTracking.ReleaseControl(); Console.WriteLine(pre + "Disconnecting from iCUE"); }
/// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void cSV出力ToolStripMenuItem_Click(object sender, EventArgs e) { try { //-------------------------------------- // データが無ければ 戻る //-------------------------------------- if (fpS1.ActiveSheet.RowCount <= 0) { return; } clsCnvStr lclsCnvStr = new clsCnvStr(); string lstrCsv = ""; string lstrCsvDetail = ""; string lstrCsvHeader = ""; //************************************** // CSV出力文字作成 //************************************** //-------------------------------------- // CSVヘッダ部作成 //-------------------------------------- lstrCsvHeader = ""; lstrCsvHeader += this.Text.ToString() + Environment.NewLine; lstrCsvHeader += "作成日付:," + DateTime.Today.ToString("yyyy/MM/dd") + Environment.NewLine; lstrCsvHeader += "資料名:," + this.Text.ToString() + Environment.NewLine + Environment.NewLine; for (int i = 1; i < fpS1.ActiveSheet.ColumnHeader.Columns.Count; i++) { lstrCsvHeader += fpS1.ActiveSheet.ColumnHeader.Columns[i].Label + ","; } //-------------------------------------- // CSV明細部作成 //-------------------------------------- //------------------ // スプレッドの内容を取得 //------------------ lstrCsvDetail = clsSpread.SheetViewToCsv(fpS1.ActiveSheet); //-------------------------------------- // CSV出力文字生成 //-------------------------------------- //------------------ // 明細部 列を右にずらす //------------------ int lintAddColumn = 0; // ※ずらす列数 lstrCsvDetail = lstrCsvDetail.Trim().Replace(Environment.NewLine, Environment.NewLine + new string(',', lintAddColumn)); lstrCsvDetail = new string(',', lintAddColumn) + lstrCsvDetail + Environment.NewLine; //------------------ // ヘッダ部 + 明細部 //------------------ lstrCsv = ""; lstrCsv += lstrCsvHeader; //lstrCsv += Environment.NewLine; lstrCsv += lstrCsvDetail; //************************************** //-------------------------------------- // 『名前を付けて保存』画面表示 //-------------------------------------- SaveFileDialog lobjSFD = new SaveFileDialog(); lobjSFD.FileName = this.Text.ToString() + "_" + DateTime.Today.ToString("yyyyMMdd") + "_" + DateTime.Now.ToString("HHmmss") + "_" + Environment.MachineName + ".csv"; lobjSFD.Filter = "CSVファイル(*.csv)|*.csv|すべてのファイル(*.*)|*.*"; if (lobjSFD.ShowDialog() == DialogResult.Cancel) { return; } //-------------------------------------- // ファイル出力 //-------------------------------------- System.IO.Stream lobjStream = lobjSFD.OpenFile(); System.IO.StreamWriter lobjStreamWriter = new System.IO.StreamWriter(lobjStream, Encoding.GetEncoding("shift_jis")); lobjStreamWriter.Write(lstrCsv.Trim() + Environment.NewLine); lobjStreamWriter.Close(); lobjStream.Close(); //-------------------------------------- // メッセージ //-------------------------------------- MessageBox.Show("CSV出力を完了しました。", this.Text); } catch (Exception ex) { MessageBox.Show("ファイル保存に失敗しました。 " + Environment.NewLine + ex.Message); } }
private bool SaveVersion() { XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = true; settings.IndentChars = ("\t"); settings.Encoding = Encoding.GetEncoding("utf-8"); settings.OmitXmlDeclaration = false; System.IO.FileInfo f = new System.IO.FileInfo(Application.StartupPath + @"\ver.xml"); System.IO.Stream s = null; int i = 0; while (i < 10) { try { s = f.Open(System.IO.FileMode.Create, System.IO.FileAccess.ReadWrite, System.IO.FileShare.ReadWrite); break; } catch { System.Threading.Thread.Sleep(100); i++; } } if (s == null) { return(false); } XmlWriter xw = XmlWriter.Create(s, settings); XmlDocument doc = new XmlDocument(); XmlElement newElem = doc.CreateElement("application"); foreach (DevComponents.AdvTree.Node n in advTreeVersion.Nodes) { Version v = (Version)n.Tag; XmlElement newElemver = doc.CreateElement("ver"); newElemver.SetAttribute("en", v.enable?"1":"0"); newElemver.SetAttribute("type", v.type.ToString()); newElemver.InnerText = v.ver; newElem.AppendChild(newElemver); } doc.AppendChild(newElem); // Save the document to a file. White space is // preserved (no white space). doc.PreserveWhitespace = true; try { if (System.IO.File.Exists(Application.StartupPath + @"\ver.xml")) { System.IO.File.SetAttributes(Application.StartupPath + @"\ver.xml", System.IO.FileAttributes.Normal); } doc.WriteTo(xw); xw.Flush(); s.Close(); } catch { } return(true); }
/// <summary> /// get images sync /// </summary> //public List<Img> GetImages(int page, int count, string keyWord, int maskScore, int maskRes, ViewedID lastViewed, bool maskViewed, System.Net.IWebProxy proxy, bool showExplicit) //{ // return GetImages(GetPageString(page, count, keyWord, proxy), maskScore, maskRes, lastViewed, maskViewed, proxy, showExplicit); //} public override string GetPageString(int page, int count, string keyWord, System.Net.IWebProxy proxy) { string url = SiteUrl + "/?page=" + page; MyWebClient web = new MyWebClient { Proxy = proxy, Encoding = Encoding.UTF8 }; if (keyWord.Length > 0) { url = SiteUrl + "/search/process/"; //multi search string data = "tags=" + keyWord + "&source=&char=&artist=&postcontent=&txtposter="; if (type == 2) { data = "tags=&source=" + keyWord + "&char=&artist=&postcontent=&txtposter="; } else if (type == 3) { data = "tags=&source=&char=&artist=" + keyWord + "&postcontent=&txtposter="; } else if (type == 4) { data = "tags=&source=&char=" + keyWord + "&artist=&postcontent=&txtposter="; } //e-shuushuu需要将关键词转换为tag id,然后进行搜索 System.Net.HttpWebRequest req = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url); req.UserAgent = SessionClient.DefUA; req.Proxy = proxy; req.Timeout = 8000; req.Method = "POST"; //prevent 303 req.AllowAutoRedirect = false; byte[] buf = Encoding.UTF8.GetBytes(data); req.ContentType = "application/x-www-form-urlencoded"; req.ContentLength = buf.Length; System.IO.Stream str = req.GetRequestStream(); str.Write(buf, 0, buf.Length); str.Close(); System.Net.WebResponse rsp = req.GetResponse(); //http://e-shuushuu.net/search/results/?tags=2 //HTTP 303然后返回实际地址 string location = rsp.Headers["Location"]; rsp.Close(); if (location != null && location.Length > 0) { //非完整地址,需要前缀 url = rsp.Headers["Location"] + "&page=" + page; } else { throw new Exception("没有搜索到关键词相关的图片(每个关键词前后需要加双引号如 \"sakura\"))"); } } string pageString = web.DownloadString(url); web.Dispose(); return(pageString); }
private void HttpRequestThread(object obj) { HttpListenerContext ctx = obj as HttpListenerContext; HttpListenerRequest request = ctx.Request; string backData = ""; if (request.HasEntityBody) { using (System.IO.Stream body = request.InputStream) { using (System.IO.StreamReader reader = new System.IO.StreamReader(body, request.ContentEncoding)) { backData = reader.ReadToEnd(); } } } else { PostLog("No body.", Brushes.Red); } string inData = backData; if (string.IsNullOrWhiteSpace(backData)) { backData = "No data."; } else { PostLog("Body : " + backData, Brushes.Blue); } HttpListenerResponse response = ctx.Response; backData = backData + " : " + DateTime.Now.ToLongTimeString(); string responseString = "<HTML><BODY>" + backData + "</BODY></HTML>"; byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString); response.ContentLength64 = buffer.Length; System.IO.Stream output = response.OutputStream; PostLog("Trying to send response..."); output.Write(buffer, 0, buffer.Length); PostLog("Sent."); Dispatcher.Invoke((ThreadStart) delegate() { lock (ObjLock) { SentReceivedOc.Add(new SentReceivedItem() { Index = (SentReceivedOc.Count + 1).ToString(), ClientIP = inData, Received = backData }); } }, null); PostLog("Trying to close response..."); output.Close(); PostLog("Closed."); }
public bool Save(string baseDir) { if (!modified) { return(true); // doh } string fileName = FileName(); string filename = baseDir + fileName; System.IO.Stream fileout = null; System.IO.BinaryWriter file = null; //try { if (!System.IO.Directory.Exists(baseDir)) { System.IO.Directory.CreateDirectory(baseDir); } //} catch { }; int n_spots = 0; int n_steps = 0; try { fileout = System.IO.File.Create(filename + ".new"); if (fileout != null) { file = new System.IO.BinaryWriter(fileout); if (file != null) { file.Write(FILE_MAGIC); List <Spot> spots = GetAllSpots(); foreach (Spot s in spots) { file.Write(SPOT_MAGIC); file.Write((uint)0); // reserved file.Write((uint)s.flags); file.Write((float)s.X); file.Write((float)s.Y); file.Write((float)s.Z); uint n_paths = (uint)s.n_paths; file.Write((uint)n_paths); for (uint i = 0; i < n_paths; i++) { uint off = i * 3; file.Write((float)s.paths[off]); file.Write((float)s.paths[off + 1]); file.Write((float)s.paths[off + 2]); n_steps++; } n_spots++; } file.Write(FILE_ENDMAGIC); } if (file != null) { file.Close(); file = null; } if (fileout != null) { fileout.Close(); fileout = null; } String old = filename + ".bak"; if (System.IO.File.Exists(old)) { System.IO.File.Delete(old); } if (System.IO.File.Exists(filename)) { System.IO.File.Move(filename, old); } System.IO.File.Move(filename + ".new", filename); if (System.IO.File.Exists(old)) { System.IO.File.Delete(old); } modified = false; } else { Log("Save failed"); } Log("Saved " + fileName + " " + n_spots + " spots " + n_steps + " steps"); } catch (Exception e) { Log("Save failed " + e); } if (file != null) { file.Close(); file = null; } if (fileout != null) { fileout.Close(); fileout = null; } return(false); }
// This Function returns: // Good : Everything Worked Correctly // RescanNeeded : Something unexpectidly changed in the files, so Stop prompt user to rescan. // LogicError : This Should never happen and is a logic problem in the code // FileSystemError : Something is wrong with the files /// <summary> /// Performs the ROMVault File Copy, with the source and destination being files or zipped files /// </summary> /// <param name="fileIn">This is the file being copied, it may be a zipped file or a regular file system file</param> /// <param name="zipFileOut">This is the zip file that is being writen to, if it is null a new zip file will be made if we are coping to a zip</param> /// <param name="zipFilenameOut">This is the name of the .zip file to be made that will be created in zipFileOut</param> /// <param name="fileOut">This is the actual output filename</param> /// <param name="forceRaw">if true then we will do a raw copy, this is so that we can copy corrupt zips</param> /// <param name="error">This is the returned error message if this copy fails</param> /// <param name="foundFile">If we are SHA1/MD5 checking the source file for the first time, and it is different from what we expected the correct values for this file are returned in foundFile</param> /// <returns>ReturnCode.Good is the valid return code otherwire we have an error</returns> public static ReturnCode CopyFile(RvFile fileIn, ref ZipFile zipFileOut, string zipFilenameOut, RvFile fileOut, bool forceRaw, out string error, out RvFile foundFile) { foundFile = null; error = ""; if (_buffer == null) { _buffer = new byte[BufferSize]; } bool rawCopy = RawCopy(fileIn, fileOut, forceRaw); ulong streamSize = 0; ushort compressionMethod = 8; bool sourceTrrntzip = false; ZipFile zipFileIn = null; System.IO.Stream readStream = null; bool isZeroLengthFile = DBHelper.IsZeroLengthFile(fileOut); if (!isZeroLengthFile) { #region check that the in and out file match if (fileOut.FileStatusIs(FileStatus.SizeFromDAT) && fileOut.Size != null && fileIn.Size != fileOut.Size) { error = "Source and destination Size does not match. Logic Error."; return(ReturnCode.LogicError); } if (fileOut.FileStatusIs(FileStatus.CRCFromDAT) && fileOut.CRC != null && !ArrByte.bCompare(fileIn.CRC, fileOut.CRC)) { error = "Source and destination CRC does not match. Logic Error."; return(ReturnCode.LogicError); } if (fileOut.FileStatusIs(FileStatus.SHA1FromDAT) && fileIn.FileStatusIs(FileStatus.SHA1Verified)) { if (fileIn.SHA1 != null && fileOut.SHA1 != null && !ArrByte.bCompare(fileIn.SHA1, fileOut.SHA1)) { error = "Source and destination SHA1 does not match. Logic Error."; return(ReturnCode.LogicError); } } if (fileOut.FileStatusIs(FileStatus.MD5CHDFromDAT) && fileIn.FileStatusIs(FileStatus.MD5Verified)) { if (fileIn.MD5 != null && fileOut.MD5 != null && !ArrByte.bCompare(fileIn.MD5, fileOut.MD5)) { error = "Source and destination SHA1 does not match. Logic Error."; return(ReturnCode.LogicError); } } #endregion #region Find and Check/Open Input Files if (fileIn.FileType == FileType.ZipFile) // Input is a ZipFile { RvDir zZipFileIn = fileIn.Parent; if (zZipFileIn.FileType != FileType.Zip) { error = "Zip File Open but Source File is not a zip, Logic Error."; return(ReturnCode.LogicError); } string fileNameIn = zZipFileIn.FullName; sourceTrrntzip = (zZipFileIn.ZipStatus & ZipStatus.TrrntZip) == ZipStatus.TrrntZip; //if (zZipFileIn.ZipFileType == RvZip.ZipType.Zip) //{ zipFileIn = new ZipFile(); ZipReturn zr1; if (fileIn.ZipFileHeaderPosition != null) { zr1 = zipFileIn.ZipFileOpen(fileNameIn, zZipFileIn.TimeStamp, false); } else { zr1 = zipFileIn.ZipFileOpen(fileNameIn, zZipFileIn.TimeStamp, true); } switch (zr1) { case ZipReturn.ZipGood: break; case ZipReturn.ZipErrorFileNotFound: error = "File not found, Rescan required before fixing " + fileIn.Name; return(ReturnCode.FileSystemError); case ZipReturn.ZipErrorTimeStamp: error = "File has changed, Rescan required before fixing " + fileIn.Name; return(ReturnCode.FileSystemError); default: error = "Error Open Zip" + zr1 + ", with File " + fileIn.DatFullName; return(ReturnCode.FileSystemError); } if (fileIn.ZipFileHeaderPosition != null) { zipFileIn.ZipFileOpenReadStreamQuick((ulong)fileIn.ZipFileHeaderPosition, rawCopy, out readStream, out streamSize, out compressionMethod); } else { zipFileIn.ZipFileOpenReadStream(fileIn.ZipFileIndex, rawCopy, out readStream, out streamSize, out compressionMethod); } } else // Input is a regular file { string fileNameIn = fileIn.FullName; if (!IO.File.Exists(fileNameIn)) { error = "Rescan needed, File Changed :" + fileNameIn; return(ReturnCode.RescanNeeded); } IO.FileInfo fileInInfo = new IO.FileInfo(fileNameIn); if (fileInInfo.LastWriteTime != fileIn.TimeStamp) { error = "Rescan needed, File Changed :" + fileNameIn; return(ReturnCode.RescanNeeded); } int errorCode = IO.FileStream.OpenFileRead(fileNameIn, out readStream); if (errorCode != 0) { error = new Win32Exception(errorCode).Message + ". " + fileNameIn; return(ReturnCode.FileSystemError); } if (fileIn.Size == null) { error = "Null File Size found in Fixing File :" + fileNameIn; return(ReturnCode.LogicError); } streamSize = (ulong)fileIn.Size; if ((ulong)readStream.Length != streamSize) { error = "Rescan needed, File Length Changed :" + fileNameIn; return(ReturnCode.RescanNeeded); } } #endregion } else { sourceTrrntzip = true; } if (!rawCopy && (Settings.FixLevel == eFixLevel.TrrntZipLevel1 || Settings.FixLevel == eFixLevel.TrrntZipLevel2 || Settings.FixLevel == eFixLevel.TrrntZipLevel3)) { compressionMethod = 8; } #region Find and Check/Open Output Files System.IO.Stream writeStream; if (fileOut.FileType == FileType.ZipFile) { // if ZipFileOut == null then we have not open the output zip yet so open it from writing. if (zipFileOut == null) { if (IO.Path.GetFileName(zipFilenameOut) == "__ROMVault.tmp") { if (IO.File.Exists(zipFilenameOut)) { IO.File.Delete(zipFilenameOut); } } else if (IO.File.Exists(zipFilenameOut)) { error = "Rescan needed, File Changed :" + zipFilenameOut; return(ReturnCode.RescanNeeded); } zipFileOut = new ZipFile(); ZipReturn zrf = zipFileOut.ZipFileCreate(zipFilenameOut); if (zrf != ZipReturn.ZipGood) { error = "Error Opening Write Stream " + zrf; return(ReturnCode.FileSystemError); } } else { if (zipFileOut.ZipOpen != ZipOpenType.OpenWrite) { error = "Output Zip File is not set to OpenWrite, Logic Error."; return(ReturnCode.LogicError); } if (zipFileOut.ZipFilename != (new IO.FileInfo(zipFilenameOut).FullName)) { error = "Output Zip file has changed name from " + zipFileOut.ZipFilename + " to " + zipFilenameOut + ". Logic Error"; return(ReturnCode.LogicError); } } if (fileIn.Size == null) { error = "Null File Size found in Fixing File :" + fileIn.FullName; return(ReturnCode.LogicError); } ZipReturn zr = zipFileOut.ZipFileOpenWriteStream(rawCopy, sourceTrrntzip, fileOut.Name, (ulong)fileIn.Size, compressionMethod, out writeStream); if (zr != ZipReturn.ZipGood) { error = "Error Opening Write Stream " + zr; return(ReturnCode.FileSystemError); } } else { if (IO.File.Exists(zipFilenameOut) && fileOut.GotStatus != GotStatus.Corrupt) { error = "Rescan needed, File Changed :" + zipFilenameOut; return(ReturnCode.RescanNeeded); } int errorCode = IO.FileStream.OpenFileWrite(zipFilenameOut, out writeStream); if (errorCode != 0) { error = new Win32Exception(errorCode).Message + ". " + zipFilenameOut; return(ReturnCode.FileSystemError); } } #endregion byte[] bCRC; byte[] bMD5 = null; byte[] bSHA1 = null; if (!isZeroLengthFile) { #region Do Data Tranfer CRC32Hash crc32 = null; MD5 md5 = null; SHA1 sha1 = null; if (!rawCopy) { crc32 = new CRC32Hash(); md5 = MD5.Create(); sha1 = SHA1.Create(); } ulong sizetogo = streamSize; while (sizetogo > 0) { int sizenow = sizetogo > BufferSize ? BufferSize : (int)sizetogo; try { readStream.Read(_buffer, 0, sizenow); } catch (ZlibException) { if (fileIn.FileType == FileType.ZipFile && zipFileIn != null) { ZipReturn zr = zipFileIn.ZipFileCloseReadStream(); if (zr != ZipReturn.ZipGood) { error = "Error Closing " + zr + " Stream :" + zipFileIn.Filename(fileIn.ReportIndex); return(ReturnCode.FileSystemError); } zipFileIn.ZipFileClose(); } else { readStream.Close(); } if (fileOut.FileType == FileType.ZipFile) { ZipReturn zr = zipFileOut.ZipFileCloseWriteStream(new byte[] { 0, 0, 0, 0 }); if (zr != ZipReturn.ZipGood) { error = "Error Closing Stream " + zr; return(ReturnCode.FileSystemError); } zipFileOut.ZipFileRollBack(); } else { writeStream.Flush(); writeStream.Close(); IO.File.Delete(zipFilenameOut); } error = "Error in Data Stream"; return(ReturnCode.SourceCRCCheckSumError); } catch (Exception e) { error = "Error reading Source File " + e.Message; return(ReturnCode.FileSystemError); } if (!rawCopy) { crc32.TransformBlock(_buffer, 0, sizenow, null, 0); md5.TransformBlock(_buffer, 0, sizenow, null, 0); sha1.TransformBlock(_buffer, 0, sizenow, null, 0); } try { writeStream.Write(_buffer, 0, sizenow); } catch (Exception e) { Debug.WriteLine(e.Message); error = "Error writing out file. " + Environment.NewLine + e.Message; return(ReturnCode.FileSystemError); } sizetogo = sizetogo - (ulong)sizenow; } writeStream.Flush(); #endregion #region Collect Checksums // if we did a full copy then we just calculated all the checksums while doing the copy if (!rawCopy) { crc32.TransformFinalBlock(_buffer, 0, 0); md5.TransformFinalBlock(_buffer, 0, 0); sha1.TransformFinalBlock(_buffer, 0, 0); bCRC = crc32.Hash; bMD5 = md5.Hash; bSHA1 = sha1.Hash; } // if we raw copied and the source file has been FileChecked then we can trust the checksums in the source file else { bCRC = ArrByte.Copy(fileIn.CRC); if (fileIn.FileStatusIs(FileStatus.MD5Verified)) { bMD5 = ArrByte.Copy(fileIn.MD5); } if (fileIn.FileStatusIs(FileStatus.SHA1Verified)) { bSHA1 = ArrByte.Copy(fileIn.SHA1); } } #endregion #region close the ReadStream if (fileIn.FileType == FileType.ZipFile && zipFileIn != null) { ZipReturn zr = zipFileIn.ZipFileCloseReadStream(); if (zr != ZipReturn.ZipGood) { error = "Error Closing " + zr + " Stream :" + zipFileIn.Filename(fileIn.ReportIndex); return(ReturnCode.FileSystemError); } zipFileIn.ZipFileClose(); } else { readStream.Close(); //if (IO.File.Exists(tmpFilename)) // IO.File.Delete(tmpFilename); } #endregion } else { // Zero Length File (Directory in a Zip) if (fileOut.FileType == FileType.ZipFile) { zipFileOut.ZipFileAddDirectory(); } bCRC = VarFix.CleanMD5SHA1("00000000", 8); bMD5 = VarFix.CleanMD5SHA1("d41d8cd98f00b204e9800998ecf8427e", 32); bSHA1 = VarFix.CleanMD5SHA1("da39a3ee5e6b4b0d3255bfef95601890afd80709", 40); } #region close the WriteStream if (fileOut.FileType == FileType.ZipFile) { ZipReturn zr = zipFileOut.ZipFileCloseWriteStream(bCRC); if (zr != ZipReturn.ZipGood) { error = "Error Closing Stream " + zr; return(ReturnCode.FileSystemError); } fileOut.ZipFileIndex = zipFileOut.LocalFilesCount() - 1; fileOut.ZipFileHeaderPosition = zipFileOut.LocalHeader(fileOut.ZipFileIndex); } else { writeStream.Flush(); writeStream.Close(); IO.FileInfo fi = new IO.FileInfo(zipFilenameOut); fileOut.TimeStamp = fi.LastWriteTime; } #endregion if (!isZeroLengthFile) { if (!rawCopy) { if (!ArrByte.bCompare(bCRC, fileIn.CRC)) { fileIn.GotStatus = GotStatus.Corrupt; error = "Source CRC does not match Source Data stream, corrupt Zip"; if (fileOut.FileType == FileType.ZipFile) { zipFileOut.ZipFileRollBack(); } else { IO.File.Delete(zipFilenameOut); } return(ReturnCode.SourceCRCCheckSumError); } fileIn.FileStatusSet(FileStatus.CRCVerified | FileStatus.SizeVerified); bool sourceFailed = false; // check to see if we have a MD5 from the DAT file if (fileIn.FileStatusIs(FileStatus.MD5FromDAT)) { if (fileIn.MD5 == null) { error = "Should have an filein MD5 from Dat but not found. Logic Error."; return(ReturnCode.LogicError); } if (!ArrByte.bCompare(fileIn.MD5, bMD5)) { sourceFailed = true; } else { fileIn.FileStatusSet(FileStatus.MD5Verified); } } // check to see if we have an MD5 (not from the DAT) so must be from previously scanning this file. else if (fileIn.MD5 != null) { if (!ArrByte.bCompare(fileIn.MD5, bMD5)) { // if we had an MD5 from a preview scan and it now does not match, something has gone really bad. error = "The MD5 found does not match a previously scanned MD5, this should not happen, unless something got corrupt."; return(ReturnCode.LogicError); } } else // (FileIn.MD5 == null) { fileIn.MD5 = bMD5; fileIn.FileStatusSet(FileStatus.MD5Verified); } // check to see if we have a SHA1 from the DAT file if (fileIn.FileStatusIs(FileStatus.SHA1FromDAT)) { if (fileIn.SHA1 == null) { error = "Should have an filein SHA1 from Dat but not found. Logic Error."; return(ReturnCode.LogicError); } if (!ArrByte.bCompare(fileIn.SHA1, bSHA1)) { sourceFailed = true; } else { fileIn.FileStatusSet(FileStatus.SHA1Verified); } } // check to see if we have an SHA1 (not from the DAT) so must be from previously scanning this file. else if (fileIn.SHA1 != null) { if (!ArrByte.bCompare(fileIn.SHA1, bSHA1)) { // if we had an SHA1 from a preview scan and it now does not match, something has gone really bad. error = "The SHA1 found does not match a previously scanned SHA1, this should not happen, unless something got corrupt."; return(ReturnCode.LogicError); } } else // (FileIn.SHA1 == null) { fileIn.SHA1 = bSHA1; fileIn.FileStatusSet(FileStatus.SHA1Verified); } if (sourceFailed) { if (fileIn.FileType == FileType.ZipFile) { RvFile tZFile = new RvFile(FileType.ZipFile); foundFile = tZFile; tZFile.ZipFileIndex = fileIn.ZipFileIndex; tZFile.ZipFileHeaderPosition = fileIn.ZipFileHeaderPosition; } else { foundFile = new RvFile(fileIn.FileType); } foundFile.Name = fileIn.Name; foundFile.Size = fileIn.Size; foundFile.CRC = bCRC; foundFile.MD5 = bMD5; foundFile.SHA1 = bSHA1; foundFile.TimeStamp = fileIn.TimeStamp; foundFile.SetStatus(DatStatus.NotInDat, GotStatus.Got); foundFile.FileStatusSet(FileStatus.SizeVerified | FileStatus.CRCVerified | FileStatus.MD5Verified | FileStatus.SHA1Verified); if (fileOut.FileType == FileType.ZipFile) { zipFileOut.ZipFileRollBack(); } else { IO.File.Delete(zipFilenameOut); } return(ReturnCode.SourceCheckSumError); } } } if (fileOut.FileType == FileType.ZipFile) { fileOut.FileStatusSet(FileStatus.SizeFromHeader | FileStatus.CRCFromHeader); } if (fileOut.FileStatusIs(FileStatus.CRCFromDAT) && fileOut.CRC != null && !ArrByte.bCompare(fileOut.CRC, bCRC)) { //Rollback the file if (fileOut.FileType == FileType.ZipFile) { zipFileOut.ZipFileRollBack(); } else { IO.File.Delete(zipFilenameOut); } return(ReturnCode.DestinationCheckSumError); } fileOut.CRC = bCRC; if (!rawCopy || fileIn.FileStatusIs(FileStatus.CRCVerified)) { fileOut.FileStatusSet(FileStatus.CRCVerified); } if (bSHA1 != null) { if (fileOut.FileStatusIs(FileStatus.SHA1FromDAT) && fileOut.SHA1 != null && !ArrByte.bCompare(fileOut.SHA1, bSHA1)) { //Rollback the file if (fileOut.FileType == FileType.ZipFile) { zipFileOut.ZipFileRollBack(); } else { IO.File.Delete(zipFilenameOut); } return(ReturnCode.DestinationCheckSumError); } fileOut.SHA1 = bSHA1; fileOut.FileStatusSet(FileStatus.SHA1Verified); } if (bMD5 != null) { if (fileOut.FileStatusIs(FileStatus.MD5FromDAT) && fileOut.MD5 != null && !ArrByte.bCompare(fileOut.MD5, bMD5)) { //Rollback the file if (fileOut.FileType == FileType.ZipFile) { zipFileOut.ZipFileRollBack(); } else { IO.File.Delete(zipFilenameOut); } return(ReturnCode.DestinationCheckSumError); } fileOut.MD5 = bMD5; fileOut.FileStatusSet(FileStatus.MD5Verified); } if (fileIn.Size != null) { fileOut.Size = fileIn.Size; fileOut.FileStatusSet(FileStatus.SizeVerified); } if (fileIn.GotStatus == GotStatus.Corrupt) { fileOut.GotStatus = GotStatus.Corrupt; } else { fileOut.GotStatus = GotStatus.Got; // Changes RepStatus to Correct } fileOut.FileStatusSet(FileStatus.SizeVerified); if (fileOut.SHA1CHD == null && fileIn.SHA1CHD != null) { fileOut.SHA1CHD = fileIn.SHA1CHD; } if (fileOut.MD5CHD == null && fileIn.MD5CHD != null) { fileOut.MD5CHD = fileIn.MD5CHD; } fileOut.CHDVersion = fileIn.CHDVersion; fileOut.FileStatusSet(FileStatus.SHA1CHDFromHeader | FileStatus.MD5CHDFromHeader | FileStatus.SHA1CHDVerified | FileStatus.MD5CHDVerified, fileIn); return(ReturnCode.Good); }
private HttpWebRequest CreateRequest() { HttpWebRequest request = null; request = (HttpWebRequest)HttpWebRequest.Create(this._UriString); request.Accept = "*/*"; request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.0; zh-CN; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3"; request.AllowAutoRedirect = this._AllowAutoRedirect; request.CookieContainer = new CookieContainer(); request.KeepAlive = true; request.Referer = this._Referer; if (this._IsProxy) { string _ProxyHost = this._ProxyHost; int _ProxyPort = this._ProxyPort; string ProxyUser = this._ProxyUser; string ProxyPassword = this._ProxyPassword; //string ProxyDomain = ""; System.Net.WebProxy oWebProxy = new System.Net.WebProxy(_ProxyHost, _ProxyPort); oWebProxy.Credentials = new NetworkCredential(ProxyUser, ProxyPassword); request.Proxy = oWebProxy; } if (this._CookiePost != null) { System.Uri u = new Uri(_UriString); foreach (System.Net.Cookie c in _CookiePost) { c.Domain = u.Host; } request.CookieContainer.PerDomainCapacity = 50; request.CookieContainer.Add(_CookiePost); } if (_PostData != null && _PostData.Length > 0) { request.ContentType = "application/x-www-form-urlencoded"; request.Method = "POST"; byte[] buffer = this._Encoding.GetBytes(this._PostData); request.ContentLength = buffer.Length; System.IO.Stream stream = null; try { stream = request.GetRequestStream(); stream.Write(buffer, 0, buffer.Length); } catch (Exception ex) { this._Err = ex.Message; } finally { if (stream != null) { stream.Close(); } } } return(request); }
public void ActOnOutMessage(FlowLib.Events.FmdcEventArgs e) { string key = null; UPnPDevice device = null; switch (e.Action) { case Actions.UPnPDeviceDescription: key = e.Data as string; if (key != null) { try { if (con.RootDevices.ContainsKey(key)) { device = con.RootDevices[key]; System.Net.HttpWebRequest httpRequest = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(device.Information.DescriptionURL); WebResponse webResponse = httpRequest.GetResponse(); System.IO.StreamReader sr = new System.IO.StreamReader(webResponse.GetResponseStream()); string ret = sr.ReadToEnd(); sr.Close(); FmdcEventArgs e2 = new FmdcEventArgs(Actions.UPnPDeviceDescription, ret); Update(con, e2); if (!e2.Handled) { ParseDescription(ref device, ret); Update(con, new FmdcEventArgs(Actions.UPnPDeviceUpdated, device)); } } } catch (System.Exception) { // TODO: Make exception handling } } break; case Actions.UPnPFunctionCall: UPnPFunction func = e.Data as UPnPFunction; if (func != null) { try { #region Create Envelope System.Text.StringBuilder sb = new System.Text.StringBuilder(); sb.Append("<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\" s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">"); sb.Append("<s:Body>"); sb.Append("<u:" + func.Name + " xmlns:u=\"" + func.Service.Information.serviceType + "\">"); foreach (KeyValuePair <string, string> argument in func.Arguments) { sb.AppendFormat("<{0}>{1}</{0}>", argument.Key, argument.Value); } sb.Append("</u:" + func.Name + ">"); sb.Append("</s:Body>"); sb.Append("</s:Envelope>"); #endregion #region Create Request byte[] body = System.Text.Encoding.UTF8.GetBytes(sb.ToString()); string url = null; // Is ControlURL relative or absolute? if (func.Service.Information.ControlURL.StartsWith("/")) { url = "http://" + func.Service.Device.Information.URLBase + func.Service.Information.ControlURL; } else { url = func.Service.Information.ControlURL; } WebRequest wr = WebRequest.Create(url); //+ controlUrl); wr.Headers.Clear(); wr.Method = "POST"; wr.ContentType = "text/xml; charset=\"utf-8\""; wr.Headers.Add("SOAPAction", "\"" + func.Service.Information.serviceType + "#" + func.Name + "\""); wr.ContentLength = body.Length; #endregion #region Call Service function // TODO: Add error handling in this (If server returns code 500 or something) System.IO.Stream stream = wr.GetRequestStream(); stream.Write(body, 0, body.Length); stream.Flush(); stream.Close(); WebResponse wres = wr.GetResponse(); System.IO.StreamReader sr = new System.IO.StreamReader(wres.GetResponseStream()); string xml = sr.ReadToEnd(); sr.Close(); #endregion #region Parse returning data XmlDocument document = new XmlDocument(); document.LoadXml(xml); SortedList <string, string> tmpList = new SortedList <string, string>(func.Arguments); foreach (KeyValuePair <string, string> argument in func.Arguments) { XmlNodeList nodes = document.GetElementsByTagName(argument.Key); if (nodes.Count == 1) { tmpList[argument.Key] = nodes[0].InnerText; } } func.Arguments = tmpList; #endregion #region Return data e.Data = func; e.Handled = true; #endregion } catch (System.Net.WebException webEx) { HttpWebResponse resp = webEx.Response as HttpWebResponse; if (resp != null) { func.ErrorCode = (int)resp.StatusCode; } e.Data = func; } catch { // TODO: Add more specific error handling here } } break; } }
public static void SaveDocument(XmlDocument doc, string filename, System.Text.Encoding encoding, bool prettyPrint) { System.IO.Stream stream = System.IO.File.Create(filename); SaveDocument(doc, stream, encoding, prettyPrint); stream.Close(); }
public static string HttpPost(Dictionary <string, string> postList, string strURL) { System.Net.HttpWebRequest request; request = (System.Net.HttpWebRequest)WebRequest.Create(strURL); //Post请求方式 request.Method = "POST"; //内容类型 //request.ContentType = "text/xml"; request.ContentType = "application/x-www-form-urlencoded"; StringBuilder sb = new StringBuilder(); //参数经过URL编码 if (postList.Count > 0) { int index = 0; foreach (var data in postList) { sb.Append(System.Web.HttpUtility.UrlEncode(data.Key)); if (string.IsNullOrEmpty(data.Key)) { continue; } sb.Append("=" + System.Web.HttpUtility.UrlEncode(data.Value)); index++; if (postList.Count != index) { sb.Append("&"); } } } else { return(""); } //sb.Append("&type=xml"); byte[] payload; //将URL编码后的字符串转化为字节 payload = System.Text.Encoding.UTF8.GetBytes(sb.ToString()); //设置请求的ContentLength request.ContentLength = payload.Length; //获得请求流 System.IO.Stream writer = request.GetRequestStream(); //将请求参数写入流 writer.Write(payload, 0, payload.Length); //关闭请求流 try { writer.Flush(); writer.Close(); } catch (Exception ex) { //Z.Common.Logger.WriteAppLog("写入文件流失败:" + ex.ToString(), "RestServer"); } System.Net.HttpWebResponse response; //获得响应流 try { response = (HttpWebResponse)request.GetResponse(); } catch (WebException ex) { response = (HttpWebResponse)ex.Response; } //response = (System.Net.HttpWebResponse)request.GetResponse(); System.IO.Stream s; s = response.GetResponseStream(); string StrDate = ""; string strValue = ""; System.IO.StreamReader Reader = new System.IO.StreamReader(s, Encoding.GetEncoding("utf-8")); while ((StrDate = Reader.ReadLine()) != null) { strValue += StrDate; } return(strValue); }
private void PostApplications() { try { List <object[]> appsData = _DB_Connection.Select(DB_Table.APPLICATIONS, new string[] { "id", "mcado", "chernobyl", "needs_hostel", "passing_examinations", "priority_right", "entrant_id", "status" }, new List <Tuple <string, Relation, object> > { new Tuple <string, Relation, object>("campaign_id", Relation.EQUAL, _CampaignID), new Tuple <string, Relation, object>("master_appl", Relation.EQUAL, false), new Tuple <string, Relation, object>("status", Relation.NOT_EQUAL, "withdrawn") }); string connectionStr = "server=" + server + ";port=3306;database=" + dbname + ";user="******";password="******";"; MySql.Data.MySqlClient.MySqlConnection connection = new MySql.Data.MySqlClient.MySqlConnection(connectionStr); if (appsData.Count > 0) { if ((cbPost.Checked) && (rbDirectToDB.Checked)) { connection.Open(); string Query = "SET foreign_key_checks = 0;" + "LOCK TABLES `" + dbname + "`.`abitur_tmptable` WRITE, " + "`" + dbname + "`.`application_tmptable` WRITE, " + "`" + dbname + "`.`profile_table` READ, " + "`" + dbname + "`.`direction_table` AS dt READ, " + "`" + dbname + "`.`faculty_table` AS ft READ;" + "TRUNCATE TABLE `" + dbname + "`.`abitur_tmptable`;" + "TRUNCATE TABLE `" + dbname + "`.`application_tmptable`;"; new MySql.Data.MySqlClient.MySqlCommand(Query, connection).ExecuteNonQuery(); } XDocument PackageData = new XDocument(new XElement("Root")); PackageData.Root.Add(new XElement("AuthData", _AuthData)); PackageData.Root.Add(new XElement("PackageData")); IEnumerable <DB_Queries.Mark> marks = DB_Queries.GetMarks(_DB_Connection, appsData.Select(s => (uint)s[0]), _CampaignID); IEnumerable <DB_Queries.Document> documents = DB_Queries.GetDocuments(_DB_Connection, appsData.Select(s => (uint)s[0])); var passwords = _DB_Connection.Select(DB_Table.ENTRANTS, "id", "personal_password").Select(s => new { EntrID = (uint)s[0], Password = s[1].ToString() }); var names = _DB_Connection.Select(DB_Table.ENTRANTS_VIEW, "id", "last_name", "first_name", "middle_name").Select(s => new { EntrID = (uint)s[0], LastName = s[1].ToString(), FirstName = s[2].ToString(), MiddleName = s[3] as string }); count = 0; foreach (object[] application in appsData) { if ((threadPost.ThreadState == ThreadState.Aborted) || (threadPost.ThreadState == ThreadState.Stopped)) { break; } XElement abitur = new XElement("Abitur", new XElement("Uin", application[0]), new XElement("EntrantUin", application[6]), new XElement("Surname", names.Single(s => s.EntrID == (uint)application[6]).LastName), new XElement("Name", names.Single(s => s.EntrID == (uint)application[6]).FirstName), new XElement("Name2", names.Single(s => s.EntrID == (uint)application[6]).MiddleName), new XElement("Password", passwords.Single(s => s.EntrID == (uint)application[6]).Password), new XElement("Status", application[7]), new XElement("MathBall", 0), new XElement("CheckedByFISMath", 0), new XElement("PhisBall", 0), new XElement("CheckedByFISPhis", 0), new XElement("RusBall", 0), new XElement("CheckedByFISRus", 0), new XElement("ObshBall", 0), new XElement("CheckedByFISObsh", 0), new XElement("ForenBall", 0), new XElement("CheckedByFISForen", 0), new XElement("IABall", 0), new XElement("ODO", 0), new XElement("Olymp", 0), new XElement("Exam", 0), new XElement("Hostel", 0), new XElement("PP", 0), new XElement("MCADO", 0), new XElement("Chern", 0), new XElement("Documents", new XElement("ApplicationOfAdmission", 1), new XElement("PassportCopy", 0), new XElement("CertificateDiplomCopy", 0), new XElement("HRRefCopy", 0), new XElement("ReferralPK", 0), new XElement("MedRef", 0), new XElement("Photo", 0), new XElement("OrphanDocument", 0), new XElement("InvalidDocument", 0), new XElement("AbsenceOfContraindicationsForTraining", 0)), new XElement("Applications")); if ((bool)application[4]) { abitur.SetElementValue("Exam", 1); } if ((bool)application[3]) { abitur.SetElementValue("Hostel", 1); } if ((bool)application[5]) { abitur.SetElementValue("PP", 1); abitur.Element("Documents").SetElementValue("ReferralPK", 1); } if ((bool)application[1]) { abitur.SetElementValue("MCADO", 1); } if ((bool)application[2]) { abitur.SetElementValue("Chern", 1); abitur.Element("Documents").SetElementValue("ReferralPK", 1); } SetMarks((uint)application[0], abitur, marks); SetDocuments((uint)application[0], abitur, documents); SetIA((uint)application[0], abitur); SetEntrances((uint)application[0], abitur); if ((cbPost.Checked) && (rbDirectToDB.Checked)) { string Query = "INSERT INTO `" + dbname + "`.`abitur_tmptable` " + "(`abitur_id`, `uin`, `entrant_uin`, `surname`, `_name`, `name2`, `status`, " + "`math_ball`, `checked_by_FIS_math`, `phis_ball`, `checked_by_FIS_phis`, `rus_ball`, `checked_by_FIS_rus`, " + "`obsh_ball`, `checked_by_FIS_obsh`, `foren_ball`, `checked_by_FIS_foren`, `IA_ball`, " + "`ODO`, `Olymp`, `Exam`, `hostel`, `PP`, `MCADO`, `Chern`, `appl_of_admission`, " + "`passport_copy`, `a_d_copy`, `hr_ref_copy`, `referral_pk`, `med_ref`, `photo`, `password`, " + "`orphan_document`, `invalid_document`, `pmp_document`, `absence_of_contraindications`) VALUES " + "(0, " + abitur.Element("Uin").Value.ToString() + ", " + abitur.Element("EntrantUin").Value.ToString() + ", '" + abitur.Element("Surname").Value.ToString() + "', '" + abitur.Element("Name").Value.ToString() + "' ,'" + abitur.Element("Name2").Value.ToString() + "' ,'" + abitur.Element("Status").Value.ToString() + "' ," + abitur.Element("MathBall").Value.ToString() + " ," + abitur.Element("CheckedByFISMath").Value.ToString() + " ," + abitur.Element("PhisBall").Value.ToString() + " ," + abitur.Element("CheckedByFISPhis").Value.ToString() + " ," + abitur.Element("RusBall").Value.ToString() + " ," + abitur.Element("CheckedByFISRus").Value.ToString() + " ," + abitur.Element("ObshBall").Value.ToString() + " ," + abitur.Element("CheckedByFISObsh").Value.ToString() + " ," + abitur.Element("ForenBall").Value.ToString() + " ," + abitur.Element("CheckedByFISForen").Value.ToString() + " ," + abitur.Element("IABall").Value.ToString() + " ," + abitur.Element("ODO").Value.ToString() + ", " + abitur.Element("Olymp").Value.ToString() + " ," + abitur.Element("Exam").Value.ToString() + ", " + abitur.Element("Hostel").Value.ToString() + " ," + abitur.Element("PP").Value.ToString() + ", " + abitur.Element("MCADO").Value.ToString() + ", " + abitur.Element("Chern").Value.ToString() + " ," + abitur.Element("Documents").Element("ApplicationOfAdmission").Value.ToString() + " ," + abitur.Element("Documents").Element("PassportCopy").Value.ToString() + " ," + abitur.Element("Documents").Element("CertificateDiplomCopy").Value.ToString() + " ," + abitur.Element("Documents").Element("HRRefCopy").Value.ToString() + " ," + abitur.Element("Documents").Element("ReferralPK").Value.ToString() + " ," + abitur.Element("Documents").Element("MedRef").Value.ToString() + " ," + abitur.Element("Documents").Element("Photo").Value.ToString() + ", '" + abitur.Element("Password").Value.ToString() + "', " + abitur.Element("Documents").Element("OrphanDocument").Value.ToString() + ", " + abitur.Element("Documents").Element("InvalidDocument").Value.ToString() + ", 0, " + abitur.Element("Documents").Element("AbsenceOfContraindicationsForTraining").Value.ToString() + ");"; string direction, profile; int direction_id = 1000, profile_id = 1000; string query_tmp; foreach (XElement appl in abitur.Element("Applications").Elements()) { direction = appl.Element("Direction").Value; profile = appl.Element("Profile").Value; if (direction != "0") { query_tmp = "SELECT dt.direction_id FROM `" + dbname + "`.`direction_table` AS dt, " + "`" + dbname + "`.`faculty_table` AS ft WHERE (dt.id_by_FIS=" + direction + ") AND " + "(ft.short_caption='" + appl.Element("Faculty").Value + "') AND " + "(dt.faculty_id=ft.faculty_id)"; direction_id = Convert.ToInt16(new MySql.Data.MySqlClient.MySqlCommand(query_tmp, connection).ExecuteScalar().ToString()); } if (profile != "") { query_tmp = "SELECT profile_id FROM `" + dbname + "`.`profile_table` WHERE short_caption='" + profile + "'"; profile_id = Convert.ToInt16(new MySql.Data.MySqlClient.MySqlCommand(query_tmp, connection).ExecuteScalar().ToString()); } Query = Query + "INSERT INTO `" + dbname + "`.`application_tmptable` " + "(`application_id`, `uin`, `direction_id`, `profile_id`, `_condition`, `appl_of_consent`, `form_of_education`) VALUES " + "(0, " + abitur.Element("Uin").Value + ", " + direction_id.ToString() + ", " + profile_id.ToString() + " ," + appl.Element("Condition").Value + " ," + appl.Element("ApplicationOfConsent").Value + " ," + appl.Element("FormOfEducation").Value + ");"; } new MySql.Data.MySqlClient.MySqlCommand(Query, connection).ExecuteNonQuery(); } PackageData.Root.Element("PackageData").Add(abitur); count++; lCount.BeginInvoke(new InvokeDelegate(() => { lCount.Text = count.ToString() + " абитуриентов"; })); } if ((cbPost.Checked) && (rbDirectToDB.Checked)) { new MySql.Data.MySqlClient.MySqlCommand("UNLOCK TABLES;", connection).ExecuteNonQuery(); } timerSum.Stop(); //timerSum.Enabled = false; _SchemaSet.Add(null, SchemaPath); PackageData.Validate(_SchemaSet, (send, ee) => { throw ee.Exception; }); if (cbSave.Checked) { PackageData.Save("doc.xml"); } if ((cbPost.Checked) && (rbDirectToDB.Checked)) { connection.Close(); HttpWebRequest HttpRequest = (HttpWebRequest)WebRequest.Create(script); HttpWebResponse HttpResponse; HttpResponse = (HttpWebResponse)HttpRequest.GetResponse(); if (HttpResponse.StatusCode == HttpStatusCode.OK) { System.IO.Stream responseStream = HttpResponse.GetResponseStream(); string responseStr = new System.IO.StreamReader(responseStream).ReadToEnd(); tbResponse.BeginInvoke(new InvokeDelegate(() => { tbResponse.Text = tbResponse.Text + responseStr + "\r\n" + "Отправлено: " + count.ToString() + " абитуриента за " + (sumTime / 60).ToString() + " мин. " + (sumTime % 60).ToString() + " сек.; " + "Среднее время на одного абитуриента: " + System.Math.Round((float)sumTime / count, 2) + " сек.\r\n\r\n"; })); HttpResponse.Close(); } } if ((cbPost.Checked) && (rbPostMethod.Checked)) { byte[] bytesData = System.Text.Encoding.UTF8.GetBytes("XMLData=" + PackageData.ToString()); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(cbAdress.Text); request.ContentType = "application/x-www-form-urlencoded"; request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"; request.UserAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36"; request.ContentLength = bytesData.Length; request.Method = "POST"; System.IO.Stream requestStream = request.GetRequestStream(); requestStream.Write(bytesData, 0, bytesData.Length); requestStream.Close(); HttpWebResponse response; response = (HttpWebResponse)request.GetResponse(); if (response.StatusCode == HttpStatusCode.OK) { System.IO.Stream responseStream = response.GetResponseStream(); string responseStr = new System.IO.StreamReader(responseStream).ReadToEnd(); tbResponse.Text = responseStr; } } if ((cbPost.Checked) && (rbFTPMethod.Checked)) { // Get the object used to communicate with the server. FtpWebRequest FtpRequest = (FtpWebRequest)WebRequest.Create(tbServer.Text + "/doc.xml"); FtpRequest.Method = WebRequestMethods.Ftp.UploadFile; // This example assumes the FTP site uses anonymous logon. FtpRequest.Credentials = new NetworkCredential(tbUser.Text, tbPassword.Text); // Copy the contents of the file to the request stream. System.IO.StreamReader sourceStream = new System.IO.StreamReader("doc.xml"); byte[] fileContents = System.Text.Encoding.UTF8.GetBytes(sourceStream.ReadToEnd()); sourceStream.Close(); FtpRequest.ContentLength = fileContents.Length; System.IO.Stream requestStream = FtpRequest.GetRequestStream(); requestStream.Write(fileContents, 0, fileContents.Length); requestStream.Close(); FtpWebResponse FtpResponse = (FtpWebResponse)FtpRequest.GetResponse(); tbResponse.Text = tbResponse.Text + DateTime.Now.ToString() + ": " + FtpResponse.StatusDescription + "\n"; FtpResponse.Close(); //FtpResponse.StatusCode=FtpStatusCode.ClosingData if (FtpResponse.StatusCode == FtpStatusCode.ClosingData) { HttpWebRequest HttpRequest = (HttpWebRequest)WebRequest.Create(tbAdress.Text); HttpWebResponse HttpResponse; HttpResponse = (HttpWebResponse)HttpRequest.GetResponse(); if (HttpResponse.StatusCode == HttpStatusCode.OK) { System.IO.Stream responseStream = HttpResponse.GetResponseStream(); string responseStr = new System.IO.StreamReader(responseStream).ReadToEnd(); tbResponse.Text = tbResponse.Text + responseStr + "\r\n"; HttpResponse.Close(); } } } } } catch (Exception e) { MessageBox.Show(e.Message); } }
public void CloseStream() { m_Stream.Close(); }
static void Main(string[] args) { Dictionary <string, string[]> aHeaders = new Dictionary <string, string[]>(); aHeaders.Add("x-axw-rest-identifier", new string[] { REST_IDENTIFIER }); aHeaders.Add("x-axw-rest-guid", new string[] { Guid.NewGuid().ToString() }); aHeaders.Add("x-axw-rest-timestamp", new string[] { ((long)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalMilliseconds).ToString() }); ArrayList aRESTTokenCollection = new ArrayList(); HttpWebRequest aReq = (HttpWebRequest)WebRequest.Create(REST_URL); foreach (string sHeaderName in aHeaders.Keys) { string[] aHeaderValues = aHeaders.GetValueOrDefault(sHeaderName); aRESTTokenCollection.Add(sHeaderName); foreach (String sHeaderValue in aHeaderValues) { aReq.Headers.Add(sHeaderName, sHeaderValue); aRESTTokenCollection.Add(sHeaderValue); } } aRESTTokenCollection.Add(REST_SECRET); aRESTTokenCollection.Sort(StringComparer.Create(new System.Globalization.CultureInfo("en-US"), true)); ArrayList aBytes = new ArrayList(); for (int i = 0; i < aRESTTokenCollection.Count; ++i) { byte[] aHeaderBytes = Encoding.UTF8.GetBytes((String)aRESTTokenCollection[i]); aBytes.AddRange(aHeaderBytes); } byte[] aByteArr = (byte[])aBytes.ToArray(typeof(byte)); byte[] aKeyArr = Encoding.UTF8.GetBytes(REST_SECRET); HMACSHA512 aKeyHMAC = new HMACSHA512(aKeyArr); byte[] aHash = aKeyHMAC.ComputeHash(aByteArr); String sToken = Convert.ToBase64String(aHash); aReq.Headers.Add("x-axw-rest-token", sToken); aReq.KeepAlive = false; aReq.ProtocolVersion = HttpVersion.Version10; aReq.Method = "GET"; HttpWebResponse aResponse = (HttpWebResponse)aReq.GetResponse(); Console.WriteLine("Status: " + aResponse.StatusCode + ", Description: " + aResponse.StatusDescription); System.IO.Stream aResponseStream = aResponse.GetResponseStream(); try { System.IO.StreamReader aStreamReader = new System.IO.StreamReader(aResponseStream); Console.WriteLine("Response: " + aStreamReader.ReadToEnd()); } finally { aResponseStream.Close(); } }
void HandleReadDone(IAsyncResult ar) { if (is_disposed) { return; } int byte_read = image_stream.EndRead(ar); lock (sync_handle) { if (byte_read == 0) { image_stream.Close(); Close(); loading = false; notify_completed = true; } else { try { if (!is_disposed && Write(buffer, (ulong)byte_read)) { image_stream.BeginRead(buffer, 0, count, HandleReadDone, null); } } catch (System.ObjectDisposedException) { } catch (GLib.GException) { } } } GLib.Idle.Add(delegate { //Send the AreaPrepared event if (notify_prepared) { notify_prepared = false; if (thumb != null) { thumb.Dispose(); thumb = null; } EventHandler <AreaPreparedEventArgs> eh = AreaPrepared; if (eh != null) { eh(this, new AreaPreparedEventArgs(false)); } } //Send the AreaUpdated events if (damage != Rectangle.Zero) { EventHandler <AreaUpdatedEventArgs> eh = AreaUpdated; if (eh != null) { eh(this, new AreaUpdatedEventArgs(damage)); } damage = Rectangle.Zero; } //Send the Completed event if (notify_completed) { notify_completed = false; OnCompleted(); } return(false); }); }
private int InitXML(string path, System.Text.Encoding encoding) { XmlDocument xml = new XmlDocument(); System.IO.Stream stream = VirtualFileSystemManager.Instance.FileSystem.OpenFile(path); int count = 0; try { XmlElement root; XmlNodeList list; xml.Load(stream); root = FindRoot(xml); list = root.ChildNodes; DateTime time = DateTime.Now; string label = this.loadingTab; foreach (object j in list) { T item = new T(); XmlElement i; if (j.GetType() != typeof(XmlElement)) { continue; } i = (XmlElement)j; try { ParseXML(root, i, item); if (i.ChildNodes.Count != 0) { ParseNode(i, item); } } catch (Exception ex) { Logger.Log.Error("Error on parsing:" + path); Logger.Log.Error(GetKey(item).ToString()); Logger.Log.Error(ex); } uint key = GetKey(item); if (!items.ContainsKey(key)) { items.Add(key, item); } #if !Web if ((DateTime.Now - time).TotalMilliseconds > 10) { time = DateTime.Now; } #endif count++; } } catch (Exception ex) { Logger.Log.Error("Error on parsing:" + path); Logger.Log.Error(ex.Message); } stream.Close(); xml.RemoveAll(); xml = null; return(count); }
/// <summary> /// Closes the stream (subject to the NoFlush property) /// </summary> public void Close() { stream.Close(); }
/// <summary> /// 发送短信方法 /// </summary> /// <param name="ReceivePhone"></param> /// <param name="MsgContent"></param> /// <param name="SendDate"></param> /// <param name="MsgType"></param> public static Hashtable UnitSms(string ReceivePhone, string MsgContent, DateTime SendDate, string MsgType) { string url = "http://112.65.228.88:8888/sms/Api/Send.do"; Encoding encoding = Encoding.GetEncoding("gb2312"); byte[] bytesToPost = encoding.GetBytes(MakeParams(ReceivePhone, MsgContent, SendDate, MsgType)); string cookieheader = string.Empty; CookieContainer cookieCon = new CookieContainer(); #region 创建HttpWebRequest对象 HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(url); #endregion #region 初始化HtppWebRequest对象 httpRequest.CookieContainer = cookieCon; httpRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2; .NET CLR 1.1.4322; .NET CLR 2.0.50727)"; httpRequest.ContentType = "application/x-www-form-urlencoded"; httpRequest.Method = "POST"; if (cookieheader.Equals(string.Empty)) { cookieheader = httpRequest.CookieContainer.GetCookieHeader(new Uri(url)); } else { httpRequest.CookieContainer.SetCookies(new Uri(url), cookieheader); } #endregion #region 附加Post给服务器的数据到HttpWebRequest对象 httpRequest.ContentLength = bytesToPost.Length; System.IO.Stream requestStream = httpRequest.GetRequestStream(); requestStream.Write(bytesToPost, 0, bytesToPost.Length); requestStream.Close(); #endregion #region 读取服务器返回信息 System.IO.Stream responseStream = httpRequest.GetResponse().GetResponseStream(); string stringResponse = string.Empty; using (System.IO.StreamReader responseReader = new System.IO.StreamReader(responseStream, Encoding.GetEncoding("gb2312"))) { stringResponse = responseReader.ReadToEnd(); } Hashtable ht = new Hashtable(); if (!string.IsNullOrEmpty(stringResponse)) { stringResponse = HttpUtility.UrlDecode(stringResponse); string[] arr = stringResponse.Split('&'); for (int i = 0; i < arr.Length; i++) { string[] arr1 = arr[i].Split('='); if (!ht.Contains(arr1[0])) { ht.Add(arr1[0], arr1[1]); } else { ht[arr1[0]] = ht[arr1[0]] + arr1[1]; } } } responseStream.Close(); #endregion return(ht); }
/// <summary> Open a RIFF STREAM. /// </summary> public virtual int Open(System.IO.Stream stream, int NewMode) { int retcode = DDC_SUCCESS; if (fmode != RFM_UNKNOWN) { retcode = Close(); } if (retcode == DDC_SUCCESS) { switch (NewMode) { case RFM_WRITE: try { //file = SupportClass.RandomAccessFileSupport.CreateRandomAccessFile(Filename, "rw"); file = stream; try { // Write the RIFF header... // We will have to come back later and patch it! sbyte[] br = new sbyte[8]; br[0] = (sbyte) ((SupportClass.URShift(riff_header.ckID, 24)) & 0x000000FF); br[1] = (sbyte) ((SupportClass.URShift(riff_header.ckID, 16)) & 0x000000FF); br[2] = (sbyte) ((SupportClass.URShift(riff_header.ckID, 8)) & 0x000000FF); br[3] = (sbyte) (riff_header.ckID & 0x000000FF); sbyte br4 = (sbyte) ((SupportClass.URShift(riff_header.ckSize, 24)) & 0x000000FF); sbyte br5 = (sbyte) ((SupportClass.URShift(riff_header.ckSize, 16)) & 0x000000FF); sbyte br6 = (sbyte) ((SupportClass.URShift(riff_header.ckSize, 8)) & 0x000000FF); sbyte br7 = (sbyte) (riff_header.ckSize & 0x000000FF); br[4] = br7; br[5] = br6; br[6] = br5; br[7] = br4; file.Write(SupportClass.ToByteArray(br), 0, 8); fmode = RFM_WRITE; } catch (System.IO.IOException ioe) { file.Close(); fmode = RFM_UNKNOWN; } } catch (System.IO.IOException ioe) { fmode = RFM_UNKNOWN; retcode = DDC_FILE_ERROR; } break; case RFM_READ: try { file = stream; //file = SupportClass.RandomAccessFileSupport.CreateRandomAccessFile(Filename, "r"); try { // Try to read the RIFF header... sbyte[] br = new sbyte[8]; SupportClass.ReadInput(file, ref br, 0, 8); fmode = RFM_READ; riff_header.ckID = ((br[0] << 24) & (int) SupportClass.Identity(0xFF000000)) | ((br[1] << 16) & 0x00FF0000) | ((br[2] << 8) & 0x0000FF00) | (br[3] & 0x000000FF); riff_header.ckSize = ((br[4] << 24) & (int) SupportClass.Identity(0xFF000000)) | ((br[5] << 16) & 0x00FF0000) | ((br[6] << 8) & 0x0000FF00) | (br[7] & 0x000000FF); } catch (System.IO.IOException ioe) { file.Close(); fmode = RFM_UNKNOWN; } } catch (System.IO.IOException ioe) { fmode = RFM_UNKNOWN; retcode = DDC_FILE_ERROR; } break; default: retcode = DDC_INVALID_CALL; break; } } return retcode; }
private bool uploadThread_Init() { try { FlagFtp.FtpClient client = new FlagFtp.FtpClient(nc); uploadThread = new System.Threading.Thread(() => { while (fileQueue.Count > 0) { #if !DEBUG try { #endif if (!System.IO.File.Exists(fileQueue.Peek().FullName)) { fileQueue.Dequeue(); continue; } string ObjFile = string.Format(@"ftp://{0}:{1}{2}", ServerAddress, Port, (FilenamePattern.StartsWith("/") ? "" : "/") + FilenamePattern); ObjFile = ObjFile.Replace("%file%", fileQueue.Peek().Name); DateTime time = DateTime.Now; ObjFile = ObjFile.Replace("%year%", time.Year.ToString("0000")); ObjFile = ObjFile.Replace("%month%", time.Month.ToString("00")); ObjFile = ObjFile.Replace("%day%", time.Day.ToString("00")); ObjFile = ObjFile.Replace("%hour%", time.Hour.ToString("00")); ObjFile = ObjFile.Replace("%minute%", time.Minute.ToString("00")); ObjFile = ObjFile.Replace("%second%", time.Second.ToString("00")); ObjFile = ObjFile.Replace("%client_user%", Environment.UserName); ObjFile = ObjFile.Replace("%server_user%", Username); System.Text.RegularExpressions.Regex regEx = new System.Text.RegularExpressions.Regex( @"%random\((\d+)\)%"); System.Text.RegularExpressions.MatchCollection matches = regEx.Matches(ObjFile); foreach (System.Text.RegularExpressions.Match match in matches) { int digit; if (!int.TryParse(match.Groups[1].Value, out digit)) { digit = 100; } Random rand = new Random(); ObjFile = ObjFile.Replace(match.Groups[0].Value, rand.Next(digit).ToString()); } System.Security.Cryptography.MD5CryptoServiceProvider md5 = new System.Security.Cryptography.MD5CryptoServiceProvider(); System.IO.StreamReader md5_streamReader = new System.IO.StreamReader(fileQueue.Peek().FullName); StringBuilder sb = new StringBuilder(); byte[] md5_result = md5.ComputeHash(md5_streamReader.BaseStream); for (int i = 0; i < md5_result.Length; i++) { sb.AppendFormat("{0:x2}", md5_result[i]); } ObjFile = ObjFile.Replace("%md5%", sb.ToString()); md5_streamReader.Close(); try { if (client.FileExists(new Uri(ObjFile))) { if (!System.IO.Directory.Exists(WatchedDir + "\\Failed")) { System.IO.Directory.CreateDirectory(WatchedDir + "\\Failed"); } System.IO.File.Move(fileQueue.Peek().FullName, WatchedDir + "\\Failed"); throw new Exception(string.Format(@"File {0} exists in server!", ObjFile)); } } catch {} System.IO.Stream writer = client.OpenWrite(new Uri(ObjFile)); System.IO.StreamReader reader = new System.IO.StreamReader(fileQueue.Peek().FullName); const int buffer_readsize = 1024 * 32; byte[] buffer = new byte[buffer_readsize]; int buffer_size = 0; do { buffer_size = reader.BaseStream.Read(buffer, 0, buffer_readsize); writer.Write(buffer, 0, buffer_size); } while (buffer_size == buffer_readsize); writer.Close(); reader.Close(); if (!System.IO.Directory.Exists(WatchedDir + "\\Complete")) { System.IO.Directory.CreateDirectory(WatchedDir + "\\Complete"); } System.IO.File.Move(fileQueue.Peek().FullName, WatchedDir + "\\Complete\\" + fileQueue.Peek().Name); fileQueue.Dequeue(); #if !DEBUG } catch (Exception ex) { } #endif } }); } catch (Exception ex) { notifyIcon.BalloonTipIcon = ToolTipIcon.Error; notifyIcon.BalloonTipText = ex.ToString(); notifyIcon.ShowBalloonTip(3000); return(false); } return(true); }
public bool TryReverseGeocoding() { bool isOK = false; XmlTextReader reader = null; System.IO.Stream stream = null; try { StringBuilder for_uri = new StringBuilder(100); for_uri.Append("https://nominatim.openstreetmap.org/reverse?format=xml"); for_uri.Append("&lat="); for_uri.Append(Latitude.ToString(System.Globalization.CultureInfo.GetCultureInfo("en-US"))); for_uri.Append("&lon="); for_uri.Append(Longitude.ToString(System.Globalization.CultureInfo.GetCultureInfo("en-US"))); for_uri.Append("&zoom=18&addressdetails="); for_uri.Append((details_flag == true) ? "1" : "0"); for_uri.Append("&[email protected]"); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(for_uri.ToString()); request.UserAgent = "WhereIsMyPhoto " + Application.ProductVersion.ToString(); request.Timeout = 1000; WebResponse response = request.GetResponse(); stream = response.GetResponseStream(); reader = new XmlTextReader(stream); XmlDocument document = new XmlDocument(); document.Load(reader); XmlNode resultNode = document.GetElementsByTagName("result")[0]; FullInformation = resultNode.InnerText; if (details_flag) { XmlNode addressparts = document.GetElementsByTagName("addressparts")[0]; foreach (XmlNode node in addressparts) { switch (node.Name) { case "house_number": Home = node.InnerText; break; case "road": Street = node.InnerText; break; case "city": City = node.InnerText; break; case "country": Country = node.InnerText; break; } } } // stream.Close(); // reader.Close(); isOK = true; } catch (Exception e) { Console.WriteLine(e.Message); isOK = false; } finally { stream?.Close(); reader?.Close(); } return(isOK); }
/// <summary>Runs the application. Retrives a token from the authentication server, then opens the WebSocket using the token.</summary> public void run() { /* Get local hostname. */ IPAddress hostEntry = Array.Find(Dns.GetHostEntry(Dns.GetHostName()).AddressList, ip => ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork); if (hostEntry != null) { _position = hostEntry.ToString(); } else { _position = "127.0.0.1"; } /* Send an HTTP request to the specified authentication server, containing our username and password. * The token will be used to login on the websocket. */ Console.WriteLine("Sending authentication request...\n"); string url = "https://" + _authHostName + ":" + _authPort + "/getToken"; HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url); webRequest.UserAgent = "CSharpMarketPriceAuthenticationExample"; /* TODO Remove this. It disables certificate validation. */ webRequest.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => { return(true); }; /* Add a cookie container to the request, so that we can get the token from the response cookies. */ webRequest.CookieContainer = new CookieContainer(); try { /* Send username and password in request. */ string postString = "username="******"&password="******"POST"; webRequest.ContentType = "application/x-www-form-urlencoded"; webRequest.ContentLength = postContent.Length; System.IO.Stream requestStream = webRequest.GetRequestStream(); requestStream.Write(postContent, 0, postContent.Length); requestStream.Close(); HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse(); if (webResponse.ContentLength > 0) { /* If there is content in the response, print it. */ /* Format the object string for easier reading. */ dynamic msg = JsonConvert.DeserializeObject(new System.IO.StreamReader(webResponse.GetResponseStream()).ReadToEnd()); string prettyJson = JsonConvert.SerializeObject(msg, Formatting.Indented); Console.WriteLine("RECEIVED:\n{0}\n", prettyJson); } /* Get the token from the cookies. */ Cookie cookie = webResponse.Cookies["AuthToken"]; if (cookie == null) { Console.WriteLine("Authentication failed. Authentication token not found in cookies."); Environment.Exit(1); } _authToken = cookie.Value; /* We have our token. */ Console.WriteLine("Authentication Succeeded. Received AuthToken: {0}\n", _authToken); webResponse.Close(); } catch (WebException e) { /* The request to the authentication server failed, e.g. due to connection failure or HTTP error response. */ if (e.InnerException != null) { Console.WriteLine("Authentication server request failed: {0} -- {1}\n", e.Message.ToString(), e.InnerException.Message.ToString()); } else { Console.WriteLine("Authentication server request failed: {0}", e.Message.ToString()); } Environment.Exit(1); } /* Open a websocket. */ string hostString = "ws://" + _hostName + ":" + _port + "/WebSocket"; Console.Write("Connecting to WebSocket " + hostString + " ..."); _webSocket = new WebSocket(hostString, "tr_json2"); /* Set the token we received from the authentication request. */ _webSocket.SetCookie(new WebSocketSharp.Net.Cookie("AuthToken", _authToken)); _webSocket.SetCookie(new WebSocketSharp.Net.Cookie("AuthPosition", _position)); _webSocket.SetCookie(new WebSocketSharp.Net.Cookie("applicationId", _appId)); _webSocket.OnOpen += onWebSocketOpened; _webSocket.OnError += onWebSocketError; _webSocket.OnClose += onWebSocketClosed; _webSocket.OnMessage += onWebSocketMessage; /* Print any log events (similar to default behavior, but we explicitly indicate it's a logger event). */ _webSocket.Log.Output = (logData, text) => Console.WriteLine("Received Log Event (Level: {0}): {1}\n", logData.Level, logData.Message); _webSocket.Connect(); Thread.Sleep(Timeout.Infinite); }