public override void Initialize() { string path = Path.Combine(TShock.SavePath, "CodeReward1_9.json"); Config = Config.Read(path); if (!File.Exists(path)) { Config.Write(path); } Commands.ChatCommands.Add(new Command(Permissions.codereward, Cmds.functionCmd, "codereward")); Commands.ChatCommands.Add(new Command(Permissions.codereward, Cmds.functionCmd, "crt")); Variables.ALL = Config.ALL; //Events ServerApi.Hooks.ServerChat.Register(this, Chat.onChat); string version = "1.3.0.8 (1.9)"; System.Net.WebClient wc = new System.Net.WebClient(); string webData = wc.DownloadString("http://textuploader.com/al9u6/raw"); if (version != webData) { Console.WriteLine("[CodeReward] New version is available!: " + webData); } System.Timers.Timer timer = new System.Timers.Timer(Variables.ALL.Interval * (60 * 1000)); timer.Elapsed += run; timer.Start(); }
public static CallResponse fetchSoundbytePlayLeaderboard() { string cnts = new System.Net.WebClient().DownloadString("https://burkeblack.tv/api/v1/soundbyte_application/soundbytes/leaderboard"); JObject decoded = JObject.Parse(cnts); CallResponse resp; if ((bool)decoded.SelectToken("success") == true) { JToken leaderboard = decoded.SelectToken("leaderboard"); sbLeaderboardListing[] sbLeaderBoardListings = new sbLeaderboardListing[leaderboard.Count()]; for (int i = 0; i < sbLeaderBoardListings.Length; i++) { int plays = -1; string name = leaderboard[i].SelectToken("name").ToString(); string genre = leaderboard[i].SelectToken("genre").ToString(); string uploaded_by = leaderboard[i].SelectToken("uploaded_by").ToString(); int.TryParse(leaderboard[i].SelectToken("plays").ToString(), out plays); string last_played_by = leaderboard[i].SelectToken("last_played_by").ToString(); sbLeaderBoardListings[i] = new sbLeaderboardListing(name, genre, uploaded_by, plays, last_played_by); } object[] leaderboardAndTotalPlays = new object[2]; leaderboardAndTotalPlays[0] = sbLeaderBoardListings; leaderboardAndTotalPlays[1] = decoded.SelectToken("total_plays").ToString(); resp = new CallResponse(CallResponse.responseType.SUCCESS, leaderboardAndTotalPlays); } else { resp = new CallResponse(CallResponse.responseType.FAILURE, null, decoded.SelectToken("message").ToString()); } return resp; }
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 static void Urldown_DownloadDataCompleted(object sender, System.Net.DownloadStringCompletedEventArgs e) { if (e.Error != null || e.Result.Length <= 0 || e.Cancelled) { return; } var resultstr = e.Result; if (string.IsNullOrEmpty(resultstr)) return; var tag = SearchData.JieXiData(resultstr); if (tag == null) return; if (!string.IsNullOrEmpty(tag.Img)) { using ( var imgdown = new System.Net.WebClient { Encoding = System.Text.Encoding.UTF8, Proxy = PublicStatic.MyProxy }) { imgdown.DownloadDataAsync(new System.Uri(tag.Img), tag); imgdown.DownloadDataCompleted += SearchImg.Imgdown_DownloadDataCompleted; } } }
private void btnSend_Click(object sender, EventArgs e) { using (System.Net.WebClient client = new System.Net.WebClient()) { try { string url = "http://smsc.vianett.no/v3/send.ashx?" + "src=" + textPhoneNumber.Text + "&" + "dst=" + textPhoneNumber.Text + "&" + "msg=" + System.Web.HttpUtility.UrlEncode(textMessage.Text, System.Text.Encoding.GetEncoding("ISO-8859-1")) + "&" + "username="******"&" + "password="******"OK")) MessageBox.Show("Your message has been successfully sent.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information); else MessageBox.Show("Your message was not successfully delivered", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information); } catch (Exception ex) { MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error); } } }
private bool CheckVersion(string lookingFor) { try { using (var wc = new System.Net.WebClient()) { var xDoc = new System.Xml.XmlDocument(); xDoc.Load(@"http://www.sqlcompact.dk/SqlCeToolboxVersions.xml"); string newVersion = xDoc.DocumentElement.Attributes[lookingFor].Value; Version vN = new Version(newVersion); if (vN > Assembly.GetExecutingAssembly().GetName().Version) { return true; } } } catch (Exception ex) { MessageBox.Show(ex.ToString()); } return false; }
private void GetUUIDButton_Click(object sender, EventArgs e) { //If the user does NOT have an internet connection then display a message, otherwise, continue! if (System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable() == false) { MessageBox.Show("Connection failed, make sure you are connected to the internet!"); } else { System.Net.WebClient wc = new System.Net.WebClient(); string webData = wc.DownloadString("https://api.mojang.com/users/profiles/minecraft/" + UsernameBox.Text); //If the webpage does not load or has no strings then say the username was invalid! Otherwise, continue! if (webData == "") { MessageBox.Show("Your username is invalid, please check and retry!"); } else { string[] mojangAPI = webData.Split(new Char[] { ',', ' ' }); mojangAPI[0] = mojangAPI[0].Substring(7); mojangAPI[0] = mojangAPI[0].Remove((mojangAPI[0].Length - 1), 1); UUIDBox.Text = mojangAPI[0]; } } }
public string Retreive(string Url) { System.Net.WebClient _WebClient = new System.Net.WebClient(); string _Result = _WebClient.DownloadString(Url); return _Result; }
static void Main(string[] args) { try { webClient = new System.Net.WebClient(); //check arguments if (args.Length < argCount) { throw new IndexOutOfRangeException(); } //divide the command line arguments into two sets //note that for each set the following index applies: //loc = 0, fname_or_url = 1, xpath = 2, kpath = 3, spath = 4; string[] args1 = args.Take(argCount / 2).ToArray(); string[] args2 = args.Skip(argCount / 2).Take(argCount / 2).ToArray(); IEnumerable<XElement> seq1 = MakeSortedSequence(args1, "_LeftSeq.xml", "LeftSeq"); IEnumerable<XElement> seq2 = MakeSortedSequence(args2, "_RightSeq.xml", "RightSeq"); PerformInnerJoin(seq1, seq2, args1, args2, "_InnerJoin.xml", "InnerJoin"); PerformOuterJoin(seq1, seq2, args1, args2, "_LeftOuterJoin.xml", "LeftOuterJoin"); PerformGroupJoin(seq1, seq2, args1, args2, "_GroupJoin.xml", "GroupJoin"); } catch (Exception e) { Console.Error.WriteLine("*** Exception: {0}", e.Message); Environment.Exit(fail); } }
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); }; }
protected void Page_Load(object sender, EventArgs e) { string siteid = Request["siteid"]; string filename = Request["filename"]; DataSet dsSite = DbHelper.GetSiteData(siteid, ""); string tmpFolder = Server.MapPath("./") + "TempOutput" + "/" + Page.User.Identity.Name + "/"; if (Directory.Exists(tmpFolder)) { string[] files = Directory.GetFiles(tmpFolder); foreach (string file in files) File.Delete(file); } else { Directory.CreateDirectory(tmpFolder); } foreach (DataRow drSite in dsSite.Tables[0].Rows) { string siteUrl = drSite["ZipApiUrl"].ToString() + "getfile.php?filename=" + filename; System.Net.WebClient client = new System.Net.WebClient(); client.DownloadFile(siteUrl, tmpFolder + filename); Func.SaveLocalFile(tmpFolder + filename, "zip", "Mone\\CSV出力"); } }
private static string DownloadString(string uri) { Thread.Sleep(5000); using (var wc = new System.Net.WebClient()) return wc.DownloadString(uri); }
private void installGame() { //download and unpack game try { String filename = installerExe.Substring(0, installerExe.Length - 4); if (!System.IO.Directory.Exists(getDosBoxPath() + "\\" + filename)) { System.Net.WebClient webc = new System.Net.WebClient(); webc.DownloadFile(new Uri("https://gamestream.ml/games/" + installerExe), getDosBoxPath() + installerExe); Process process1 = Process.Start(getDosBoxPath() + installerExe); process1.WaitForExit(); startDosBox(); } else { startDosBox(); } } catch (Exception e) { MessageBox.Show(e.Message); Application.ExitThread(); Application.Exit(); } }
static void Main(string[] args) { //Inkorrekte Argumente if (args.Length != 1) { //Falsche Anzahl der Argumente Console.WriteLine("Benutzung: dhltrack [Delivery-ID]"); } else { //The joy of working with modern languages... string id = args[0]; //Building up the URL... string url = "http://nolp.dhl.de/nextt-online-public/set_identcodes.do?lang=de&idc=" + id; System.Net.WebClient wc = new System.Net.WebClient(); wc.Encoding = UTF8Encoding.UTF8; string htmldata = wc.DownloadString(url); if (htmldata.Contains("<div class=\"error\">")) //DHL gibt bei nicht vorhandener ID den Error in dieser CSS-Klasse heraus. { //Leider nicht vorhanden. Console.WriteLine("Es ist keine Sendung mit der ID " + id + " bekannt!"); } else { //Status der Sendung extrahieren -- evtl. wäre hier ein RegExp besser... string status = htmldata.Split(new[] { "<td class=\"status\">" }, StringSplitOptions.None)[1].Split(new[] { "</td>" }, StringSplitOptions.None)[0].Replace("<div class=\"statusZugestellt\">", "").Replace("</div>", "").Trim(); Console.WriteLine("Status der Sendung mit ID: " + id); Console.WriteLine(status); } } }
public static oEmbedResponse Call(oEmbedOptions options) { if (options == null || string.IsNullOrEmpty(options.Url)) { return null; } oEmbedResponse oEmbedResponse = null; var jsonResponse = string.Empty; var endpoint = BuildUrl(options); try { jsonResponse = new System.Net.WebClient().DownloadString(endpoint); } catch (System.Net.WebException exception) { if (exception.Status != System.Net.WebExceptionStatus.ProtocolError) throw; } if (!string.IsNullOrEmpty(jsonResponse)) oEmbedResponse = new JavaScriptSerializer().Deserialize<oEmbedResponse>(jsonResponse); return oEmbedResponse; }
protected override void ImportMethod() { using (Utils.ProgressBlock progress = new Utils.ProgressBlock(this, STR_IMPORT, STR_DOWNLOAD, 1, 0)) { using (System.IO.TemporaryFile tmp = new System.IO.TemporaryFile(true)) using (System.Net.WebClient wc = new System.Net.WebClient()) { wc.DownloadFile("http://www.globalcaching.eu/service/cachedistance.aspx?country=Netherlands&prefix=GC", tmp.Path); using (var fs = System.IO.File.OpenRead(tmp.Path)) using (ZipInputStream s = new ZipInputStream(fs)) { ZipEntry theEntry = s.GetNextEntry(); byte[] data = new byte[1024]; if (theEntry != null) { StringBuilder sb = new StringBuilder(); while (true) { int size = s.Read(data, 0, data.Length); if (size > 0) { if (sb.Length == 0 && data[0] == 0xEF && size > 2) { sb.Append(System.Text.ASCIIEncoding.UTF8.GetString(data, 3, size - 3)); } else { sb.Append(System.Text.ASCIIEncoding.UTF8.GetString(data, 0, size)); } } else { break; } } XmlDocument doc = new XmlDocument(); doc.LoadXml(sb.ToString()); XmlElement root = doc.DocumentElement; XmlNodeList nl = root.SelectNodes("wp"); if (nl != null) { Core.Geocaches.AddCustomAttribute(CUSTOM_ATTRIBUTE); foreach (XmlNode n in nl) { var gc = Utils.DataAccess.GetGeocache(Core.Geocaches, n.Attributes["code"].InnerText); if (gc != null) { string dist = Utils.Conversion.StringToDouble(n.Attributes["dist"].InnerText).ToString("000.0"); gc.SetCustomAttribute(CUSTOM_ATTRIBUTE, dist); } } } } } } } }
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 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; }
/// <summary> /// Set desktop wallpaper /// </summary> /// <param name="uri">Image filename</param> /// <param name="style">Style of wallpaper</param> public static void Set(Uri uri, Style style) { Stream s = new System.Net.WebClient().OpenRead(uri.ToString()); System.Drawing.Image img = System.Drawing.Image.FromStream(s); Set(img, style); }
public void Set(Uri uri, WallpaperStyle style) { Stream s = new System.Net.WebClient().OpenRead(uri.ToString()); System.Drawing.Image img = System.Drawing.Image.FromStream(s); string tempPath = Path.Combine(Path.GetTempPath(), "wallpaper.bmp"); img.Save(tempPath, System.Drawing.Imaging.ImageFormat.Bmp); RegistryKey key = Registry.CurrentUser.OpenSubKey(@"Control Panel\Desktop", true); if (style == WallpaperStyle.Stretched) { key.SetValue(@"WallpaperStyle", 2.ToString()); key.SetValue(@"TileWallpaper", 0.ToString()); } if (style == WallpaperStyle.Centered) { key.SetValue(@"WallpaperStyle", 1.ToString()); key.SetValue(@"TileWallpaper", 0.ToString()); } if (style == WallpaperStyle.Tiled) { key.SetValue(@"WallpaperStyle", 1.ToString()); key.SetValue(@"TileWallpaper", 1.ToString()); } SystemParametersInfo(SPI_SETDESKWALLPAPER, 0, tempPath, SPIF_UPDATEINIFILE | SPIF_SENDWININICHANGE); }
public void LoadFromUrl(System.Uri url) { using (var stream = new System.Net.WebClient().OpenRead(url)) { base.Image = System.Drawing.Image.FromStream(stream); } }
public static System.Drawing.Image Webimage(this string s) { var wc = new System.Net.WebClient { Proxy = null }; var filesavepath = System.Windows.Forms.Application.StartupPath + "\\" + System.Guid.NewGuid(); wc.DownloadFile(s, filesavepath); return System.Drawing.Image.FromFile(filesavepath); }
/// <summary> /// get an Assembly according to wsdl path. /// </summary> /// <param name="wsdl">wsdl path</param> /// <param name="nameSpace">namespace</param> /// <returns>return Assembly</returns> public static Assembly GetWebServiceAssembly(string wsdl, string nameSpace) { try { System.Net.WebClient webClient = new System.Net.WebClient(); System.IO.Stream webStream = webClient.OpenRead(wsdl); ServiceDescription serviceDescription = ServiceDescription.Read(webStream); ServiceDescriptionImporter serviceDescroptImporter = new ServiceDescriptionImporter(); serviceDescroptImporter.AddServiceDescription(serviceDescription, "", ""); System.CodeDom.CodeNamespace codeNameSpace = new System.CodeDom.CodeNamespace(nameSpace); System.CodeDom.CodeCompileUnit codeCompileUnit = new System.CodeDom.CodeCompileUnit(); codeCompileUnit.Namespaces.Add(codeNameSpace); serviceDescroptImporter.Import(codeNameSpace, codeCompileUnit); System.CodeDom.Compiler.CodeDomProvider codeDom = new Microsoft.CSharp.CSharpCodeProvider(); System.CodeDom.Compiler.CompilerParameters codeParameters = new System.CodeDom.Compiler.CompilerParameters(); codeParameters.GenerateExecutable = false; codeParameters.GenerateInMemory = true; codeParameters.ReferencedAssemblies.Add("System.dll"); codeParameters.ReferencedAssemblies.Add("System.XML.dll"); codeParameters.ReferencedAssemblies.Add("System.Web.Services.dll"); codeParameters.ReferencedAssemblies.Add("System.Data.dll"); System.CodeDom.Compiler.CompilerResults compilerResults = codeDom.CompileAssemblyFromDom(codeParameters, codeCompileUnit); return compilerResults.CompiledAssembly; } catch (Exception ex) { throw ex; } }
public static string Get(string msg) { try { var url = "http://www.aphorismen.de/suche?text=" + Uri.EscapeDataString (msg) + "&autor_quelle=&thema="; var webClient = new System.Net.WebClient (); var s = webClient.DownloadString (url); var doc = new HtmlDocument (); doc.LoadHtml (s); var toftitle = doc.DocumentNode.Descendants ().Where (x => (x.Name == "p" && x.Attributes ["class"] != null && x.Attributes ["class"].Value.Contains ("spruch text"))).ToList (); if (toftitle.Count > 0) { var seed = Convert.ToInt32 (Regex.Match (Guid.NewGuid ().ToString (), @"\d+").Value); var i = new Random (seed).Next (0, toftitle.Count); return toftitle [i].InnerText; } } catch { return null; } return null; }
public CurrentWeather(string fetched, JObject json) { Fetched = fetched; Json = json; if (Json["current_observation"]["temp_f"] != null) { CurrentTempF = (double)Json["current_observation"]["temp_f"]; FeelsLikeF = (double)Json["current_observation"]["feelslike_f"]; CurrentTempC = (double)Json["current_observation"]["temp_c"]; FeelsLikeC = (double)Json["current_observation"]["feelslike_c"]; CityName = (string)Json["current_observation"]["display_location"]["full"]; WindFeel = (string)Json["current_observation"]["wind_string"]; WindSpeedMph = (double)Json["current_observation"]["wind_mph"]; DewPointF = (double)Json["current_observation"]["dewpoint_f"]; ForecastURL = (string)Json["current_observation"]["forecast_url"]; VisibilityMi = (double)Json["current_observation"]["visibility_mi"]; Weather = (string)Json["current_observation"]["weather"]; Elevation = (string)Json["current_observation"]["observation_location"]["elevation"]; ImageName = (string)Json["current_observation"]["icon"]; ImageUrl = (string)Json["current_observation"]["icon_url"]; string folder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); LocalUrl = System.IO.Path.Combine(folder, System.IO.Path.GetRandomFileName()); System.Net.WebClient webClient = new System.Net.WebClient(); webClient.DownloadFile(ImageUrl, LocalUrl); } }
/// <summary> /// 获取双色球开奖结果 /// </summary> /// <returns></returns> private void GetSSQResult() { string ssqResult = ""; try { System.Threading.Thread.Sleep(3000); string html = new System.Net.WebClient().DownloadString("http://www.zhcw.com/kaijiang/index_kj.html"); html = html.Substring(html.IndexOf("<dd>"), html.IndexOf("</dd>") - html.IndexOf("<dd>") + 4).Replace("\r\n",""); string regStr = "<li class=\"qiured\">(.*?)</li> <li class=\"qiured\">(.*?)</li> <li class=\"qiured\">(.*?)</li> <li class=\"qiured\">(.*?)</li> <li class=\"qiured\">(.*?)</li> <li class=\"qiured\">(.*?)</li> <li class=\"qiublud\">(.*?)</li>"; var regex = new System.Text.RegularExpressions.Regex(regStr); System.Text.RegularExpressions.Match m; if ((m = regex.Match(html)).Success && m.Groups.Count == 8) { for (int i = 1; i < 8; i++) { ssqResult += "," + m.Groups[i].Value; } ssqResult = ssqResult.Substring(1); } } catch (Exception ex) { ssqResult = ex.Message; } Response.Write(ssqResult); Response.Flush(); Response.End(); }
internal string GetStringFromURL(string URL) { string cacheKey = string.Format("GetStringFromURL_{0}", URL); var cached = CacheProvider.Get<string>(cacheKey); if (cached != null) { LogProvider.LogMessage("Url.GetStringFromURL : Returning cached result"); return cached; } LogProvider.LogMessage("Url.GetStringFromURL : Cached result unavailable, fetching url content"); string result; try { result = new System.Net.WebClient().DownloadString(URL); } catch (Exception error) { if (LogProvider.HandleAndReturnIfToThrowError(error)) throw; return null; } CacheProvider.Set(result, cacheKey); return result; }
public static bool UpdateFileCached(string remoteUrl, string localUrl, int thresholdInHours = -1) { bool returnValue = false; DateTime threshold; if (thresholdInHours > -1) { threshold = DateTime.Now.AddHours(-thresholdInHours); } else { threshold = DateTime.MinValue; } try { if (!File.Exists(localUrl) || File.GetLastWriteTime(localUrl) < threshold) { Console.WriteLine("we need to re-download " + localUrl); using (System.Net.WebClient webClient = new System.Net.WebClient()) { webClient.DownloadFile(remoteUrl, localUrl); returnValue = true; } } else { returnValue = true; } } catch(Exception e) { Debug.WriteLine(e); returnValue = false; } return returnValue; }
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 SteamPlayerGames GetPlayerGames(string profileName) { var client = new System.Net.WebClient(); string xml = client.DownloadString(string.Format(getPlayerGamesUrl, profileName)); return SteamPlayerGames.Deserialize(xml); }
/// <summary>Runs the <see cref="Downloader"/>.</summary> /// <remarks> /// The download is done in steps: /// <para>Firstly, the appropriate version file in the application data directory is locked, /// so that no other program can use it, until this program ends.</para> /// <para>Then, the version file is downloaded from the remote location.</para> /// <para>If there is already a valid version file in the download directory, /// and the version obtained from the remote version file is equal to the version obtained from the version file in the download directory, /// then the package was already downloaded before. Then we only check that the package file is also present and that it has the appropriate hash sum.</para> /// <para>Else, if the version obtained from the remote version file is higher than the program's current version, /// we download the package file from the remote location.</para> /// </remarks> public void Run() { if (!Directory.Exists(_storagePath)) { Directory.CreateDirectory(_storagePath); SetDownloadDirectoryAccessRights(_storagePath); } var versionFileFullName = Path.Combine(_storagePath, PackageInfo.VersionFileName); using (var fs = new FileStream(versionFileFullName, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None)) { fs.Seek(0, SeekOrigin.Begin); var alreadyDownloadedVersion = PackageInfo.GetPresentDownloadedPackage(fs, _storagePath); fs.Seek(0, SeekOrigin.Begin); using (var webClient = new System.Net.WebClient()) { Console.Write("Starting to download version file ..."); var versionData = webClient.DownloadData(_downloadURL + PackageInfo.VersionFileName); Console.WriteLine(" ok! ({0} bytes downloaded)", versionData.Length); // we leave the file open, thus no other process can access it var parsedVersions = PackageInfo.FromStream(new MemoryStream(versionData)); fs.Write(versionData, 0, versionData.Length); fs.Flush(); // write the new version to disc in order to change the write date // from all parsed versions, choose that one that matches the requirements var parsedVersion = PackageInfo.GetHighestVersion(parsedVersions); if (null != parsedVersion) { Console.WriteLine("The remote package version is: {0}", parsedVersion.Version); } else { Console.WriteLine("This computer does not match the requirements of any package. The version file contains {0} packages.", parsedVersions.Length); return; } if (Comparer <Version> .Default.Compare(parsedVersion.Version, _currentVersion) > 0) // if the remote version is higher than the currently installed Altaxo version { Console.Write("Cleaning download directory ..."); CleanDirectory(versionFileFullName); // Clean old downloaded files from the directory Console.WriteLine(" ok!"); var packageUrl = _downloadURL + PackageInfo.GetPackageFileName(parsedVersion.Version); var packageFileName = Path.Combine(_storagePath, PackageInfo.GetPackageFileName(parsedVersion.Version)); Console.WriteLine("Starting download of package file ..."); webClient.DownloadProgressChanged += EhDownloadOfPackageFileProgressChanged; webClient.DownloadFileCompleted += EhDownloadOfPackageFileCompleted; _isDownloadOfPackageCompleted = false; webClient.DownloadFileAsync(new Uri(packageUrl), packageFileName);// download the package asynchronously to get progress messages for (; !_isDownloadOfPackageCompleted;) { System.Threading.Thread.Sleep(250); } webClient.DownloadProgressChanged -= EhDownloadOfPackageFileProgressChanged; webClient.DownloadFileCompleted -= EhDownloadOfPackageFileCompleted; Console.WriteLine("Download finished!"); // make at least the test for the right length var fileInfo = new FileInfo(packageFileName); if (fileInfo.Length != parsedVersion.FileLength) { Console.WriteLine("Downloaded file length ({0}) differs from length in VersionInfo.txt {1}, thus the downloaded file will be deleted!", fileInfo.Length, parsedVersion.FileLength); fileInfo.Delete(); } else { Console.WriteLine("Test file length of downloaded package file ... ok!"); } } } } }
public void Execute(DriverManager driver, TestStep step) { long order = step.Order; string wait = step.Wait != null ? step.Wait : ""; List <TestStep> steps = new List <TestStep>(); IWebElement ele; string data = ""; string xpath = ""; int count = 0; //List of necessary data List <string> activeTrainJobConfigIDArray = new List <string>(); List <string> inactiveTrainJobConfigIDArray = new List <string>(); List <string> activeTrainJobConfigTypeIDArray = new List <string>(); List <string> inactiveTrainJobConfigTypeIDArray = new List <string>(); List <string> activeJobSettingsArray = new List <string>(); List <string> inactiveJobSettingsArray = new List <string>(); List <string> activeTriggerTrainArray = new List <string>(); List <string> inactiveTriggerTrainArray = new List <string>(); List <string> activeTrainConfigIDArray = new List <string>(); List <string> inactiveTrainConfigIDArray = new List <string>(); List <string> activeNameArray = new List <string>(); List <string> inactiveNameArray = new List <string>(); //Fetching json file JObject json = new JObject(); using (var webClient = new System.Net.WebClient()) { var jsonString = webClient.DownloadString("http://recspublicdev-1454793804.us-east-2.elb.amazonaws.com/v2/training/job/configuration"); json = JObject.Parse(jsonString); } //Getting data foreach (JToken x in json["result"]) { if (x["ConfigurationStatus"].ToString().Equals("active")) { //Active TrainingJobConfigurationID if (x["TrainingJobConfigurationID"] != null) { activeTrainJobConfigIDArray.Add(x["TrainingJobConfigurationID"].ToString()); } else { activeTrainJobConfigIDArray.Add(""); } //Active Name if (x["Name"] != null) { activeNameArray.Add(x["Name"].ToString()); } else { activeNameArray.Add(""); } //Active TrainingJobConfigurationTypeID if (x["TrainingJobConfigurationTypeID"] != null) { activeTrainJobConfigTypeIDArray.Add(x["TrainingJobConfigurationTypeID"].ToString()); } else { activeTrainJobConfigTypeIDArray.Add(""); } //Ative JobSettings if (x["JobSettings"] != null) { activeJobSettingsArray.Add(x["JobSettings"].ToString()); } else { activeJobSettingsArray.Add(""); } //Active TriggerTrainingJobConfigurationID if (x["TriggerTrainingJobConfigurationID"] != null) { activeTriggerTrainArray.Add(x["TriggerTrainingJobConfigurationID"].ToString()); } else { activeTriggerTrainArray.Add(""); } //Active TrainingConfigurationID if (x["TrainingConfigurationID"] != null) { activeTrainConfigIDArray.Add(x["TrainingConfigurationID"].ToString()); } else { activeTrainConfigIDArray.Add(""); } } } Dictionary <string, string[]> dataDictionary = new Dictionary <string, string[]>(); dataDictionary.Add("activeTrainJobConfigIDArray", activeTrainJobConfigIDArray.ToArray()); dataDictionary.Add("activeNameArray", activeNameArray.ToArray()); dataDictionary.Add("activeTrainJobConfigTypeIDArray", activeTrainJobConfigTypeIDArray.ToArray()); dataDictionary.Add("activeJobSettingsArray", activeJobSettingsArray.ToArray()); dataDictionary.Add("activeTriggerTrainArray", activeTriggerTrainArray.ToArray()); dataDictionary.Add("activeTrainConfigIDArray", activeTrainConfigIDArray.ToArray()); VerifyError err = new VerifyError(); ReadOnlyCollection <IWebElement> elements; if (step.Name.Equals("Check Training Job ID")) { string[] id = dataDictionary["activeTrainJobConfigIDArray"]; elements = driver.FindElements("xpath", "/html/body/div/main/div/div[2]/table/tbody/tr/td[1]"); if (elements.Count > 0) { for (int i = 0; i < elements.Count; i++) { if (elements.ElementAt(i).GetAttribute("innerText").Equals(id[i])) { log.Info("Match! " + "Expected: " + id[i] + " Actual: " + elements.ElementAt(i).GetAttribute("innerText")); } else { err.CreateVerificationError(step, "Expected Training Job ID: " + id[i], "Actual Training Job ID: " + elements.ElementAt(i).GetAttribute("innerText")); } } } else { log.Error("Can't find Training Job ID values"); } } else if (step.Name.Equals("Check Training Name")) { string[] id = dataDictionary["activeNameArray"]; elements = driver.FindElements("xpath", "/html/body/div/main/div/div[2]/table/tbody/tr/td[2]"); if (elements.Count > 0) { for (int i = 0; i < elements.Count; i++) { if (elements.ElementAt(i).GetAttribute("innerText").Equals(id[i])) { log.Info("Match! " + "Expected: " + id[i] + " Actual: " + elements.ElementAt(i).GetAttribute("innerText")); } else { err.CreateVerificationError(step, "Expected Training Job Name: " + id[i], "Actual Training Job Name: " + elements.ElementAt(i).GetAttribute("innerText")); } } } else { log.Error("Can't find Training Job Name values"); } } else if (step.Name.Equals("Check Training Configuration ID")) { string[] id = dataDictionary["activeTrainConfigIDArray"]; elements = driver.FindElements("xpath", "/html/body/div/main/div[4]/div[2]/span"); if (elements.Count > 0) { for (int i = 0; i < elements.Count; i++) { if (elements.ElementAt(i).GetAttribute("innerText").Equals(id[i])) { log.Info("Match! " + "Expected: " + id[i] + " Actual: " + elements.ElementAt(i).GetAttribute("innerText")); } else { err.CreateVerificationError(step, "Expected Training Config ID: " + id[i], "Actual Training Config ID: " + elements.ElementAt(i).GetAttribute("innerText")); } } } else { log.Error("Can't find Training Job Name values"); } } else if (step.Name.Equals("Check Trigger Training Job Config ID")) { string[] id = dataDictionary["activeTriggerTrainArray"]; for (int i = 0; i < id.Length; i++) { steps.Add(new TestStep(order, "Click Training Job with ID: " + dataDictionary["activeTrainJobConfigIDArray"][i], "", "click", "xpath", "/html/body/div/main/div/div[2]/table/tbody/tr/td[1][1][.='" + dataDictionary["activeTrainJobConfigIDArray"][i] + "']/a", wait)); TestRunner.RunTestSteps(driver, null, steps); steps.Clear(); elements = driver.FindElements("xpath", "/html/body/div/main/div/div[3]/div[5]/div/div[3]"); if (elements.Count > 0) { if (elements.ElementAt(i).GetAttribute("innerText").Equals(id[i])) { log.Info("Match! " + "Expected: " + id[i] + " Actual: " + elements.ElementAt(i).GetAttribute("innerText")); } else { err.CreateVerificationError(step, "Expected Trigger Training Job ID: " + id[i], "Actual Trigger Training Job ID: " + elements.ElementAt(i).GetAttribute("innerText")); } } else { log.Error("Can't find Trigger Training Job ID values"); } } } }
private static CompilerResults CompileDll() { Console.WriteLine("Generating new DLL"); var csprojPath = @"..\BattleSharpController\"; if (!File.Exists(csprojPath + "BattleSharpController.csproj")) { Console.WriteLine("Getting latest version info from Github"); System.Net.WebClient wc = new System.Net.WebClient(); string hash = wc.DownloadString("https://github.com/shalzuth/BattleSharp"); string hashSearch = "\"commit-tease-sha\" href=\"/shalzuth/BattleSharp/commit/"; hash = hash.Substring(hash.IndexOf(hashSearch) + hashSearch.Length, 7); string hashFile = @".\BattleSharp-master\hash.txt"; csprojPath = @".\BattleSharp-master\BattleSharpController"; if (File.Exists(hashFile)) { if (hash != File.ReadAllText(hashFile)) { Console.WriteLine("Later version exists, removing existing version"); Directory.Delete(@".\BattleSharp-master", true); } } if (!File.Exists(hashFile)) { Console.WriteLine("Downloading latest version"); wc.DownloadFile("https://github.com/shalzuth/BattleSharp/archive/master.zip", "BattleSharpSource.zip"); using (var archive = ZipFile.OpenRead("BattleSharpSource.zip")) { archive.ExtractToDirectory(@".\"); } File.WriteAllText(hashFile, hash); } } var randString = "aa" + Guid.NewGuid().ToString().Substring(0, 8); var codeProvider = new CSharpCodeProvider(); var compilerParameters = new CompilerParameters { GenerateExecutable = false, #if DEBUG IncludeDebugInformation = true, #endif GenerateInMemory = false, OutputAssembly = randString + ".dll" }; compilerParameters.ReferencedAssemblies.Add("mscorlib.dll"); compilerParameters.ReferencedAssemblies.Add(gamePath + "System.dll"); compilerParameters.ReferencedAssemblies.Add(gamePath + "System.Core.dll"); // not sure which to use... prefer Linq... compilerParameters.ReferencedAssemblies.Add("System.Drawing.dll"); compilerParameters.ReferencedAssemblies.Add("System.Windows.Forms.dll"); compilerParameters.ReferencedAssemblies.Add(gamePath + "UnityEngine.dll"); compilerParameters.ReferencedAssemblies.Add(gamePath + "UnityEngine.UI.dll"); compilerParameters.ReferencedAssemblies.Add(gamePath + "UnityContent.dll"); compilerParameters.ReferencedAssemblies.Add(gamePath + "MergedShared.dll"); compilerParameters.ReferencedAssemblies.Add(gamePath + "MergedUnity.dll"); var sourceFiles = Directory.GetFiles(csprojPath, "*.cs", SearchOption.AllDirectories); var sources = new List <String>(); foreach (var sourceFile in sourceFiles) { var source = File.ReadAllText(sourceFile); source = source.Replace("BattleSharpControllerGenericNamespace", randString); sources.Add(source); } Console.WriteLine("Compiling DLL"); var result = codeProvider.CompileAssemblyFromSource(compilerParameters, sources.ToArray()); return(result); }
public string download_and_install(string DriverPath) { string extract_to = DriverPath; object path; //get value of chrome from registry path = Registry.GetValue(@"HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\App Paths\chrome.exe", "", null); if (path != null) { //read exact version of chrome browser from registry value string chrome_browser_vers; chrome_browser_vers = FileVersionInfo.GetVersionInfo(path.ToString()).FileVersion; //get major version of chrome browser int pos = chrome_browser_vers.LastIndexOf('.') + 1; string major_browser = chrome_browser_vers.Substring(0, pos - 1); //read version of chrome driver associated with major browser version System.Net.WebClient wc = new System.Net.WebClient(); string associated_driver_vers = wc.DownloadString("https://chromedriver.storage.googleapis.com/LATEST_RELEASE_" + major_browser); //check if associated browser version is already installed bool download = true; if (System.IO.File.Exists(extract_to + "\\chromedriver.exe")) { System.IO.File.Delete(extract_to + "\\chromedriver.exe"); //downloaded chromedriver has no version info. In the future, save file with version # and compare version of currently installed driver //string current_driver_vers = DriverVersion(extract_to + "\\chromedriver.exe"); //if (current_driver_vers == associated_driver_vers) //{ // download = false; //} } if (download == true) { string fname = associated_driver_vers + "/chromedriver_win32.zip"; var jsonstr = wc.DownloadString("https://www.googleapis.com/storage/v1/b/chromedriver/o"); //get mediaLink from JSON object JObject json = JObject.Parse(jsonstr); var media_list = (from p in json["items"] select(string) p["mediaLink"]).ToList(); var names_list = (from p in json["items"] select(string) p["name"]).ToList(); int media_index = names_list.FindIndex(a => a == fname); string mediaLink = media_list[media_index]; //download associated driver from respective media link string remoteUri = mediaLink; string zipfileName = extract_to + "\\chromedriver_win32.zip"; // Create a new WebClient instance. using (System.Net.WebClient myWebClient = new System.Net.WebClient()) { string myStringWebResource = remoteUri; // Download the Web resource and save it into the current filesystem folder. myWebClient.DownloadFile(myStringWebResource, zipfileName); } ZipFile.ExtractToDirectory(zipfileName, extract_to); System.IO.File.Delete(zipfileName); } return(extract_to); } else { throw new System.Exception("Chrome is not installed on this machine."); } }
public static void StartTimer() { if (tmr.Enabled || timerRenable.Enabled) { return; } stop = false; timerRenable.Interval = 60000; timerRenable.Tick += (snd, obj) => { tmr.Enabled = true; timerRenable.Enabled = false; }; tmr.Interval = 3000; tmr.Tick += (snd, obj) => { //if (MainV2.comPort == null || !MainV2.comPort.BaseStream.IsOpen) return; if (MainV2.comPort.MAV == null || MainV2.comPort.MAV.cs == null) { return; } if (MainV2.comPort.MAV.cs.Location == null) { return; } if (MainV2.comPort.MAV.cs.Location.Lat == 0 && MainV2.comPort.MAV.cs.Location.Lng == 0) { return; } //if (MainV2.comPort.MAV.cs.gpsstatus <= 3) return; System.ComponentModel.BackgroundWorker bgWorker = new System.ComponentModel.BackgroundWorker(); bool error = false; tmr.Enabled = timerRenable.Enabled = false; bgWorker.DoWork += (sender, obj2) => { try { //http://public-api.adsbexchange.com/VirtualRadar/AircraftList.json?lat=33.433638&lng=-112.008113&fDstL=0&fDstU=37.04 using (var client = new System.Net.WebClient()) { string request = string.Format("http://public-api.adsbexchange.com/VirtualRadar/AircraftList.json?lat={0}&lng={1}&fDstL=0&fDstU=37.04", MainV2.comPort.MAV.cs.Location.Lat, MainV2.comPort.MAV.cs.Location.Lng); if (!string.IsNullOrEmpty(ldv)) { request = string.Format("http://public-api.adsbexchange.com/VirtualRadar/AircraftList.json?lat={0}&lng={1}&fDstL=0&fDstU=37.04&ldv={2}", MainV2.comPort.MAV.cs.Location.Lat, MainV2.comPort.MAV.cs.Location.Lng, ldv); } var json = client.DownloadString(request); var serializer = new System.Web.Script.Serialization.JavaScriptSerializer(); RootObject adsbexchange = serializer.Deserialize <RootObject>(json); // TODO: do something with the model //System.Diagnostics.Debug.WriteLine("Found " + adsbexchange.acList.Count + " aircraft within 20nm"); if (adsbexchange == null) { return; } if (!string.IsNullOrEmpty(adsbexchange.lastDv)) { ldv = adsbexchange.lastDv; } lock (MainV2.instance.adsbPlanes) { float multi = Settings.Instance["distunits"] == "Feet" ? 3.28084f : 1f; foreach (AcList vehicle in adsbexchange.acList) { string id = vehicle.Id.ToString(); //vehicle alt is always feet, if set to meters change //GAlt is altitude adjusted for local air pressure PointLatLngAlt vehicleplla = new PointLatLngAlt(vehicle.Lat, vehicle.Long, vehicle.GAlt * 3.2808399f); double distance = MainV2.comPort.MAV.cs.Location.GetDistance(vehicleplla) * 0.000539957; double altsep = vehicleplla.Alt - (MainV2.comPort.MAV.cs.altasl * multi); if (MainV2.instance.adsbPlanes.ContainsKey(id)) { // update existing MainV2.instance.adsbPlanes[id].Lat = vehicle.Lat; MainV2.instance.adsbPlanes[id].Lng = vehicle.Long; MainV2.instance.adsbPlanes[id].Alt = vehicleplla.Alt; MainV2.instance.adsbPlanes[id].Heading = (float)vehicle.Trak; MainV2.instance.adsbPlanes[id].Time = DateTime.Now; MainV2.instance.adsbPlanes[id].CallSign = vehicle.Call; MainV2.instance.adsbPlanes[id].Tag = vehicle.Icao; // + Environment.NewLine + species + "/" + vehicle.Call + Environment.NewLine + vehicle.Mdl; MainV2.instance.adsbPlanes[id].Vsi = vehicle.Vsi; MainV2.instance.adsbPlanes[id].Species = (adsb.ADSBSpecies)vehicle.Species; MainV2.instance.adsbPlanes[id].type = vehicle.Type; } else { // create new plane MainV2.instance.adsbPlanes[id] = new adsb.PointLatLngAltHdg(vehicle.Lat, vehicle.Long, vehicleplla.Alt, (float)vehicle.Trak, id, DateTime.Now) { CallSign = vehicle.Call, Tag = vehicle.Icao, DisplayICAO = true, Vsi = vehicle.Vsi, Species = (adsb.ADSBSpecies)vehicle.Species, type = vehicle.Type }; } if (distance <= 2 && altsep <= 152.4 && altsep >= -152.4) //closer than 2NM and verticle seperation <= 500 feet { MainV2.instance.adsbPlanes[id].ThreatLevel = MAVLink.MAV_COLLISION_THREAT_LEVEL.HIGH; } else if (distance <= 5 && altsep <= 457.2 && altsep >= -457.2) //greater than 2NM but less than 5NM and verticle seperation <= 1500 feet { MainV2.instance.adsbPlanes[id].ThreatLevel = MAVLink.MAV_COLLISION_THREAT_LEVEL.LOW; } else { MainV2.instance.adsbPlanes[id].ThreatLevel = MAVLink.MAV_COLLISION_THREAT_LEVEL.NONE; } try { //send adsb to mav if (MainV2.comPort.BaseStream.IsOpen) { MAVLink.mavlink_adsb_vehicle_t packet = new MAVLink.mavlink_adsb_vehicle_t(); packet.altitude = (int)(MainV2.instance.adsbPlanes[id].Alt * 1000); packet.altitude_type = (byte)MAVLink.ADSB_ALTITUDE_TYPE.GEOMETRIC; packet.callsign = ASCIIEncoding.ASCII.GetBytes(MainV2.instance.adsbPlanes[id].CallSign == null ? MainV2.instance.adsbPlanes[id].Tag : MainV2.instance.adsbPlanes[id].CallSign); packet.emitter_type = (byte)MAVLink.ADSB_EMITTER_TYPE.NO_INFO; packet.heading = (ushort)(MainV2.instance.adsbPlanes[id].Heading * 100); packet.lat = (int)(MainV2.instance.adsbPlanes[id].Lat * 1e7); packet.lon = (int)(MainV2.instance.adsbPlanes[id].Lng * 1e7); packet.ICAO_address = uint.Parse(id, System.Globalization.NumberStyles.HexNumber); packet.flags = (ushort)(MAVLink.ADSB_FLAGS.VALID_ALTITUDE | MAVLink.ADSB_FLAGS.VALID_COORDS | MAVLink.ADSB_FLAGS.VALID_HEADING | MAVLink.ADSB_FLAGS.VALID_CALLSIGN); //send to current connected MainV2.comPort.sendPacket(packet, MainV2.comPort.MAV.sysid, MainV2.comPort.MAV.compid); } } catch { } } foreach (var key in MainV2.instance.adsbPlanes.Keys) { adsb.PointLatLngAltHdg tmp; if (!adsbexchange.acList.Any(x => x.Id.ToString() == key && x.Gnd == false)) { MainV2.instance.adsbPlanes.TryRemove(key, out tmp); } } } } } catch (System.Net.WebException webException) { error = true; timerRenable.Enabled = true; } catch { } }; if (!error && !stop) { tmr.Enabled = true; } bgWorker.RunWorkerAsync(); }; tmr.Enabled = true; }
/// <summary> /// Check for Updates with GitHub /// </summary> static void CheckForUpdate() { var fileContent = string.Empty; EditorUtility.DisplayProgressBar("VSCode", "Checking for updates ...", 0.5f); // Because were not a runtime framework, lets just use the simplest way of doing this try { using (var webClient = new System.Net.WebClient()) { fileContent = webClient.DownloadString("https://raw.githubusercontent.com/dotBunny/VSCode/master/Plugins/Editor/VSCode.cs"); } } 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(); } // Set the last update time LastUpdate = DateTime.Now; // Fix for oddity in downlo if (fileContent.Substring(0, 2) != "/*") { int startPosition = fileContent.IndexOf("/*", StringComparison.CurrentCultureIgnoreCase); // Jump over junk characters fileContent = fileContent.Substring(startPosition); } string[] fileExploded = fileContent.Split('\n'); if (fileExploded.Length > 7) { float github = Version; if (float.TryParse(fileExploded[6].Replace("*", "").Trim(), out github)) { GitHubVersion = github; } if (github > Version) { var GUIDs = AssetDatabase.FindAssets("t:Script VSCode"); var path = Application.dataPath.Substring(0, Application.dataPath.Length - "/Assets".Length) + System.IO.Path.DirectorySeparatorChar + AssetDatabase.GUIDToAssetPath(GUIDs[0]).Replace('/', System.IO.Path.DirectorySeparatorChar); if (EditorUtility.DisplayDialog("VSCode Update", "A newer version of the VSCode plugin is available, would you like to update your version?", "Yes", "No")) { // Always make sure the file is writable System.IO.FileInfo fileInfo = new System.IO.FileInfo(path); fileInfo.IsReadOnly = false; // Write update file File.WriteAllText(path, fileContent); // Force update on text file AssetDatabase.ImportAsset(AssetDatabase.GUIDToAssetPath(GUIDs[0]), ImportAssetOptions.ForceUpdate); } } } }
void demoButton_Click(object sender, EventArgs e) { try { if (Commons.IsNullOrEmpty(dxErrorProvider1, this.mailGroupControl.Controls)) { return; } else { dxErrorProvider1.ClearErrors(); } if (!Mail.IsAddressValid(this.mailTextEdit.Text)) { dxErrorProvider1.SetError(this.mailTextEdit, L.MailGecersiz); return; } string mesaj = BAYMYO.UI.FileIO.ReadText(Commons.AppFilePath + "DL.dat") .Replace("{COMPANY}", firmaAdiTextEdit.Text.Trim()) .Replace("{PHONE}", telefonTextEdit.Text) .Replace("{MAIL}", mailTextEdit.Text) .Replace("{VK}", validateKeyText.Text) .Replace("{PV}", productVersionText.Text); Commons.Loading("License downloading .. ."); Application.DoEvents(); using (System.Net.WebClient cln = new System.Net.WebClient()) { System.IO.Stream s = cln.OpenRead(string.Format("http://service.baymyo.com/license.ashx?key={0}&v={1}", validateKeyText.Text, productVersionText.Text)); bool baymyoMail = Mail.SendBaymyo(this.mailTextEdit.Text, this.firmaAdiTextEdit.Text, "Demo License! Easy Supply Application.", mesaj + "<br/><br/> * Aynı mail SonayNet'de gitti!"); bool sonayMail = Mail.SendSonay(this.mailTextEdit.Text, this.firmaAdiTextEdit.Text, "Demo License! Easy Supply Application.", mesaj + "<br/><br/> * Aynı mail baymyo yazılma'da gitti!"); if ((baymyoMail || sonayMail) & s != null) { this.telefonTextEdit.Text = string.Empty; this.firmaAdiTextEdit.Text = string.Empty; this.mailTextEdit.Text = string.Empty; if (!System.IO.File.Exists(Commons.LicenseKeyFile)) { BAYMYO.UI.FileIO.CreateDirectory(Commons.FolderPath); cln.DownloadFile(string.Format("http://service.baymyo.com/keys/{0}-{1}.zip", validateKeyText.Text, productVersionText.Text.Replace(".", "-")), Commons.LicenseKeyFile); Commons.IsLicenseLoad = true; if (Commons.ValidateApplication()) { this.DialogResult = DialogResult.OK; } else { MessageBox.Show(L.LisansGecersiz, "License Warning"); } } else { MessageBox.Show("Şuan sisteminizde bir adet lisans dosyası bulunmaktadır.", "Info"); } } else { MessageBox.Show("Lisans dosyası indirilemiyor lütfen internet bağlantınızı yada proxy ayarlarınızı kontrol ediniz.", "Warning"); } } } catch (Exception) { MessageBox.Show(Commons.GetErrorCode("FTL", 4) + " DEMO LICENSE ERROR!", "Warning"); } finally { Commons.Loaded(); } }
/// <summary> /// This is the method that actually does the work. /// </summary> /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param> protected override void SolveInstance(IGH_DataAccess DA) { List <Curve> boundary = new List <Curve>(); DA.GetDataList(0, boundary); int zoom = -1; DA.GetData(1, ref zoom); string filePath = ""; DA.GetData(2, ref filePath); if (!filePath.EndsWith(@"\")) { filePath = filePath + @"\"; } string prefix = ""; DA.GetData(3, ref prefix); if (prefix == "") { prefix = slippySource; } string URL = slippyURL; //DA.GetData<string>(4, ref URL); string userAgent = ""; DA.GetData(4, ref userAgent); bool run = false; DA.GetData <bool>("Run", ref run); GH_Structure <GH_String> mapList = new GH_Structure <GH_String>(); GH_Structure <GH_Rectangle> imgFrame = new GH_Structure <GH_Rectangle>(); GH_Structure <GH_String> tCount = new GH_Structure <GH_String>(); for (int i = 0; i < boundary.Count; i++) { GH_Path path = new GH_Path(i); int tileTotalCount = 0; int tileDownloadedCount = 0; ///Get image frame for given boundary and make sure it's valid if (!boundary[i].GetBoundingBox(true).IsValid) { AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Boundary is not valid."); return; } BoundingBox boundaryBox = boundary[i].GetBoundingBox(true); ///TODO: look into scaling boundary to get buffer tiles ///file path for final image string imgPath = filePath + prefix + "_" + i + ".jpg"; ///location of final image file mapList.Append(new GH_String(imgPath), path); ///create cache folder for images string cacheLoc = filePath + @"HeronCache\"; List <string> cachefilePaths = new List <string>(); if (!Directory.Exists(cacheLoc)) { Directory.CreateDirectory(cacheLoc); } ///tile bounding box array List <Point3d> boxPtList = new List <Point3d>(); ///get the tile coordinates for all tiles within boundary var ranges = Convert.GetTileRange(boundaryBox, zoom); List <List <int> > tileList = new List <List <int> >(); var x_range = ranges.XRange; var y_range = ranges.YRange; if (x_range.Length > 100 || y_range.Length > 100) { AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "This tile range is too big (more than 100 tiles in the x or y direction). Check your units."); return; } ///cycle through tiles to get bounding box for (int y = (int)y_range.Min; y <= y_range.Max; y++) { for (int x = (int)x_range.Min; x <= x_range.Max; x++) { ///add bounding box of tile to list boxPtList.AddRange(Convert.GetTileAsPolygon(zoom, y, x).ToList()); cachefilePaths.Add(cacheLoc + slippySource.Replace(" ", "") + zoom + "-" + x + "-" + y + ".jpg"); tileTotalCount = tileTotalCount + 1; } } tCount.Insert(new GH_String(tileTotalCount + " tiles (" + tileDownloadedCount + " downloaded / " + (tileTotalCount - tileDownloadedCount) + " cached)"), path, 0); ///bounding box of tile boundaries BoundingBox bbox = new BoundingBox(boxPtList); var rect = BBoxToRect(bbox); imgFrame.Append(new GH_Rectangle(rect), path); AddPreviewItem(imgPath, boundary[i], rect); ///tile range as string for (de)serialization of TileCacheMeta string tileRangeString = zoom.ToString() + x_range[0].ToString() + y_range[0].ToString() + x_range[1].ToString() + y_range[1].ToString(); ///check if the existing final image already covers the boundary. ///if so, no need to download more or reassemble the cached tiles. if ((TileCacheMeta == tileRangeString) && Convert.CheckCacheImagesExist(cachefilePaths)) { if (File.Exists(imgPath)) { using (Bitmap imageT = new Bitmap(imgPath)) { ///getting commments currently only working for JPG ///TODO: get this to work for any image type or ///find another way to check if the cached image covers the boundary. string imgComment = imageT.GetCommentsFromJPG(); imageT.Dispose(); ///check to see if tilerange in comments matches current tilerange if (imgComment == (slippySource.Replace(" ", "") + tileRangeString)) { AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Using existing image."); continue; } } } } ///Query Slippy URL ///download all tiles within boundary ///merge tiles into one bitmap ///API to query ///Do the work of assembling image ///setup final image container bitmap int fImageW = ((int)x_range.Length + 1) * 256; int fImageH = ((int)y_range.Length + 1) * 256; Bitmap finalImage = new Bitmap(fImageW, fImageH); int imgPosW = 0; int imgPosH = 0; if (run == true) { using (Graphics g = Graphics.FromImage(finalImage)) { g.Clear(Color.Black); for (int y = (int)y_range.Min; y <= (int)y_range.Max; y++) { for (int x = (int)x_range.Min; x <= (int)x_range.Max; x++) { //create tileCache name string tileCache = slippySource.Replace(" ", "") + zoom + x + y + ".jpg"; string tileCacheLoc = cacheLoc + tileCache; //check cache folder to see if tile image exists locally if (File.Exists(tileCacheLoc)) { Bitmap tmpImage = new Bitmap(Image.FromFile(tileCacheLoc)); ///add tmp image to final g.DrawImage(tmpImage, imgPosW * 256, imgPosH * 256); tmpImage.Dispose(); } else { tileList.Add(new List <int> { zoom, y, x }); string urlAuth = Convert.GetZoomURL(x, y, zoom, slippyURL); System.Net.WebClient client = new System.Net.WebClient(); ///insert header if required client.Headers.Add("user-agent", userAgent); client.DownloadFile(urlAuth, tileCacheLoc); Bitmap tmpImage = new Bitmap(Image.FromFile(tileCacheLoc)); client.Dispose(); //add tmp image to final g.DrawImage(tmpImage, imgPosW * 256, imgPosH * 256); tmpImage.Dispose(); tileDownloadedCount = tileDownloadedCount + 1; } //increment x insert position, goes left to right imgPosW++; } //increment y insert position, goes top to bottom imgPosH++; imgPosW = 0; } //garbage collection g.Dispose(); //add tile range meta data to image comments finalImage.AddCommentsToJPG(slippySource.Replace(" ", "") + tileRangeString); //save the image finalImage.Save(imgPath, System.Drawing.Imaging.ImageFormat.Jpeg); } } //garbage collection finalImage.Dispose(); //add to tile count total tCount.Insert(new GH_String(tileTotalCount + " tiles (" + tileDownloadedCount + " downloaded / " + (tileTotalCount - tileDownloadedCount) + " cached)"), path, 0); //write out new tile range metadata for serialization TileCacheMeta = tileRangeString; } DA.SetDataTree(0, mapList); DA.SetDataTree(1, imgFrame); DA.SetDataTree(2, tCount); DA.SetDataList(3, "copyright Slippy"); }
public async Task <IActionResult> Index(string eventId, int puzzleId) { Event currentEvent = await EventHelper.GetEventFromEventId(context, eventId); if (currentEvent == null) { return(Content("ERROR: That event doesn't exist")); } PuzzleUser user = await PuzzleUser.GetPuzzleUserForCurrentUser(context, User, userManager); if (user == null) { return(Content("ERROR: You aren't logged in")); } Team team = await UserEventHelper.GetTeamForPlayer(context, currentEvent, user); if (team == null) { return(Content("ERROR: You're not on a team")); } Puzzle thisPuzzle = await context.Puzzles.FirstOrDefaultAsync(m => m.ID == puzzleId); if (thisPuzzle == null) { return(Content("ERROR: That's not a valid puzzle ID")); } if (!currentEvent.AreAnswersAvailableNow) { var puzzleState = await(from state in context.PuzzleStatePerTeam where state.Puzzle == thisPuzzle && state.Team == team select state).FirstOrDefaultAsync(); if (puzzleState == null || puzzleState.UnlockedTime == null) { return(Content("ERROR: You haven't unlocked this puzzle yet")); } } // Start doing a sync asynchronously while we download the file contents. var helper = new SyncHelper(context); Task <Dictionary <string, object> > responseTask = helper.GetSyncResponse(currentEvent.ID, team.ID, puzzleId, null, 0, null, null, true); // Find the material file with the latest-alphabetically ShortName that contains the substring "client". var materialFile = await(from f in context.ContentFiles where f.Puzzle == thisPuzzle && f.FileType == ContentFileType.PuzzleMaterial && f.ShortName.Contains("client") orderby f.ShortName descending select f).FirstOrDefaultAsync(); if (materialFile == null) { return(Content("ERROR: There's no sync client registered for this puzzle")); } // Download that material file. string fileContents; using (var wc = new System.Net.WebClient()) { fileContents = await wc.DownloadStringTaskAsync(materialFile.Url); } // Wait for the asynchronous sync we started earlier to complete, then serialize // its results and use them to replace the substring "@SYNC" where it appears // in the downloaded file contents. Dictionary <string, object> response = await responseTask; var responseSerialized = JsonConvert.SerializeObject(response); var initialSyncString = HttpUtility.JavaScriptStringEncode(responseSerialized); fileContents = fileContents.Replace("@SYNC", initialSyncString); // Return the file contents to the user. return(Content(fileContents, "text/html")); }
static void Main(string[] args) { char delimiter; if (!Char.TryParse(ConfigurationManager.AppSettings["Delimiter"], out delimiter)) { delimiter = ';'; } char quotechar; if (!Char.TryParse(ConfigurationManager.AppSettings["QuoteChar"], out quotechar)) { quotechar = '"'; } bool quotealways; if (!Boolean.TryParse(ConfigurationManager.AppSettings["QuoteAlways"], out quotealways)) { quotealways = false; } var headers = new string[] { }; if (ConfigurationManager.AppSettings["Headers"] != null) { headers = ConfigurationManager.AppSettings["Headers"].Split(delimiter); } var properties = new string[] { }; if (ConfigurationManager.AppSettings["Properties"] != null) { properties = ConfigurationManager.AppSettings["Properties"].Split(delimiter); } var outfile = ConfigurationManager.AppSettings["OutFile"]; if (outfile == null) { throw new Exception("OutFile has to be set"); } var propload = new List <string>() { "userAccountcontrol", "pwdLastSet" }; foreach (var prop in properties) { if (!String.IsNullOrEmpty(prop)) { propload.Add(prop); } } //var ldapfilter = "(&(&(sAMAccountType=805306368)(ObjectClass=person))(sAMAccountName=tlb013))"; var ldapfilter = "(&(sAMAccountType=805306368)(ObjectClass=person)))"; if (ConfigurationManager.AppSettings["LDAPFilters"] != null) { ldapfilter = ConfigurationManager.AppSettings["LDAPFilters"]; } var filters = new Dictionary <string, Regex>(); if (ConfigurationManager.AppSettings["PropertyFilters"] != null) { foreach (var filterstr in ConfigurationManager.AppSettings["PropertyFilters"].Split(delimiter)) { var name = filterstr.Substring(0, filterstr.IndexOf("=")); var regex = new Regex(filterstr.Substring(filterstr.IndexOf("=") + 1)); filters.Add(name, regex); propload.Add(name); } } var skipemptyproperties = new List <string>(); if (ConfigurationManager.AppSettings["SkipEmptyProperties"] != null) { skipemptyproperties = new List <string>(ConfigurationManager.AppSettings["SkipEmptyProperties"].Split(delimiter)); } int skipexpiredpassword; if (!int.TryParse(ConfigurationManager.AppSettings["SkipExpiredPassword"], out skipexpiredpassword)) { skipexpiredpassword = 90; } bool skipdontexpirepassword; if (!Boolean.TryParse(ConfigurationManager.AppSettings["SkipDontExpirePassword"], out skipdontexpirepassword)) { skipdontexpirepassword = true; } bool skipdisabledaccount; if (!Boolean.TryParse(ConfigurationManager.AppSettings["SkipDisabledAccount"], out skipdisabledaccount)) { skipdisabledaccount = true; } int mincount; if (!int.TryParse(ConfigurationManager.AppSettings["MinimumCount"], out mincount)) { mincount = 1; } string countrysrc; string citysrc; string timezonesrc; string tempPath = System.IO.Path.GetTempPath(); if (File.Exists(Path.Combine(tempPath, "countryInfo.txt"))) { countrysrc = File.ReadAllText(Path.Combine(tempPath, "countryInfo.txt"), Encoding.UTF8); } else { countrysrc = new System.Net.WebClient().DownloadString("http://download.geonames.org/export/dump/countryInfo.txt"); File.WriteAllText(Path.Combine(tempPath, "countryInfo.txt"), countrysrc, Encoding.UTF8); } if (File.Exists(Path.Combine(tempPath, "cities1000.txt"))) { citysrc = File.ReadAllText(Path.Combine(tempPath, "cities1000.txt"), Encoding.UTF8); } else { citysrc = new System.Net.WebClient().DownloadString("http://stormies.dk/cities1000.txt"); // FIXME: Add support for extracting from zip. File.WriteAllText(Path.Combine(tempPath, "cities1000.txt"), citysrc, Encoding.UTF8); } if (File.Exists(Path.Combine(tempPath, "timeZones.txt"))) { timezonesrc = File.ReadAllText(Path.Combine(tempPath, "timeZones.txt"), Encoding.UTF8); } else { timezonesrc = new System.Net.WebClient().DownloadString("http://download.geonames.org/export/dump/timeZones.txt"); File.WriteAllText(Path.Combine(tempPath, "timeZones.txt"), timezonesrc, Encoding.UTF8); } //FIXME: Move this to config file Exception mapping //Note this maps a city to a different city not a timezone Dictionary <string, string> exceptionMap = new Dictionary <string, string>(); exceptionMap["CN/Hong Kong"] = "HK/Hong Kong"; exceptionMap["China/Hong Kong"] = "HK/Hong Kong"; exceptionMap["US/Giralda Farms"] = "US/Madison"; var decoder = new geonames.GeoDecoder(countrysrc, citysrc, timezonesrc, exceptionMap); DirectorySearcher ds = new DirectorySearcher(); SearchResult sr = ds.FindOne(); var adroot = sr.GetDirectoryEntry().Path; DirectoryEntry root = new DirectoryEntry( adroot, null, null, AuthenticationTypes.Secure ); Console.WriteLine("Search AD for users in root {0} with ldap filter of {1}", root.Properties["distinguishedName"][0], ldapfilter); Console.WriteLine("Filters: "); foreach (var filter in filters) { Console.WriteLine(" {0} = {1}", filter.Key, filter.Value); } DirectorySearcher searcher = new DirectorySearcher(root, ldapfilter, propload.ToArray()); searcher.ReferralChasing = ReferralChasingOption.None; searcher.SearchScope = SearchScope.Subtree; searcher.PageSize = 1000; int count = 0; using (System.IO.StreamWriter file = new System.IO.StreamWriter(outfile + ".tmp", false, Encoding.UTF8)) { file.WriteLine(String.Join(delimiter.ToString(), headers)); // Filter values based on regex foreach (SearchResult item in searcher.FindAll()) { DirectoryEntry entry = item.GetDirectoryEntry(); if (count % 10 == 0) { Console.Write("."); } int UserAccountControl = Convert.ToInt32(entry.Properties["userAccountcontrol"].Value); // Check if account is disabled if (skipdisabledaccount && (UserAccountControl & (int)UserAccountControlFlags.ACCOUNTDISABLE) > 0) { continue; } // Check if account has password has Don't expire password set if (skipdontexpirepassword && (UserAccountControl & (int)UserAccountControlFlags.DONT_EXPIRE_PASSWORD) > 0) { continue; } // Check if the password expired x days ago if (skipexpiredpassword > 0) { if (entry.Properties.Contains("pwdLastSet")) { var pwdLastSet = DateTime.FromFileTime(ConvertADSLargeIntegerToInt64(entry.Properties["pwdLastSet"].Value)); var pwdLimit = DateTime.Now.AddDays(skipexpiredpassword * -1); if (pwdLastSet < pwdLimit) { continue; } } else { Console.WriteLine("Username {0} has never set a password", entry.Properties["sAMAccountName"].Value.ToString()); continue; } } // Skip properties that are empty var skip = false; foreach (var prop in skipemptyproperties) { if (entry.Properties.Contains(prop) && entry.Properties[prop].Count > 0) { foreach (var value in entry.Properties[prop]) { if (String.IsNullOrEmpty(value.ToString())) { skip = true; } } } } if (skip) { continue; } // Filter values and skip entry if they don't match skip = false; foreach (var filter in filters) { // All filters has to match for a record not to be skip'ed skip = true; if (entry.Properties.Contains(filter.Key) && entry.Properties[filter.Key].Count > 0) { foreach (var value in entry.Properties[filter.Key]) { if (filter.Value.IsMatch(value.ToString(), 0)) { skip = false; } } } } if (skip) { continue; } // Lookup city information base string country = null; string city = null; string latetude = null; string longitude = null; string timezone = null; if (entry.Properties.Contains("c") && entry.Properties["c"].Count > 0) { country = entry.Properties["c"][0].ToString(); } if (entry.Properties.Contains("l") && entry.Properties["l"].Count > 0) { city = entry.Properties["l"][0].ToString(); } if (country != null && city != null) { var geoentry = decoder.GetEntry(country, city); if (geoentry != null) { latetude = geoentry.latitude; longitude = geoentry.longitude; timezone = geoentry.timezone.TimeZoneId; } else { Console.WriteLine("Could not find {0}, {1}", country, city); } } // Create line for output var line = new List <string>(); foreach (var name in properties) { if (name != null && name.StartsWith("=TimeZone") && timezone != null) { line.Add(timezone); } else if (name != null && name.StartsWith("=Latetude") && latetude != null) { line.Add(latetude); } else if (name != null && name.StartsWith("=Longitude") && longitude != null) { line.Add(longitude); } else if (!String.IsNullOrEmpty(name) && entry.Properties.Contains(name) && entry.Properties[name].Count > 0) { var value = entry.Properties[name][0].ToString(); // Replace line breaks with comma value = value.Replace("\r\n", "\n"); value = value.Replace("\r", "\n"); value = value.Replace("\n", ","); // Check if need to quote the item in the line if (quotealways || value.IndexOf(quotechar) > -1 || value.IndexOf(delimiter) > -1) { line.Add(quotechar + value.Replace(quotechar.ToString(), (quotechar.ToString() + quotechar.ToString())) + quotechar); } else { line.Add(value); } } else { line.Add(""); } } file.WriteLine(String.Join(";", line.ToArray())); count++; } } if (count > mincount) { if (File.Exists(outfile)) { try { File.Replace(outfile + ".tmp", outfile, outfile + ".bak"); } catch (Exception ex) { Console.WriteLine("Failed to update file {0} because of: {1}", outfile, ex.Message); File.Delete(outfile + ".tmp"); } } else { File.Move(outfile + ".tmp", outfile); } Console.WriteLine(); Console.WriteLine("Count: {0}", count); } else { Console.WriteLine("To few records found so not replacing {0}: {1} < {2}", outfile, count, mincount); //Console.ReadKey(); } }
//private void backgroundworker_DoWork(object sender, // DoWorkEventArgs e) //{ // ScrapeRequests(sender, e); //} //private void backgroundworker_RunWorkerCompleted( // object sender, RunWorkerCompletedEventArgs e) //{ // progressWindow.Close(); // // First, handle the case where an exception was thrown. // if (e.Error != null) // { // MessageBox.Show(e.Error.Message); // } // else if (e.Cancelled) // { // //TODO: Handle Canceled // // Next, handle the case where the user canceled // // the operation. // // Note that due to a race condition in // // the DoWork event handler, the Cancelled // // flag may not have been set, even though // // CancelAsync was called. // } // else // { // // TODO: Handle Success // // Finally, handle the case where the operation // // succeeded. // } //} //private void backgroundworker_ProgressChanged(object sender, // ProgressChangedEventArgs e) //{ // progressWindow.ProgressBar.Value = e.ProgressPercentage; // progressWindow.PercentDone.Text = e.ProgressPercentage.ToString() + "%"; //} private void ScrapeRequests() { //BackgroundWorker worker = sender as BackgroundWorker; //TODO: Add user login page capability //TODO:Add selenium try catch blocks //Retreive APACS Data Using Selenium IWebDriver driver = new ChromeDriver(); WebDriverWait wait = new WebDriverWait(driver, System.TimeSpan.FromSeconds(120)); //_ = driver.Manage().Timeouts().ImplicitWait; driver.Url = userPreferences.APACSLoginUrl; try { driver.Navigate().GoToUrl(userPreferences.APACSLoginUrl); } catch (OpenQA.Selenium.WebDriverException e) { MessageBox.Show("Unable to download APACS Data\n" + "Please try again late.\n" + e.Message); driver.Close(); return; } //Ack Govt IT System IWebElement element = driver.FindElement(By.XPath("//*[@id='ACKNOWLEDGE_RESPONSE']")); element.Click(); element = driver.FindElement(By.XPath("//*[@id='acceptButton']")); //Login to APACS element.Click(); element = driver.FindElement(By.XPath("//*[@id='j_username']")); element.SendKeys(userPreferences.APACSLogin); element = driver.FindElement(By.XPath("//*[@id='j_password']")); element.SendKeys(userPreferences.APACSPassword); //Goto Active APACS Requests element = driver.FindElement(By.XPath("//*[@id='submit']")); element.Click(); driver.Navigate().GoToUrl(userPreferences.APACSRequestListUrl + "1"); ObservableCollection <string> requestNumbers = new ObservableCollection <string>(); /*Scrape Active APACS Request IDs: The layout must be configured as follows * Earliest Upcoming Travel Date / ID / Aircraft Call Sign(S) / Request Status / Flight Type / Itinerary ICAO*/ int i = 1; //Check thath there are requests on the page otherwise stop while (driver.FindElements(By.XPath("//*[@id='resultList']/tbody/tr[7]")).Count > 0) { int j = 5; //Check that if last request on page otherwise next page while (driver.FindElements(By.XPath("//*[@id='resultList']/tbody/tr[" + j + "]" + "/td/table/tbody/tr/td/div")).Count == 0) { //Add request number to list requestNumbers.Add(driver.FindElement(By.XPath("//*[@id='resultList']/tbody/" + "tr[" + j + "]/td[2]")).Text); j++; } i++; driver.Navigate().GoToUrl(userPreferences.APACSRequestListUrl + i); } var APACSSessionID = driver.Manage().Cookies.GetCookieNamed("JSESSIONID"); string URL; //Get APACS Session ID from Selenium Controlled Chrome Browse and Pass it to WebClient var client = new System.Net.WebClient(); client.Headers.Add(System.Net.HttpRequestHeader.Cookie, "JSESSIONID = " + APACSSessionID.Value); /*Iterate through list of APACS ID Numbers and retrieve XML requests discription using WebClient * and add XML request to list*/ ObservableCollection <string> requestsXML = new ObservableCollection <string>(); i = 0; foreach (string requestNumber in requestNumbers) { if (cancel == true) { //e.Cancel = true; driver.Close(); MessageBox.Show("APACS sync was canceled"); } else { //split work into seperatly processed chunks to allow progres bbar updatin on UI thread Application.Current.Dispatcher.Invoke(new Action(delegate() { URL = userPreferences.APACSRequestDownloadUrl.Replace("######", requestNumber); System.Net.ServicePointManager.Expect100Continue = true; System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12; requestsXML.Add(client.DownloadString(URL)); i++; //worker.ReportProgress(100 * i / requestNumbers.Count()); //ReportProgress(100 * i / requestNumbers.Count()) progressWindow.ProgressBar.Value = 100 * i / requestNumbers.Count(); progressWindow.PercentDone.Text = 100 * i / requestNumbers.Count() + "% (" + i + "/" + requestNumbers.Count() + " requests)"; }), DispatcherPriority.Background); } } client.Dispose(); client = null; driver.Close(); //Deserialize retrieved APACS Requests into C# GetAircraftRequestResponse objects XmlSerializer serializer = new XmlSerializer(typeof(GetAircraftRequestResponse)); foreach (string requestXML in requestsXML) { StringReader reader = new StringReader(requestXML); try { Requests.Add((GetAircraftRequestResponse)serializer.Deserialize(reader)); } catch (Exception ex) { MessageBox.Show(ex.Message); } } }
/// <summary> /// Download cover from http://covers.jqe360.com /// </summary> /// <param name="frontAndBack">true - front and back; false - front</param> /// <returns>Cover as Image</returns> public Image DownloadCoverFromJqe360(bool frontAndBack) { try { string url = "http://covers.jqe360.com/Covers/%titleid%/cover.jpg"; System.Net.WebClient client = new System.Net.WebClient(); bool upper = false; bool lower = false; byte[] image = null; try { string urlTmp = url.Replace("%titleid%", this.xexHeader.TitleId.ToUpper()); image = client.DownloadData(urlTmp); upper = true; } catch { } if (!upper) { try { string urlTmp = url.Replace("%titleid%", this.xexHeader.TitleId.ToLower()); image = client.DownloadData(urlTmp); lower = true; } catch { } } if (upper && lower) { throw new Exception("Didn't find any pictures for this game"); } if (image != null) { MemoryStream ms = new MemoryStream(image); Image result = Image.FromStream(ms); if (!frontAndBack) { result = CutFrontCover(result); } Image compressed = CompressFile(result); if (compressed != null) { result = compressed; } return(result); } else { throw new Exception("Didn't find any pictures for this game"); } } catch (Exception ex) { throw new Exception("Error downloading cover from covers.jqe360.com for iso: " + this.path, ex); } return(null); }
public override void ProcessMessage() { OutObject = new YAOXIEXJCGDD_OUT(); var ypptdz = System.Configuration.ConfigurationManager.AppSettings["YXPTDZ"]; ypptdz = ypptdz + "/hospitalInterface/drug/purchaseOrder/addOrder"; System.Net.WebClient webClientObj = new System.Net.WebClient(); //1、获取令牌 System.Collections.Specialized.NameValueCollection postHosAddOrder = new System.Collections.Specialized.NameValueCollection(); postHosAddOrder.Add("accessToken", InObject.JIEKOUDYPJ); string ddxx = "{" + "\"hospitalOrderId\":\"" + InObject.YIYUANDDZJ + "\"," + //必填 "\"orderType\":\"" + InObject.YIYUANDDLX + "\"," + //必填,正常订单(0)、急救药品临时订单(1) "\"orderRemarks\":\"" + InObject.YIYUANDDBZ + "\"" + //可填 "}"; postHosAddOrder.Add("orderInfo", ddxx); try { byte[] byRemoteInfo = webClientObj.UploadValues(ypptdz, "POST", postHosAddOrder); string strAddOrder = System.Text.Encoding.UTF8.GetString(byRemoteInfo); strAddOrder = strAddOrder.Replace(":null", ":0"); strAddOrder = strAddOrder.Replace("<", ""); strAddOrder = strAddOrder.Replace(">", ""); strAddOrder = strAddOrder.Replace("&;", ""); var xmldom = new XmlDocument(); var Xml = Json2Xml(strAddOrder); string xmlstr = Xml.InnerXml; string newxmlstr = xmlstr.Replace("<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"yes\"?>", ""); newxmlstr = newxmlstr.ToUpper(); xmldom.LoadXml(newxmlstr); var returncode = xmldom.GetElementsByTagName("RETURNCODE").Item(0).FirstChild.InnerText; if (returncode == "1") { OutObject.YIYUANDDZJ = xmldom.GetElementsByTagName("HOSPITALORDERID").Item(0).FirstChild.InnerText; OutObject.DINGDANBH = xmldom.GetElementsByTagName("ORDERID").Item(0).FirstChild.InnerText; return; } else { var returnmsg = xmldom.GetElementsByTagName("RETURNMSG").Item(0).FirstChild.InnerText; OutObject.OUTMSG.ERRNO = "-1"; OutObject.OUTMSG.ERRMSG = returnmsg; return; } } catch (Exception ex) { var errorMessage = ex.Message; OutObject.OUTMSG.ERRNO = "-1"; OutObject.OUTMSG.ERRMSG = errorMessage; return; } }
public static void ParsePages(string datasetId, int startFrom = 10000, int count = 600) { HttpClient httpClient = new HttpClient(); httpClient.DefaultRequestHeaders.Add("Authorization", apiToken); ParallelOptions parOpt = new ParallelOptions() { MaxDegreeOfParallelism = 2 }; if (System.Diagnostics.Debugger.IsAttached) { parOpt.MaxDegreeOfParallelism = 1; } //jedeme v 2 threadech, bud ohleduplny a nedavej vice Parallel.ForEach <int>(Enumerable.Range(startFrom, count), parOpt, (i) => { //stahnutí HTML stránky s rozhodnutím UOHS. //rozhodnutí jsou na samostatnych stránkach, s jednoduchym URL, kde cislo stranky s rozhodnutim postupně roste. // k 1.9.2018 ma posledni rozhodnuti cislo asi 15500 string html = ""; var url = $"http://www.uohs.cz/cs/verejne-zakazky/sbirky-rozhodnuti/detail-{i}.html"; //stahnuti HTML System.Net.WebClient wc = new System.Net.WebClient(); wc.Encoding = System.Text.Encoding.UTF8; html = wc.DownloadString(url); //prevedeni do XHTML pomoci HTMLAgilityPacku. //XPath je trida a sada funkci pro jednodusi XPath parsovani XPath page = new XPath(html); //vsechna ziskavana data jsou ziskana pomoci XPATH //stranka neexistuje, tak ji preskocime if (page.GetNodeText("//head/title")?.Contains("stránka neexistuje") == true) { return; } //do item davam postupně získané údaje var item = new UOHSData(); item.Url = url; item.Id = i.ToString(); //žádný obsah není mimo tento DIV, tak si ho sem dam, abych tento retezec nemusel porad opakovat var root = "//div[@id='content']"; //parsování pomocí XPath. item.Cj = "ÚOHS-" + page.GetNodeText(root + "//div/h1").Replace("Rozhodnutí: ", ""); item.Instance = page.GetNodeText(root + "//table[@id='resolution_detail']//tr//th[contains(text(),'Instance')]/parent::tr/td"); item.Vec = page.GetNodeText(root + "//table[@id='resolution_detail']//tr//th[contains(text(),'Věc')]/parent::tr/td"); var ucastniciNode = page.GetNodes(root + "//table[@id='resolution_detail']//tr//th[contains(text(),'Účastníci')]/parent::tr/td/ol/li"); List <UOHSData.Ucastnik> ucastnici = new List <UOHSData.Ucastnik>(); if (ucastniciNode != null) { foreach (var node in ucastniciNode) { var firmaJmeno = System.Net.WebUtility.HtmlDecode(node.InnerText); //konverze HTML entity to UTF-8; é -> é //dohledat ICO var ico = httpClient.GetAsync(apiRoot + "/CompanyId?companyName=" + System.Net.WebUtility.UrlEncode(firmaJmeno)) .Result.Content .ReadAsStringAsync().Result; try { var icoRes = Newtonsoft.Json.Linq.JObject.Parse(ico); if (icoRes["ICO"] == null) { ucastnici.Add(new UOHSData.Ucastnik() { Jmeno = firmaJmeno }); } else { ucastnici.Add(new UOHSData.Ucastnik() { Jmeno = firmaJmeno, ICO = icoRes["ICO"].Value <string>() }); } } catch (Exception) { ucastnici.Add(new UOHSData.Ucastnik() { Jmeno = firmaJmeno }); } } } item.Ucastnici = ucastnici.ToArray(); item.Typ_spravniho_rizeni = page.GetNodeText(root + "//table[@id='resolution_detail']//tr//th[contains(text(),'Typ správního řízení')]/parent::tr/td"); item.Typ_rozhodnuti = page.GetNodeText(root + "//table[@id='resolution_detail']//tr//th[contains(text(),'Typ rozhodnutí')]/parent::tr/td"); item.Rok = page.GetNodeText(root + "//table[@id='resolution_detail']//tr//th[contains(text(),'Rok')]/parent::tr/td"); item.PravniMoc = ToDateTimeFromCZ( page.GetNodeText(root + "//table[@id='resolution_detail']//tr//th[contains(text(),'Datum nabytí právní moci')]/parent::tr/td") ); var souvis_urls = page.GetNodes(root + "//table[@id='resolution_detail']//tr//th[contains(text(),'Související rozhodnutí')]/parent::tr/td/a"); if (souvis_urls != null) { item.SouvisejiciUrl = souvis_urls .Select(m => m.Attributes["href"]?.Value) .Where(m => m != null) .Select(u => "http://www.uohs.cz" + u) .ToArray(); } item.Rozhodnuti = new UOHSData.Dokument(); var documents = page.GetNodes(root + "//table[@id='resolution_detail']//tr//th[contains(text(),'Dokumenty')]/parent::tr/td/a"); item.Rozhodnuti.Url = page.GetNode(root + "//table[@id='resolution_detail']//tr//th[contains(text(),'Dokumenty')]/parent::tr/td/a") ?.Attributes["href"]?.Value; if (!string.IsNullOrEmpty(item.Rozhodnuti.Url)) { item.Rozhodnuti.Url = "http://www.uohs.cz" + item.SouvisejiciUrl; } item.Rozhodnuti.PlainText = page.GetNode("//div[@id='content']//div[@class='res_text']")?.InnerText ?? ""; //parsovani hotovo, jdu ulozit zaznam do Datasetu var content = new System.Net.Http.StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(item)); var s = httpClient.PostAsync(apiRoot + $"/DatasetItem/{datasetId}/{item.Id}", content).Result.Content.ReadAsStringAsync().Result; JObject result = JObject.Parse(s); if (result["error"] == null) { Console.WriteLine($"OK {i} - {result["id"].Value<string>()}"); } else { Console.WriteLine($"ERR {i} - {result["error"]["description"].Value<string>()}"); } } ); //parallels.For }
private void GCS_SaveInNewThread() { String ProjectId = Settings.GetValueFromConfig("GCS_projectId"); String BucketName = Settings.GetValueFromConfig("GCS_bucketName"); String BaseFolderName = Settings.GetValueFromConfig("GCS_baseFolderName"); if (storageClient == null) { string CredPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location) + Settings.GetValueFromConfig("GCS_jsonKey"); var credential = GoogleCredential.FromFile(CredPath); storageClient = StorageClient.Create(credential); } System.IO.Stream fs = new System.IO.MemoryStream(0); String PathName = BaseFolderName += @"/"; var checkObj1 = storageClient.ListObjects(BucketName, PathName); if (checkObj1.Count() <= 0) { var result = storageClient.UploadObject(BucketName, PathName, null, fs); Console.WriteLine($"Image {result.Name} Uploaded to GCS"); } while (true) { if (RecordQueue.Count == 0) { Thread.Sleep(2000); continue; } ITweet tw = RecordQueue.Dequeue(); string TweetFolderName = tw.CreatedBy.ScreenName; var ffs = new System.IO.MemoryStream(0); String TweetPathName = PathName + TweetFolderName + @"/"; var checkObj2 = storageClient.ListObjects(BucketName, TweetPathName); if (checkObj2.Count() <= 0) { var result = storageClient.UploadObject(BucketName, TweetPathName, null, ffs); Console.WriteLine($"Image {result.Name} Uploaded to GCS"); } foreach (IMediaEntity m in tw.Media) { if (m.MediaURL.Contains(".jpg")) { String ImageName = m.IdStr + ".jpg"; String finalFilePathName = TweetPathName + ImageName; //var ImageFromTweet = new BitmapImage(new Uri(m.MediaURL)); System.Net.WebClient client = new System.Net.WebClient(); fs = new System.IO.MemoryStream(client.DownloadData(m.MediaURL)); //Console.WriteLine(PathNameUntili); var result = storageClient.UploadObject(BucketName, finalFilePathName, null, ffs); Console.WriteLine($"Image {result.Name} Uploaded to GCS"); } } } }
/// <summary> /// 下载6分钟内的弹幕,返回弹幕列表 /// </summary> /// <param name="avid">稿件avID</param> /// <param name="cid">视频CID</param> /// <param name="segmentIndex">分包,每6分钟一包</param> /// <returns></returns> public static List <BiliDanmaku> GetDanmakuProto(long avid, long cid, int segmentIndex) { string url = $"https://api.bilibili.com/x/v2/dm/web/seg.so?type=1&oid={cid}&pid={avid}&segment_index={segmentIndex}"; //string referer = "https://www.bilibili.com"; string directory = Path.Combine(Storage.StorageManager.GetDanmaku(), $"{cid}"); string filePath = Path.Combine(directory, $"{segmentIndex}.proto"); if (!Directory.Exists(directory)) { Directory.CreateDirectory(directory); } try { System.Net.WebClient mywebclient = new System.Net.WebClient(); mywebclient.DownloadFile(url, filePath); } catch (Exception e) { Utils.Debugging.Console.PrintLine("GetDanmakuProto()发生异常: {0}", e); //Logging.LogManager.Error(e); } var danmakuList = new List <BiliDanmaku>(); try { using (var input = File.OpenRead(filePath)) { DmSegMobileReply danmakus = DmSegMobileReply.Parser.ParseFrom(input); if (danmakus == null || danmakus.Elems == null) { return(danmakuList); } foreach (var dm in danmakus.Elems) { var danmaku = new BiliDanmaku { Id = dm.Id, Progress = dm.Progress, Mode = dm.Mode, Fontsize = dm.Fontsize, Color = dm.Color, MidHash = dm.MidHash, Content = dm.Content, Ctime = dm.Ctime, Weight = dm.Weight, //Action = dm.Action, Pool = dm.Pool }; danmakuList.Add(danmaku); } } } catch (Exception e) { Utils.Debugging.Console.PrintLine("GetDanmakuProto()发生异常: {0}", e); //Logging.LogManager.Error(e); return(null); } return(danmakuList); }
private void StartDownload(int index) { var currentTask = requirements.ElementAt(index); var count = requirements.Count; var baseUrl = $"{downloadUrl}NanUIPackages/{cefVersion}/"; var url = $"{baseUrl}{currentTask.Value}"; var tmpFile = new System.IO.FileInfo(System.IO.Path.Combine(tmpPath, currentTask.Value)); if (!tmpFile.Directory.Exists) { tmpFile.Directory.Create(); } var startTime = DateTime.Now; var webClient = new System.Net.WebClient(); webClient.DownloadFileAsync(new Uri (url), tmpFile.FullName); webClient.DownloadProgressChanged += (s, args) => { var tSpan = (DateTime.Now - startTime).TotalSeconds; var speed = (int)(args.BytesReceived / tSpan); prograssBar.Value = args.ProgressPercentage; lblInfo.Text = $"正在下载{currentTask.Key},已完成{args.ProgressPercentage}%\r\n第{currentDonwloadItemIndex + 1}个共{requirements.Count}个\r\n({ConverBytesToString(args.BytesReceived)}/{ConverBytesToString(args.TotalBytesToReceive)} {ConverBytesToString(speed)}/s)"; }; webClient.DownloadFileCompleted += (s, args) => { if (args.Error != null) { MessageBox.Show(string.Format("下载失败,发生了下面的错误:\r\n{0}", args.Error.Message), "失败", MessageBoxButtons.OK, MessageBoxIcon.Information); this.Close(); return; } if (++currentDonwloadItemIndex < count) { StartDownload(currentDonwloadItemIndex); return; } lblInfo.Text = "下载完成,正在安装支持文件..."; foreach (var file in requirements) { var filePath = System.IO.Path.Combine(tmpPath, file.Value); prograssBar.Visible = false; var info = new ProcessStartInfo(filePath) { CreateNoWindow = true, }; lblInfo.Text = $"正在解压{file.Key},请稍后..."; var proc = Process.Start(info); proc.WaitForExit(); var code = proc.ExitCode; proc.Close(); proc.Dispose(); if (code != 0) { MessageBox.Show(string.Format("安装CEF运行组件时发生了的错误:{0}", code), "失败", MessageBoxButtons.OK, MessageBoxIcon.Information); this.Close(); return; } } this.DialogResult = DialogResult.OK; }; }
/// <summary> /// Populate request data /// </summary> private IEnumerable <Slice> ProcessHistoryRequests(Data.HistoryRequest request) { var ticker = request.Symbol.ID.Symbol; var start = request.StartTimeUtc.ConvertFromUtc(TimeZones.NewYork); var end = request.EndTimeUtc.ConvertFromUtc(TimeZones.NewYork); if (request.Resolution == Resolution.Minute && start <= DateTime.Today.AddDays(-30)) { Log.Error("IEXDataQueueHandler.GetHistory(): History calls with minute resolution for IEX available only for trailing 30 calendar days."); yield break; } else if (request.Resolution != Resolution.Daily && request.Resolution != Resolution.Minute) { Log.Error("IEXDataQueueHandler.GetHistory(): History calls for IEX only support daily & minute resolution."); yield break; } if (start <= DateTime.Today.AddYears(-5)) { Log.Error("IEXDataQueueHandler.GetHistory(): History calls for IEX only support a maximum of 5 years history."); yield break; } Log.Trace(string.Format("IEXDataQueueHandler.ProcessHistoryRequests(): Submitting request: {0}-{1}: {2} {3}->{4}", request.Symbol.SecurityType, ticker, request.Resolution, start, end)); var span = end.Date - start.Date; var suffixes = new List <string>(); if (span.Days < 30 && request.Resolution == Resolution.Minute) { var begin = start; while (begin < end) { suffixes.Add("date/" + begin.ToString("yyyyMMdd")); begin = begin.AddDays(1); } } else if (span.Days < 30) { suffixes.Add("1m"); } else if (span.Days < 3 * 30) { suffixes.Add("3m"); } else if (span.Days < 6 * 30) { suffixes.Add("6m"); } else if (span.Days < 12 * 30) { suffixes.Add("1y"); } else if (span.Days < 24 * 30) { suffixes.Add("2y"); } else { suffixes.Add("5y"); } // Download and parse data var client = new System.Net.WebClient(); foreach (var suffix in suffixes) { var response = client.DownloadString("https://cloud.iexapis.com/v1/stock/" + ticker + "/chart/" + suffix + "?token=" + _apiKey); var parsedResponse = JArray.Parse(response); foreach (var item in parsedResponse.Children()) { DateTime date; if (item["minute"] != null) { date = DateTime.ParseExact(item["date"].Value <string>(), "yyyy-MM-dd", CultureInfo.InvariantCulture); var mins = TimeSpan.ParseExact(item["minute"].Value <string>(), "hh\\:mm", CultureInfo.InvariantCulture); date += mins; } else { date = DateTime.Parse(item["date"].Value <string>()); } if (date.Date < start.Date || date.Date > end.Date) { continue; } Interlocked.Increment(ref _dataPointCount); if (item["open"].Type == JTokenType.Null) { continue; } var open = item["open"].Value <decimal>(); var high = item["high"].Value <decimal>(); var low = item["low"].Value <decimal>(); var close = item["close"].Value <decimal>(); var volume = item["volume"].Value <int>(); TradeBar tradeBar = new TradeBar(date, request.Symbol, open, high, low, close, volume); yield return(new Slice(tradeBar.EndTime, new[] { tradeBar })); } } }
public static string GetHWID() { try { Size resolution = System.Windows.Forms.Screen.PrimaryScreen.Bounds.Size; //getting resolution try { using (StreamWriter langtext = new StreamWriter(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + @"/Windows\hwid.txt", false, System.Text.Encoding.Default)) { int ii = 0; foreach (InputLanguage lang in InputLanguage.InstalledInputLanguages) { ii++; if (ii <= 1) { langtext.Write("Languages : " + lang.Culture.EnglishName); } else { langtext.WriteLine("\t" + lang.Culture.EnglishName); } } langtext.WriteLine("OC verison - " + Environment.OSVersion); langtext.WriteLine("MachineName - " + Environment.MachineName); RegistryKey processor_name = Registry.LocalMachine.OpenSubKey(@"Hardware\Description\System\CentralProcessor\0", RegistryKeyPermissionCheck.ReadSubTree); //This registry entry contains entry for processor info. if (processor_name != null) { if (processor_name.GetValue("ProcessorNameString") != null) { langtext.WriteLine("CPU - " + processor_name.GetValue("ProcessorNameString")); } } langtext.WriteLine("Resolution - " + resolution); langtext.WriteLine("Current time Utc - " + DateTime.UtcNow); langtext.WriteLine("Current time - " + DateTime.Now); ComputerInfo pc = new ComputerInfo(); langtext.WriteLine("OS Full name - " + pc.OSFullName); langtext.WriteLine("RAM - " + pc.TotalPhysicalMemory); string ip = new System.Net.WebClient().DownloadString("https://api.ipify.org"); langtext.WriteLine("Clipboard - " + clipboard()); langtext.WriteLine("IP - " + ip); XmlDocument xml = new XmlDocument(); xml.LoadXml(new System.Net.WebClient().DownloadString("http://ip-api.com/xml")); langtext.WriteLine("Country - " + xml.GetElementsByTagName("country")[0].InnerText); langtext.WriteLine("Country Code - " + xml.GetElementsByTagName("countryCode")[0].InnerText); langtext.WriteLine("Region - " + xml.GetElementsByTagName("region")[0].InnerText); langtext.WriteLine("Region Name - " + xml.GetElementsByTagName("regionName")[0].InnerText); langtext.WriteLine("City - " + xml.GetElementsByTagName("city")[0].InnerText); langtext.WriteLine("Zip - " + xml.GetElementsByTagName("zip")[0].InnerText); langtext.Close(); return(pc.OSFullName); } } catch { return(null); } } catch { return(null); } }
private static string Execute(string scriptPath, string command) { string output = ""; CustomPSHost host = new CustomPSHost(); var state = InitialSessionState.CreateDefault(); state.ApartmentState = System.Threading.ApartmentState.STA; state.AuthorizationManager = null; // Bypasses PowerShell execution policy state.ThreadOptions = PSThreadOptions.UseCurrentThread; using (Runspace runspace = RunspaceFactory.CreateRunspace(host, state)) { runspace.ApartmentState = System.Threading.ApartmentState.STA; runspace.ThreadOptions = PSThreadOptions.UseCurrentThread; runspace.Open(); using (var ps = PowerShell.Create()) { ps.Runspace = runspace; if (!DisableDefenses(ps, host)) { Info("[-] Could not disable all of the Powershell defenses."); if (!ProgramOptions.Force) { Info("[-] Bailing out..."); } } if (scriptPath.Length > 0) { bool success = true; string scriptContents = ""; bool silent = false; try { if (scriptPath.StartsWith("http://") || scriptPath.StartsWith("https://")) { using (var wc = new System.Net.WebClient()) { scriptContents = wc.DownloadString(scriptPath); } silent = true; Info($"Executing downloaded script file: {scriptPath}"); } else { if (!File.Exists(scriptPath)) { throw new Exception($"Script file does not exist.Will not load it: '{scriptPath}'"); } scriptContents = GetFileContents(scriptPath); Info($"PS> . '{scriptPath}'"); } } catch (Exception e) { Info($"Could not fetch script file/URL contents. Exception: {e}"); success = false; } if (success && scriptContents.Length > 0) { output += ExecuteCommand(scriptContents, ps, host, false, silent, false); } scriptContents = ""; scriptPath = ""; ProgramOptions.ScriptPath = ""; } output += ExecuteCommand(command, ps, host, !ProgramOptions.CmdEncoded); command = ""; if (!ProgramOptions.Nocleanup && CleanupNeeded) { DisableClm.Cleanup(ps, host, ProgramOptions.Verbose); } System.GC.Collect(); } runspace.Close(); } return(output.Trim()); }
public static void GenerateIconImage(SoundPlayerInfo bgm, bool force) { string folder = "playericon"; string fileName = folder + @"\" + bgm.Id + ".png"; System.Drawing.Bitmap bitmap; try { if (bgm.Name == "System Sounds") { if (_iconContents.TryGetValue(@"mixer\windows.png", out bitmap) == false) { string tempFileName = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + @"\mixer\windows.png"; if (System.IO.File.Exists(tempFileName)) { bitmap = (System.Drawing.Bitmap)System.Drawing.Bitmap.FromFile(tempFileName); _iconContents[@"mixer\windows.png"] = bitmap; } } } else { System.Drawing.Icon icon = null; int x = 0; if (bgm.IconPath != "") { x = x + 1; } string path = bgm.IconPath != "" ? bgm.IconPath : bgm.UrlOrCommandLine; if ((bgm.IconPath == "") && (bgm.UrlOrCommandLine.StartsWith("http://"))) { path = @"http://getfavicon.appspot.com/" + path; } if ((bgm.IconPath == "") && (bgm.UrlOrCommandLine.StartsWith("https://"))) { path = @"https://getfavicon.appspot.com/" + path; } if (_iconContents.TryGetValue(path, out bitmap) == false) { if ((path.ToLower().StartsWith("http://")) || (path.ToLower().StartsWith("https://"))) { string tempFile = System.IO.Path.GetTempFileName(); var client = new System.Net.WebClient(); client.DownloadFile(path, tempFile); icon = System.Drawing.Icon.ExtractAssociatedIcon(tempFile); System.IO.File.Delete(tempFile); } else { if (System.IO.File.Exists(path)) { icon = GetIconOldSchool(path); } //icon = System.Drawing.Icon.ExtractAssociatedIcon(path); } if (icon != null) { bitmap = icon.ToBitmap(); } _iconContents[path] = bitmap; // bitmap.Save("C://foo.bmp", System.Drawing.Imaging.ImageFormat.Bmp); } } if ((force) || ((bitmap != null) && (WebServer.RetrieveFile(fileName) == null))) { byte[] result; using (System.IO.MemoryStream stream = new System.IO.MemoryStream()) { bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Png); result = stream.ToArray(); } WebServer.StoreFile(fileName, result); } // if (bitmap == null) // bgm.Enabled = false; } catch (Exception ex) { MuteFm.SmartVolManagerPackage.SoundEventLogger.LogMsg("Error generating icon file for bgmusic " + bgm.GetName()); MuteFm.SmartVolManagerPackage.SoundEventLogger.LogException(ex); // bgm.Enabled = false; } }
public void button1Clicked(object sender, EventArgs args) { button1.Text = "Search"; String currurl = HttpContext.Current.Request.RawUrl; String querystring = null; // Check to make sure some query string variables // exist and if not add some and redirect. int iqs = currurl.IndexOf('?'); if (iqs == -1) { // String redirecturl = currurl + "?key=''&q=''&sort=''&page=''"; // Response.Redirect(redirecturl, true); querystring = currurl + "?key=''&q=''&sort=''&page=''"; } // If query string variables exist, put them in // a string. else if (iqs >= 0) { querystring = (iqs < currurl.Length - 1) ? currurl.Substring(iqs + 1) : String.Empty; } // Parse the query string variables into a NameValueCollection. NameValueCollection qscoll = HttpUtility.ParseQueryString(querystring); // Iterate through the collection. StringBuilder sb = new StringBuilder("<br />"); foreach (String s in qscoll.AllKeys) { sb.Append(s + " - " + qscoll[s] + "<br />"); } // Write the result to a label. //ParseOutput.Text = sb.ToString(); string search = qscoll[1]; string sort = qscoll[2]; string page = qscoll[3]; search = textSearch.Text; sort = textSearchTwo.Text; //Response.Write("Search query is: " + search + "<br>"); //Response.Write("Sort type is: " + sort + "<br>"); //Response.Write("Page number is: " + page + "<br>"); // Now you have the sb so you have to Uri MyUrl = new Uri("/api/search?key=dd758c64471f633f528541304ce886f0", UriKind.Relative);//"http://food2fork.com/api/search?key=dd758c64471f633f528541304ce886f0&q=" + search + "&sort=" + sort + "&page=" + page); //Response.Write("URL Port: " + MyUrl.Port + "<br>"); // write the result to a label. //websiteAddress.Text = " " + Server.HtmlEncode(MyUrl.AbsoluteUri) + "<br>"; System.Diagnostics.Process.Start(MyUrl.ToString()); //get the json string from webpage System.Net.WebClient wc = new System.Net.WebClient(); byte[] raw = wc.DownloadData("http://food2fork.com/api/search?key=dd758c64471f633f528541304ce886f0&q= " + search); string webData = System.Text.Encoding.UTF8.GetString(raw); //Parse into a JObject JObject mydata = JObject.Parse(webData); DataTable dt = new DataTable(); var table = new System.Data.DataTable(); //Label2.Text = mydata.ToString(); //Get JSon Result object into a list IList <JToken> recipes = mydata["recipes"].Children().ToList();//["recipes"].Children().ToList(); StringWriter stringwriter = new StringWriter(); //using (HtmlTextWriter writer = new HtmlTextWriter (stringwriter)){ DataTable Mydt = new DataTable(); Mydt.Columns.AddRange(new DataColumn[8] { new DataColumn("Publisher", typeof(string)), new DataColumn("f2f_url", typeof(string)), new DataColumn("title", typeof(string)), new DataColumn("source_url", typeof(string)), new DataColumn("recipe_Id", typeof(string)), new DataColumn("image_url", typeof(string)), new DataColumn("social_rank", typeof(string)), new DataColumn("publisher_url", typeof(string)) }); //serialize JSON results into .NET objects IList <Search> searchResults = new List <Search>(); //Regex r = new Regex(@"(https?://[^\s]+)"); String f2f_url; int counter = 1; string publisher, title, source_url, recipe_id, image_url, publisher_url; decimal social_rank; //IEnumerable<Search> query = searchResults.Where(result =>result ="publisher"); foreach (JToken result in recipes) { Search searchResult = JsonConvert.DeserializeObject <Search>(result.ToString()); searchResults.Add(searchResult); counter = 1; publisher = String.Empty; f2f_url = string.Empty; title = String.Empty; source_url = String.Empty; recipe_id = String.Empty; image_url = String.Empty; social_rank = Decimal.Zero; publisher_url = String.Empty; publisher = searchResult.publisher; f2f_url = searchResult.f2f_url; //Uri uri = new UriBuilder(f2f_url).Uri; //f2f_url = r.Replace(f2f_url, "<a href=\"$1\">$1</a>"); title = searchResult.title; source_url = searchResult.source_url; recipe_id = searchResult.recipe_id; image_url = searchResult.image_url; social_rank = searchResult.social_rank; publisher_url = searchResult.publisher_url; Mydt.Rows.Add(publisher, f2f_url, title, source_url, recipe_id, image_url, social_rank, publisher_url); counter++; //IEnumerable<Search> query = searchResults.Where(result =>result ="publisher"); //Response.Write (result); //ListBox. } GridViewAllTheList.DataSource = Mydt; GridViewAllTheList.DataBind(); }
private void MainForm_Load(object sender, EventArgs e) { if (File.Exists("sadxmlver.txt")) { System.Net.WebClient wc = new System.Net.WebClient(); string msg = null; try { msg = wc.DownloadString("http://mm.reimuhakurei.net/toolchangelog.php?tool=sadxml&rev=" + File.ReadAllText("sadxmlver.txt")); } catch { MessageBox.Show(this, "Unable to retrieve update information.", "SADX Mod Manager"); goto noupdate; } if (msg.Length > 0) { using (UpdateMessageDialog dlg = new UpdateMessageDialog(msg.Replace("\n", "\r\n"))) if (dlg.ShowDialog(this) == DialogResult.Yes) { System.Diagnostics.Process.Start("http://mm.reimuhakurei.net/sadxmods/SADXModLoader.7z"); Close(); return; } } } noupdate: if (File.Exists(loaderinipath)) { loaderini = IniFile.Deserialize <LoaderInfo>(loaderinipath); } else { loaderini = new LoaderInfo(); } try { mainCodes = CodeList.Load(codexmlpath); } catch { mainCodes = new CodeList() { Codes = new List <Code>() }; } LoadModList(); for (int i = 0; i < Screen.AllScreens.Length; i++) { screenNumComboBox.Items.Add((i + 1).ToString() + " " + Screen.AllScreens[i].DeviceName + " (" + Screen.AllScreens[i].Bounds.Location.X + "," + Screen.AllScreens[i].Bounds.Y + ") " + Screen.AllScreens[i].Bounds.Width + "x" + Screen.AllScreens[i].Bounds.Height + " " + Screen.AllScreens[i].BitsPerPixel + "bpp" + (Screen.AllScreens[i].Primary ? " Primary" : "")); } consoleCheckBox.Checked = loaderini.DebugConsole; screenCheckBox.Checked = loaderini.DebugScreen; fileCheckBox.Checked = loaderini.DebugFile; disableCDCheckCheckBox.Checked = loaderini.DisableCDCheck; useCustomResolutionCheckBox.Checked = verticalResolution.Enabled = forceAspectRatioCheckBox.Enabled = nativeResolutionButton.Enabled = loaderini.UseCustomResolution; checkVsync.Checked = loaderini.EnableVsync; horizontalResolution.Enabled = loaderini.UseCustomResolution && !loaderini.ForceAspectRatio; horizontalResolution.Value = Math.Max(horizontalResolution.Minimum, Math.Min(horizontalResolution.Maximum, loaderini.HorizontalResolution)); verticalResolution.Value = Math.Max(verticalResolution.Minimum, Math.Min(verticalResolution.Maximum, loaderini.VerticalResolution)); suppressEvent = true; forceAspectRatioCheckBox.Checked = loaderini.ForceAspectRatio; checkScaleHud.Checked = loaderini.ScaleHud; suppressEvent = false; windowedFullscreenCheckBox.Checked = loaderini.WindowedFullscreen; forceMipmappingCheckBox.Checked = loaderini.AutoMipmap; forceTextureFilterCheckBox.Checked = loaderini.TextureFilter; pauseWhenInactiveCheckBox.Checked = loaderini.PauseWhenInactive; stretchFullscreenCheckBox.Checked = loaderini.StretchFullscreen; int scrn = loaderini.ScreenNum; if (scrn > Screen.AllScreens.Length) { scrn = 1; } screenNumComboBox.SelectedIndex = scrn; customWindowSizeCheckBox.Checked = windowHeight.Enabled = maintainWindowAspectRatioCheckBox.Enabled = loaderini.CustomWindowSize; windowWidth.Enabled = loaderini.CustomWindowSize && !loaderini.MaintainWindowAspectRatio; System.Drawing.Rectangle rect = Screen.PrimaryScreen.Bounds; foreach (Screen screen in Screen.AllScreens) { rect = System.Drawing.Rectangle.Union(rect, screen.Bounds); } windowWidth.Maximum = rect.Width; windowWidth.Value = Math.Max(windowWidth.Minimum, Math.Min(rect.Width, loaderini.WindowWidth)); windowHeight.Maximum = rect.Height; windowHeight.Value = Math.Max(windowHeight.Minimum, Math.Min(rect.Height, loaderini.WindowHeight)); suppressEvent = true; maintainWindowAspectRatioCheckBox.Checked = loaderini.MaintainWindowAspectRatio; suppressEvent = false; if (!File.Exists(datadllpath)) { MessageBox.Show(this, "CHRMODELS.dll could not be found.\n\nCannot determine state of installation.", Text, MessageBoxButtons.OK, MessageBoxIcon.Warning); installButton.Hide(); } else if (File.Exists(datadllorigpath)) { installed = true; installButton.Text = "Uninstall loader"; MD5 md5 = MD5.Create(); byte[] hash1 = md5.ComputeHash(File.ReadAllBytes(loaderdllpath)); byte[] hash2 = md5.ComputeHash(File.ReadAllBytes(datadllpath)); if (!hash1.SequenceEqual(hash2)) { if (MessageBox.Show(this, "Installed loader DLL differs from copy in mods folder.\n\nDo you want to overwrite the installed copy?", Text, MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes) { File.Copy(loaderdllpath, datadllpath, true); } } } }
public override void Run(IWwtContext context) { string wwtTilesDir = ConfigurationManager.AppSettings["WWTTilesDir"]; string dsstoastpng = WWTUtil.GetCurrentConfigShare("DSSTOASTPNG", true); string query = context.Request.Params["Q"]; string[] values = query.Split(','); int level = Convert.ToInt32(values[0]); int tileX = Convert.ToInt32(values[1]); int tileY = Convert.ToInt32(values[2]); int octsetlevel = level; string filename; if (level > 20) { context.Response.Write("No image"); context.Response.Close(); return; } if (level < 8) { context.Response.ContentType = "image/png"; Stream s = PlateTilePyramid.GetFileStream(wwtTilesDir + "\\BmngMerBase.plate", level, tileX, tileY); int length = (int)s.Length; byte[] data = new byte[length]; s.Read(data, 0, length); context.Response.OutputStream.Write(data, 0, length); context.Response.Flush(); context.Response.End(); return; } else if (level < 10) { int L = level; int X = tileX; int Y = tileY; string mime = "png"; int powLev5Diff = (int)Math.Pow(2, L - 2); int X32 = X / powLev5Diff; int Y32 = Y / powLev5Diff; filename = string.Format(wwtTilesDir + @"\BmngMerL2X{1}Y{2}.plate", mime, X32, Y32); int L5 = L - 2; int X5 = X % powLev5Diff; int Y5 = Y % powLev5Diff; context.Response.ContentType = "image/png"; Stream s = PlateTilePyramid.GetFileStream(filename, L5, X5, Y5); int length = (int)s.Length; byte[] data = new byte[length]; s.Read(data, 0, length); context.Response.OutputStream.Write(data, 0, length); context.Response.Flush(); context.Response.End(); return; } System.Net.WebClient client = new System.Net.WebClient(); string url = String.Format("http://a{0}.ortho.tiles.virtualearth.net/tiles/a{1}.jpeg?g=15", WWTUtil.GetServerID(tileX, tileY), WWTUtil.GetTileID(tileX, tileY, level, false)); byte[] dat = client.DownloadData(url); client.Dispose(); context.Response.OutputStream.Write(dat, 0, dat.Length); }
/// <summary> /// </summary> /// <param name="url"></param> /// <returns></returns> public static Bitmap GetBitmapByUrl(string url) { var wc = new System.Net.WebClient(); return(new Bitmap(wc.OpenRead(url))); }
static void Main(string[] args) { //if (!TDSM.API.Command.WorldTime.Test()) //{ // Console.WriteLine("Time test failed"); // Console.ReadKey(true); //} //if (!TDSM.API.Permissions.PermissionsManager.IsSet) //{ // var file = System.IO.Path.Combine(TDSM.API.Globals.DataPath, "permissions.xml"); // //if (System.IO.File.Exists(file)) System.IO.File.Delete(file); // if (System.IO.File.Exists(file)) // { // var handler = new TDSM.API.Permissions.XmlSupplier(file); // if (handler.Load()) // TDSM.API.Permissions.PermissionsManager.SetHandler(handler); // } //} Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine(Console.Title = String.Format("TDSM patcher build {0}", Build)); Console.ForegroundColor = ConsoleColor.White; var isMono = Type.GetType("Mono.Runtime") != null; #if SERVER var inFile = "TerrariaServer.exe"; var fileName = "tdsm"; // var outFileMS = fileName + ".microsoft.exe"; // var outFileMN = fileName + ".mono.exe"; var output = fileName + ".exe"; var patchFile = "TDSM.API.dll"; if (!File.Exists(inFile)) { var bin = Path.Combine(Environment.CurrentDirectory, "bin", "x86", "Debug", inFile); if (File.Exists(bin)) { inFile = bin; } } if (!File.Exists(patchFile)) { var bin = Path.Combine(Environment.CurrentDirectory, "bin", "x86", "Debug", patchFile); if (File.Exists(bin)) { patchFile = bin; } } var resourceLib = "Vestris.ResourceLib.dll"; if (!System.IO.File.Exists(resourceLib)) { var bin = System.IO.Path.Combine(Environment.CurrentDirectory, "bin", "x86", "Debug", resourceLib); if (System.IO.File.Exists(bin)) { System.IO.File.Copy(bin, resourceLib); } } #if DEV // if (File.Exists(outFileMS)) File.Delete(outFileMS); // if (File.Exists(outFileMN)) File.Delete(outFileMN); if (File.Exists(output)) { File.Delete(output); } var root = new DirectoryInfo(Environment.CurrentDirectory); while (root.GetDirectories().Where(x => x.Name == "tdsm-patcher").Count() == 0) { if (root.Parent == null) { Console.WriteLine("Failed to find root TDSM project directory"); break; } root = root.Parent; } Copy(root, "Binaries", Path.Combine(Environment.CurrentDirectory), "TDSM.API"); Copy(root, "tdsm-api", Environment.CurrentDirectory); Copy(root, "tdsm-core", Path.Combine(Environment.CurrentDirectory, "Plugins")); //Copy (root, "Restrict", Path.Combine (Environment.CurrentDirectory, "Plugins"), "RestrictPlugin"); Copy(root, "External", Path.Combine(Environment.CurrentDirectory, "Libraries"), "KopiLua", false); Copy(root, "External", Path.Combine(Environment.CurrentDirectory, "Libraries"), "NLua", false); Copy(root, "External", Path.Combine(Environment.CurrentDirectory, "Libraries"), "ICSharpCode.SharpZipLib", false); Copy(root, "External", Path.Combine(Environment.CurrentDirectory, "Libraries"), "Mono.Nat", false); Copy(root, "tdsm-core", Path.Combine(Environment.CurrentDirectory, "Libraries"), "Newtonsoft.Json", true); Copy(root, "tdsm-mysql-connector", Path.Combine(Environment.CurrentDirectory, "Plugins"), "tdsm-mysql-connector", true); // Copy(root, "tdsm-sqlite-connector", Path.Combine(Environment.CurrentDirectory, "Plugins"), "tdsm-sqlite-connector", true); #endif #elif CLIENT var inFile = "Terraria.exe"; var fileName = "tcsm"; var outFileMS = fileName + ".microsoft.exe"; var outFileMN = fileName + ".mono.exe"; var patchFile = "MonoGame.Framework.dll"; #endif if (!File.Exists(inFile)) { //Download the supported vanilla software from our GitHub repo Console.WriteLine("The original Re-Logic TerrariaServer.exe is missing, download?"); if (Console.ReadKey(true).Key == ConsoleKey.Y) { //TODO add throbber const String Url = "https://github.com/DeathCradle/Terraria-s-Dedicated-Server-Mod/raw/master/Official/TerrariaServer.exe"; using (var wc = new System.Net.WebClient()) { var started = DateTime.Now; try { wc.DownloadFile(Url, inFile); } catch (Exception e) { Console.WriteLine(e); Console.WriteLine("Press any key to exit..."); Console.ReadKey(true); return; } var duration = DateTime.Now - started; Console.WriteLine("Download completed in {0:c}", duration); } } else { return; } } var patcher = new Injector(inFile, patchFile); var noVersionCheck = args != null && args.Where(x => x.ToLower() == "-nover").Count() > 0; if (noVersionCheck != true) { var vers = patcher.GetAssemblyVersion(); if (vers != APIWrapper.TerrariaVersion) { Console.WriteLine("This patcher only supports Terraria {0}, but we have detected something else {1}.", APIWrapper.TerrariaVersion, vers); Console.Write("There's a high chance this will fail, continue? (y/n)"); if (Console.ReadKey(true).Key != ConsoleKey.Y) { return; } Console.WriteLine(); } } #if SERVER Console.Write("Opening up classes for API usage..."); patcher.MakeTypesPublic(true); Console.Write("Ok\nHooking command line..."); patcher.PatchCommandLine(); Console.Write("Ok\nHooking players..."); patcher.PatchPlayer(); Console.Write("Ok\nRemoving console handlers..."); patcher.RemoveConsoleHandler(); Console.Write("Ok\nRemoving mono incompatible code..."); patcher.SwapProcessPriority(); ////patcher.HookConsoleTitle(); Console.Write("Ok\nSkipping sysmenus functions..."); patcher.SkipMenu(); //Console.Write("Ok\nFixing code entry..."); //patcher.FixEntryPoint(); Console.Write("Ok\nPatching save paths..."); patcher.FixSavePath(); Console.Write("Ok\nHooking receive buffer..."); patcher.HookMessageBuffer(); //Console.Write("Ok\nAdding the slot manager..."); //patcher.PatchServer(); Console.Write("Ok\nPatching XNA..."); patcher.PatchXNA(true); Console.Write("Ok\nHooking start..."); patcher.HookProgramStart(); Console.Write("Ok\nHooking initialise..."); patcher.HookInitialise(); patcher.HookNetplayInitialise(); Console.Write("Ok\nHooking into world events..."); patcher.HookWorldEvents(); Console.Write("Ok\nHooking statusText..."); patcher.HookStatusText(); //Console.Write("Ok\nHooking NetMessage..."); //patcher.HookNetMessage(); ////Console.Write("Ok\nRemoving client code..."); ////patcher.RemoveClientCode(); Console.Write("Ok\nHooking Server events..."); patcher.HookUpdateServer(); patcher.HookDedServEnd(); Console.Write("Ok\nHooking NPC Spawning..."); patcher.HookNPCSpawning(); Console.Write("Ok\nHooking config..."); patcher.HookConfig(); ////Console.Write("Ok\nRouting socket implementations..."); ////patcher.HookSockets(); Console.Write("Ok\nFixing statusText..."); patcher.FixStatusTexts(); Console.Write("Ok\nHooking invasions..."); patcher.HookInvasions(); Console.Write("Ok\nEnabling rain..."); patcher.EnableRaining(); //Console.Write("Ok\nHooking eclipse..."); //patcher.HookEclipse(); //Console.Write("Ok\nHooking blood moon..."); //patcher.HookBloodMoon(); Console.Write("Ok\nFixing world removal..."); patcher.PathFileIO(); Console.Write("Ok\nRouting network message validity..."); patcher.HookValidPacketState(); //We only need one TDSM.exe if this works... Console.Write("Ok\nRemoving port forwarding functionality..."); patcher.FixNetplay(); // patcher.DetectMissingXNA(); Console.Write("Ok\n"); patcher.InjectHooks(); // patcher.SwapToVanillaTile(); //Holy shit batman! it works // Console.Write("Ok\nPutting Terraria on a diet..."); // patcher.ChangeTileToStruct(); //Console.Write("Ok\nHooking DEBUG..."); //patcher.HookWorldFile_DEBUG(); Console.Write("Ok\n"); //TODO repace Terraria's Console.SetTitles #elif CLIENT Console.Write("Opening up classes for API usage..."); patcher.MakeTypesPublic(false); Console.Write("Ok\nPatching XNA..."); patcher.PatchXNA(false); Console.Write("Ok\n"); #endif #if Release try { #endif // APIWrapper.Initialise(); // byte[] data; // using (var ms = new MemoryStream()) // { // patcher.Terraria.Write(ms); // ms.Seek(0, SeekOrigin.Begin); // data = ms.ToArray(); // } // data = APIWrapper.InvokeEvent(data, true); //// TDSM.API.Globals.Touch(); //// //// TDSM.API.PluginManager.SetHookSource(typeof(HookPoints)); //// TDSM.API.PluginManager.Initialize(TDSM.API.Globals.PluginPath, TDSM.API.Globals.LibrariesPath); //// TDSM.API.PluginManager.LoadPlugins(); //// //// var ctx = new TDSM.API.Plugin.HookContext //// { //// Sender = TDSM.API.Plugin.HookContext.ConsoleSender //// }; //// //// var hookArgs = new HookArgs.PatchServer //// { //// Default = patcher, ////#if SERVER //// IsClient = false, //// IsServer = true ////#elif CLIENT //// IsClient = true, //// IsServer = false ////#endif //// }; //// HookPoints.PatchServer.Invoke(ref ctx, ref hookArgs); // //var apiBuild = APIWrapper.Build; // APIWrapper.Finish(); #if Release } catch (Exception e) { Console.WriteLine("An exception ocurred during PluginManager.LoadPlugins: {0}", e); } #endif Console.ForegroundColor = ConsoleColor.DarkGreen; // //if (isMono || (args != null && args.Where(x => x.ToLower() == "-removeupnp").Count() > 0)) // //{ // // Console.Write("Ok\nRemoving port forwarding functionality..."); // // patcher.FixNetplay(); // //} // Console.Write("Ok\nSaving to {0}...", outFileMN); // patcher.Save(outFileMN, Build, TDSMGuid, fileName); Console.Write("Saving to {0}...", output); patcher.Save(output, Build, TDSMGuid, fileName); //var t = patcher.Terraria.Netplay.Fields.Single(x => x.Name == "serverSock"); patcher.Dispose(); // Console.WriteLine("Ok"); Console.ForegroundColor = ConsoleColor.White; if (!isMono) { Console.Write("Ok\nUpdating icons..."); var res = new Vestris.ResourceLib.IconDirectoryResource(new Vestris.ResourceLib.IconFile("tdsm.ico")); foreach (var fl in new string[] { output }) //outFileMS, outFileMN }) { try { System.Threading.Thread.Sleep(1000); res.SaveTo(fl); } catch { Console.Write("Failed to write icon for: " + fl); } } Console.Write("Ok\nUpdating headers..."); foreach (var fl in new string[] { output }) //outFileMS, outFileMN }) { try { using (var ri = new Vestris.ResourceLib.ResourceInfo()) { System.Threading.Thread.Sleep(1000); ri.Load(fl); var ver = (Vestris.ResourceLib.VersionResource)ri[Vestris.ResourceLib.Kernel32.ResourceTypes.RT_VERSION].First(); var inf = (Vestris.ResourceLib.StringFileInfo)ver["StringFileInfo"]; inf["OriginalFilename"] = fileName + ".exe" + '\0'; inf["InternalName"] = fileName + ".exe" + '\0'; inf["ProductName"] = fileName + '\0'; inf["FileDescription"] = fileName + '\0'; ri.Unload(); ver.SaveTo(fl); } } catch { Console.WriteLine("Failed to write header for: " + fl); } } } #if DEBUG Console.Write("Ok\nUpdating Binaries folder..."); UpdateBinaries(); Console.Write("Ok\nGenerating server.config..."); GenerateConfig(); #endif #if Release || true var noRun = args != null && args.Where(x => x.ToLower() == "-norun").Count() > 0; if (!noRun) { //var current = isMono ? outFileMN : outFileMS; // if (File.Exists("tdsm.exe")) File.Delete("tdsm.exe"); // if (isMono) // { // File.Copy(outFileMN, "tdsm.exe"); // } // else // { // File.Copy(outFileMS, "tdsm.exe"); // } // var current = "tdsm.exe"; Console.WriteLine("Ok"); Console.ForegroundColor = ConsoleColor.DarkGreen; Console.WriteLine("You may now run {0} as you would normally.", output); Console.WriteLine("Press [y] to run {0}, any other key will exit . . .", output); if (Console.ReadKey(true).Key == ConsoleKey.Y) { if (!isMono) { if (File.Exists("server.config")) { System.Diagnostics.Process.Start(output, "-config server.config"); } else { System.Diagnostics.Process.Start(output); } } else { Console.Clear(); using (var ms = new MemoryStream()) { using (var fs = File.OpenRead(output)) { var buff = new byte[256]; while (fs.Position < fs.Length) { var task = fs.Read(buff, 0, buff.Length); ms.Write(buff, 0, task); } } ms.Seek(0L, SeekOrigin.Begin); var asm = System.Reflection.Assembly.Load(ms.ToArray()); try { if (File.Exists("server.config")) { asm.EntryPoint.Invoke(null, new object[] { new string[] { "-config", "server.config", "-noupnp" } }); } else { asm.EntryPoint.Invoke(null, null); } } catch (Exception e) { } } } } } else { Console.WriteLine("Ok\n"); } #endif }
/// <summary> /// Checks mods for updates. ForceUpdateCheck will force the mod to validate against the server (essentially repair mode). It is not used for rate limiting! /// </summary> /// <param name="modsToCheck"></param> /// <param name="forceUpdateCheck"></param> /// <returns></returns> public static List <ModUpdateInfo> CheckForModUpdates(List <Mod> modsToCheck, bool forceUpdateCheck) { string updateFinalRequest = UpdateManifestEndpoint; bool first = true; foreach (var mod in modsToCheck) { if (mod.ModModMakerID > 0) { //Modmaker style if (first) { updateFinalRequest += "?"; first = false; } else { updateFinalRequest += "&"; } updateFinalRequest += "modmakerupdatecode[]=" + mod.ModModMakerID; } else if (mod.ModClassicUpdateCode > 0) { //Classic style if (first) { updateFinalRequest += "?"; first = false; } else { updateFinalRequest += "&"; } updateFinalRequest += "classicupdatecode[]=" + mod.ModClassicUpdateCode; } //else if (mod.NexusModID > 0) //{ // //Classic style // if (first) // { // updateFinalRequest += "?"; // first = false; // } // else // { // updateFinalRequest += "&"; // } // updateFinalRequest += "nexusupdatecode[]=" + mod.ModClassicUpdateCode; //} } using var wc = new System.Net.WebClient(); try { string updatexml = wc.DownloadStringAwareOfEncoding(updateFinalRequest); XElement rootElement = XElement.Parse(updatexml); var modUpdateInfos = (from e in rootElement.Elements("mod") select new ModUpdateInfo { changelog = (string)e.Attribute("changelog"), versionstr = (string)e.Attribute("version"), updatecode = (int)e.Attribute("updatecode"), serverfolder = (string)e.Attribute("folder"), sourceFiles = (from f in e.Elements("sourcefile") select new SourceFile { lzmahash = (string)f.Attribute("lzmahash"), hash = (string)f.Attribute("hash"), size = (int)f.Attribute("size"), lzmasize = (int)f.Attribute("lzmasize"), relativefilepath = f.Value, timestamp = (Int64?)f.Attribute("timestamp") ?? (Int64)0 }).ToList(), }).ToList(); foreach (var modUpdateInfo in modUpdateInfos) { modUpdateInfo.ResolveVersionVar(); //Calculate update information var matchingMod = modsToCheck.FirstOrDefault(x => x.ModClassicUpdateCode == modUpdateInfo.updatecode); if (matchingMod != null && (forceUpdateCheck || matchingMod.ParsedModVersion < modUpdateInfo.version)) { modUpdateInfo.mod = matchingMod; modUpdateInfo.SetLocalizedInfo(); string modBasepath = matchingMod.ModPath; foreach (var serverFile in modUpdateInfo.sourceFiles) { var localFile = Path.Combine(modBasepath, serverFile.relativefilepath); if (File.Exists(localFile)) { var info = new FileInfo(localFile); if (info.Length != serverFile.size) { modUpdateInfo.applicableUpdates.Add(serverFile); } else { //Check hash CLog.Information("Hashing file for update check: " + localFile, Settings.LogModUpdater); var md5 = Utilities.CalculateMD5(localFile); if (md5 != serverFile.hash) { modUpdateInfo.applicableUpdates.Add(serverFile); } } } else { modUpdateInfo.applicableUpdates.Add(serverFile); } } //Files to remove calculation var modFiles = Directory.GetFiles(modBasepath, "*", SearchOption.AllDirectories).Select(x => x.Substring(modBasepath.Length + 1)).ToList(); modUpdateInfo.filesToDelete.AddRange(modFiles.Except(modUpdateInfo.sourceFiles.Select(x => x.relativefilepath), StringComparer.InvariantCultureIgnoreCase).Distinct().ToList()); //Todo: Add security check here to prevent malicious values modUpdateInfo.TotalBytesToDownload = modUpdateInfo.applicableUpdates.Sum(x => x.lzmasize); } return(modUpdateInfos); } } catch (Exception e) { Log.Error("Error checking for mod updates: " + App.FlattenException(e)); Crashes.TrackError(e, new Dictionary <string, string>() { { "Update check URL", updateFinalRequest } }); } return(null); }
public static String GetURLContents(this string @url) { System.Net.WebClient webClient = new System.Net.WebClient(); return(webClient.DownloadString(@url)); }
public Process readConfigAndStart(bool restart = false) { Console.WriteLine("Updating network parameters"); Console.WriteLine($"Current server name :{_config.serverName}"); if (string.IsNullOrWhiteSpace(_config.serverName)) { throw new Exception("servename is required"); } if (string.IsNullOrWhiteSpace(_config.serverPrivateIp)) { throw new Exception("serverPrivateIp is required"); } S3Object serverRegistry = null; try { serverRegistry = readS3Object(_SERVER_REGISTRY); } catch (Exception ex) { if (ex.Message.Contains("The specified key does not exist")) { Console.WriteLine($"no registryfile {_SERVER_REGISTRY}"); } else { throw ex; } } var serverMap = null == serverRegistry ? new ServerMap() : JsonConvert.DeserializeObject <ServerMap>(serverRegistry.value); Console.WriteLine($"Got server map, we have {serverMap.Count} servers"); var myConfigChanged = false; var updateRegistry = false; if (!serverMap.ContainsKey(_config.serverName)) { Console.WriteLine($"server name :{_config.serverName} not found creating"); serverMap[_config.serverName] = new CoreServer { //ordinalNumber = newOrdinal, isManager = _config.isManager, initialPublicIp = _config.serverPublicIp, serverPrivateIp = _config.serverPrivateIp }; updateRegistry = true; } if (serverMap[_config.serverName].initialPublicIp != _config.serverPublicIp) { serverMap[_config.serverName].initialPublicIp = _config.serverPublicIp; updateRegistry = true; } if (updateRegistry) { saveS3Object(_SERVER_REGISTRY, JsonConvert.SerializeObject(serverMap)); myConfigChanged = true; } if (serverMap[_config.serverName].serverPrivateIp != _config.serverPrivateIp) { throw new Exception("found serverIP {serverMap[serverName].serverPrivateIp} from registry doesn't match provided {serverPrivateIp}"); } var confData = new string[] { $"Name = {_config.serverName}", "AddressFamily = ipv4", "Interface = tun0" }; { var otherServers = serverMap.Where(v => v.Key != _config.serverName && !String.IsNullOrWhiteSpace(v.Value.initialPublicIp)) .Select(m => $"ConnectTo = {m.Key}").ToArray(); confData = confData.Concat(otherServers).ToArray(); } if (String.IsNullOrWhiteSpace(_config.tincExecutable)) { throw new Exception("tinc path needed"); } if (!Directory.Exists(_confLocation)) { Directory.CreateDirectory(_confLocation); } var hostConfFileWIthPublicKeys = Path.Combine(_confLocation, "hosts", _config.serverName); if (!File.Exists(hostConfFileWIthPublicKeys)) { myConfigChanged = true; var iinitCmd = $"init {_config.serverName}"; Console.WriteLine($"Running :{_config.tincExecutable} {iinitCmd} "); var process = Process.Start(_config.tincExecutable, iinitCmd); process.WaitForExit(); Console.WriteLine($"completed : {iinitCmd} "); } if (!restart) { var confFile = Path.Combine(_confLocation, "tinc.conf"); Console.WriteLine($"Writing conf file {confFile}"); File.WriteAllLines(confFile, confData); } { Console.WriteLine($"Updating file {hostConfFileWIthPublicKeys}"); if (!File.Exists(hostConfFileWIthPublicKeys)) { throw new Exception($"file {hostConfFileWIthPublicKeys} not found. most likely tinc init failed."); } var hostInfo = new string[] { }; if (!String.IsNullOrWhiteSpace(_config.serverPublicIp)) { hostInfo = new string[] { $"Address = {_config.serverPublicIp}" }; } hostInfo = hostInfo.Concat(new[] { $"Subnet = {_config.serverPrivateIp}/32" }).ToArray(); var KeyInfo = File.ReadAllLines(hostConfFileWIthPublicKeys); var keyStrated = false; KeyInfo = KeyInfo.Select(s => { if (!!String.IsNullOrWhiteSpace(_config.serverPublicIp) && s.StartsWith("Address = ")) { var currentAddress = s.Replace("Address = ", ""); if (currentAddress != _config.serverPublicIp) { myConfigChanged = true; Console.WriteLine("public address changed will trigger change request"); } } if (!keyStrated && !s.Contains("BEGIN RSA PUBLIC KEY")) { return(null); } keyStrated = true; return(s); }) .Where(s => null != s) .ToArray(); hostInfo = hostInfo.Concat(KeyInfo).ToArray(); File.WriteAllLines(hostConfFileWIthPublicKeys, hostInfo); Console.WriteLine($"done with {hostConfFileWIthPublicKeys}. Updating to registry"); saveS3Object(key: $"{_SERVER_HOST_FOLDER}{_config.serverName}", content: String.Join('\n', hostInfo)); Console.WriteLine("done uploading"); } { Console.WriteLine("getting other hosts"); var otherServersValues = serverMap.Where(v => v.Key != _config.serverName).Select(v => { var ohostdata = readS3Object($"{_SERVER_HOST_FOLDER}{v.Key}"); return(new { v.Key, data = ohostdata.value }); }).ToArray(); foreach (var v in otherServersValues) { var hostConf = Path.Combine(_confLocation, "hosts", v.Key); Console.WriteLine($"writing host info :{hostConf}"); File.WriteAllText(hostConf, v.data); } Console.WriteLine("getting other hosts done"); } if (!restart) { var tincupfile = Path.Combine(_confLocation, "tinc-up"); Console.WriteLine($"creating file {tincupfile}"); //tinc broke after 1688.5.3 now it needs a delay after creating the TUN device var fileText = new[] { "#!/bin/sh", "sleep 0.1", $"ifconfig $INTERFACE {_config.serverPrivateIp} netmask 255.255.255.0" }; File.WriteAllLines(tincupfile, fileText); Console.WriteLine($"done with {tincupfile}"); } if (myConfigChanged) { var otherServersValues = serverMap.Where(v => v.Key != _config.serverName && !String.IsNullOrWhiteSpace(v.Value.initialPublicIp)).Select(v => v.Value.initialPublicIp).ToArray(); foreach (var publicserer in otherServersValues) { try { var done = new System.Net.WebClient().DownloadString($"http://{publicserer}:{Program._myPort}/configchanged"); } catch (Exception ex) { ex.PrintDetails($"failed while change notifying :{publicserer}:{Program._myPort}"); } } } { //https://www.tinc-vpn.org/documentation-1.1/tinc-commands.html var initCmd = $"start -D " + string.Join(' ', _tincARgs); if (!String.IsNullOrWhiteSpace(_config.tincExtraParams)) { initCmd += (" " + _config.tincExtraParams); } if (restart) { initCmd = "restart"; } Console.WriteLine($"Running :{_config.tincExecutable} {initCmd} "); return(Process.Start(_config.tincExecutable, initCmd)); } }
public void Getter() { do { Console.Clear(); int fc = 0, mc = 0; System.Net.WebClient wc = new System.Net.WebClient(); byte[] raw = wc.DownloadData("http://api.lod-misis.ru/testassignment"); string webData = System.Text.Encoding.UTF8.GetString(raw); string[] words = webData.Split(delimiterChars); Console.Write("Recent events:\n"); foreach (string item in words) { Console.WriteLine(item); if (item == "Male:Died") { mc = mc - 1; } else { if (item == "Male:Born") { mc = mc + 1; } else { if (item == "Female:Died") { fc = fc - 1; } else { if (item == "Female:Born") { fc = fc + 1; } } } } // надо разобрать эту ахинею } Console.WriteLine("_________________"); if (mc < 0) { Console.WriteLine("Погибло мужчин: " + Math.Abs(mc)); } if (mc > 0) { Console.WriteLine("Родилось мужчин: " + Math.Abs(mc)); } if (fc < 0) { Console.WriteLine("Погибло женщин: " + Math.Abs(fc)); } if (fc > 0) { Console.WriteLine("Родилось женщин: " + Math.Abs(fc)); } Console.WriteLine("_________________"); Thread.Sleep(5000); } while (true); }