protected void UserAuthenticate(object sender, AuthenticateEventArgs e) { if (Membership.ValidateUser(this.LoginForm.UserName, this.LoginForm.Password)) { e.Authenticated = true; return; } string url = string.Format( this.ForumAuthUrl, HttpUtility.UrlEncode(this.LoginForm.UserName), HttpUtility.UrlEncode(this.LoginForm.Password) ); WebClient web = new WebClient(); string response = web.DownloadString(url); if (response.Contains(groupId)) { e.Authenticated = Membership.ValidateUser("Premier Subscriber", "danu2HEt"); this.LoginForm.UserName = "******"; HttpCookie cookie = new HttpCookie("ForumUsername", this.LoginForm.UserName); cookie.Expires = DateTime.Now.AddMonths(2); Response.Cookies.Add(cookie); } }
public void UpdateFiles() { try { WriteLine("Local version: " + Start.m_Version); WebClient wc = new WebClient(); string versionstr; using(System.IO.StreamReader sr = new System.IO.StreamReader(wc.OpenRead(baseurl + "version.txt"))) { versionstr = sr.ReadLine(); } Version remoteversion = new Version(versionstr); WriteLine("Remote version: " + remoteversion); if(Start.m_Version < remoteversion) { foreach(string str in m_Files) { WriteLine("Updating: " + str); wc.DownloadFile(baseurl + str, str); } } wc.Dispose(); WriteLine("Update complete"); } catch(Exception e) { WriteLine("Update failed:"); WriteLine(e); } this.Button_Ok.Enabled = true; }
private void CreateIncident() { WebClient client = new WebClient(); client.Headers[HttpRequestHeader.Accept] = "application/json"; client.Headers[HttpRequestHeader.ContentType] = "application/json"; client.UploadStringCompleted += (object source, UploadStringCompletedEventArgs e) => { if (e.Error != null || e.Cancelled) { Console.WriteLine("Error" + e.Error); Console.ReadKey(); } }; JavaScriptSerializer js = new JavaScriptSerializer(); TriggerDetails triggerDetails = new TriggerDetails(Component, Details); var detailJson = js.Serialize(triggerDetails); //Alert name should be unique for each alert - as alert name is used as incident key in pagerduty. string key = ConfigurationManager.AppSettings["PagerDutyServiceKey"]; if (!string.IsNullOrEmpty(EscPolicy)) { key = ConfigurationManager.AppSettings["PagerDutySev1ServiceKey"]; } if (string.IsNullOrEmpty(key)) { key = ConfigurationManager.AppSettings["PagerDutyServiceKey"]; } Trigger trigger = new Trigger(key,AlertName,AlertSubject,detailJson); var triggerJson = js.Serialize(trigger); client.UploadString(new Uri("https://events.pagerduty.com/generic/2010-04-15/create_event.json"), triggerJson); }
public HttpClient (Uri baseUrl) { // this.baseUrl = baseUrl; visualizeUrl = new Uri (baseUrl, "visualize"); stopVisualizingUrl = new Uri (baseUrl, "stopVisualizing"); client = new WebClient (); }
public GamePlayHistory AddNewGameHistory(GamePlayHistory gamePlayHistory) { if (string.IsNullOrEmpty(ToSavourToken)) { throw new InvalidOperationException("No ToSavour Token is set"); } RequestClient = new WebClient(); RequestClient.Headers.Add("Authorization", ToSavourToken); RequestClient.Headers.Add("Content-Type", "application/json"); var memoryStream = new MemoryStream(); GetSerializer(typeof(GamePlayHistory)).WriteObject(memoryStream, gamePlayHistory); memoryStream.Position = 0; var sr = new StreamReader(memoryStream); var json = sr.ReadToEnd(); var userJsonString = RequestClient.UploadString(_host + @"gamehistories", json); var byteArray = Encoding.ASCII.GetBytes(userJsonString); var stream = new MemoryStream(byteArray); var returnedGamePlayHistory = GetSerializer(typeof(GamePlayHistory)).ReadObject(stream) as GamePlayHistory; return returnedGamePlayHistory; }
public static string DELETE(string uri, IDictionary<string, string> args) { try { WebClient client = new WebClient(); client.Encoding = Encoding.UTF8; client.Headers["Connection"] = "Keep-Alive"; StringBuilder formattedParams = new StringBuilder(); IDictionary<string, string> parameters = new Dictionary<string, string>(); foreach (var arg in args) { parameters.Add(arg.Key, arg.Value); formattedParams.AppendFormat("{0}={{{1}}}", arg.Key, arg.Key); } //Formatted URI Uri baseUri = new Uri(uri); client.UploadStringCompleted += new UploadStringCompletedEventHandler(client_UploadStringCompletedDelete); client.UploadStringAsync(baseUri, "DELETE", string.Empty); allDone.Reset(); allDone.WaitOne(); return requestResult; } catch (WebException ex) { return ReadResponse(ex.Response.GetResponseStream()); } }
/// <summary> /// Used to perform the actual conversion of the input string /// </summary> /// <param name="InputString"></param> /// <returns></returns> public override string TranslateString(string InputString) { Console.WriteLine("Processing: " + InputString); string result = ""; using (WebClient client = new WebClient()) { using (Stream data = client.OpenRead(this.BuildRequestString(InputString))) { using (StreamReader reader = new StreamReader(data)) { string s = reader.ReadToEnd(); result = ExtractTranslatedString(s); reader.Close(); } data.Close(); } } return result; }
public static List<CoinInformation> GetCoinInformation(string userAgent = "", BaseCoin profitabilityBasis = BaseCoin.Bitcoin) { WebClient client = new WebClient(); if (!string.IsNullOrEmpty(userAgent)) client.Headers.Add("user-agent", userAgent); string apiUrl = GetApiUrl(profitabilityBasis); string jsonString = client.DownloadString(apiUrl); JArray jsonArray = JArray.Parse(jsonString); List<CoinInformation> result = new List<CoinInformation>(); foreach (JToken jToken in jsonArray) { CoinInformation coinInformation = new CoinInformation(); coinInformation.PopulateFromJson(jToken); if (coinInformation.Difficulty > 0) //only add coins with valid info since the user may be basing //strategies on Difficulty result.Add(coinInformation); } return result; }
public async Task<Queue> DownloadQueue() { using (WebClient w = new WebClient()) { return this.ConvertApiResultToQueue(await w.DownloadStringTaskAsync("http://localhost:8080/sabnzbd/api?mode=queue&output=xml")); } }
public List<SearchResult> Search(string searchQuery) { string url = "http://www.imdb.com/find?q={0}&s=all".Fmt(searchQuery); string html = new WebClient().DownloadString(url); CQ dom = html; var searchResults = new List<SearchResult>(); foreach (var fragment in dom.Select("table.findList tr.findResult")) { var searchResult = new SearchResult(); searchResult.ImageUrl = fragment.Cq().Find(".primary_photo > a > img").Attr("src"); searchResult.Text = fragment.Cq().Find(".result_text").Html(); searchResult.Text = StringEx.RemoveHtmlTags(searchResult.Text); string filmUrl = fragment.Cq().Find(".result_text > a").Attr("href"); filmUrl = filmUrl.Replace("/title/", ""); searchResult.FilmId = filmUrl.Substring(0, filmUrl.IndexOf("/")); searchResults.Add(searchResult); } return searchResults; }
public List<Thread> GetFilmThreads(string filmId, int? page = null) { string url = "http://www.imdb.com/title/{0}/board".Fmt(filmId); if (page.HasValue) url += "?p=" + page.Value; string html = new WebClient().DownloadString(url); CQ dom = html; var threadHtmlFragments = dom.Select("div.threads > div.thread"); var threads = new List<Thread>(); foreach (var fragment in threadHtmlFragments) { if (fragment["class"] == "thread header") continue; var cq = fragment.Cq(); var thread = new Thread(); thread.Title = cq.Find(">.title a").Html(); thread.Url = cq.Find(">.title a").Attr("href"); thread.Id = thread.Url.Substring(thread.Url.LastIndexOf("/") + 1); thread.UserUrl = cq.Find(".author .user a.nickname").Attr("href"); thread.UserImage = cq.Find(".author .user .avatar > img").Attr("src"); thread.UserName = cq.Find(".author .user a.nickname").Html(); thread.RepliesCount = int.Parse(cq.Find(".replies a").Html().Trim()); thread.Timestamp = ParseDate(cq.Find(".timestamp > a > span").Attr("title"), hasSeconds: false); threads.Add(thread); } return threads; }
public ItemCrawler(Uri url) { _htmlDocument = new HtmlDocument(); var html = new WebClient().DownloadString(url.OriginalString); _htmlDocument.LoadHtml(html); _document = _htmlDocument.DocumentNode; }
/// <summary> /// loads a xml from the web server /// </summary> /// <param name="_url">URL of the XML file</param> /// <returns>A XmlDocument object of the XML file</returns> public static XmlDocument LoadXml(string _url) { var xmlDoc = new XmlDocument(); try { while (Helper.pingForum("forum.mods.de", 10000) == false) { Console.WriteLine("Can't reach forum.mods.de right now, try again in 15 seconds..."); System.Threading.Thread.Sleep(15000); } xmlDoc.Load(_url); } catch (XmlException) { while (Helper.pingForum("forum.mods.de", 100000) == false) { Console.WriteLine("Can't reach forum.mods.de right now, try again in 15 seconds..."); System.Threading.Thread.Sleep(15000); } WebClient client = new WebClient(); ; Stream stream = client.OpenRead(_url); StreamReader reader = new StreamReader(stream); string content = reader.ReadToEnd(); content = RemoveTroublesomeCharacters(content); xmlDoc.LoadXml(content); } return xmlDoc; }
public async override Task<IEnumerable<string>> GetVersion(string packageName) { if (string.IsNullOrEmpty(packageName)) return Enumerable.Empty<string>(); string url = $"http://registry.npmjs.org/{packageName}"; string json = "{}"; using (var client = new WebClient()) { json = await client.DownloadStringTaskAsync(url); } var array = JObject.Parse(json); var time = array["time"]; if (time == null) return Enumerable.Empty<string>(); var props = time.Children<JProperty>(); return from version in props where char.IsNumber(version.Name[0]) orderby version.Name descending select version.Name; }
public List<string> FindOLIDsByTitle(string title) { if (string.IsNullOrEmpty(title)) { throw new ArgumentNullException("title"); } // OpenLibrary is friendly with the book title whose first character is captial. title = title[0].ToString().ToUpper() + title.Substring(1); var uri = baseUrl + "things?query={\"type\":\"\\/type\\/edition\",\"title~\":\"" + title + "*\"}&prettyprint=true&text=true"; List<string> oLIDs = new List<string>(); using (var webClient = new WebClient()) { var response = JsonConvert.DeserializeObject<Thing>(webClient.DownloadString(uri)); if (response.Status.Equals("ok", StringComparison.OrdinalIgnoreCase)) { foreach (var oLID in response.Result) { string strToRemove = "/books/"; if (oLID.StartsWith(strToRemove)) { oLIDs.Add(oLID.Replace(strToRemove, "")); } } } } return oLIDs; }
public async Task<long> GetPageSize(CancellationToken cToken) { WebClient wc = new WebClient(); Stopwatch sw = Stopwatch.StartNew(); byte[] apressData = await wc.DownloadDataTaskAsync(TargetUrl); Debug.WriteLine("Elapsed ms: {0}", sw.ElapsedMilliseconds); return apressData.LongLength; //List<long> results = new List<long>(); //for (int i = 0; i < 10; i++) //{ // if (!cToken.IsCancellationRequested) // { // Debug.WriteLine("Making Request: {0}", i); // byte[] apressData = await wc.DownloadDataTaskAsync(TargetUrl); // results.Add(apressData.LongLength); // } // else // { // Debug.WriteLine("Cancelled"); // return 0; // } //} ////byte[] apressData = await wc.DownloadDataTaskAsync(TargetUrl); //Debug.WriteLine("Elapsed ms: {0}", sw.ElapsedMilliseconds); ////return apressData.LongLength; //return (long)results.Average(); }
// get Weather Data by Location (Long, Lat) public WeatherData GetWeatherData(WeatherDataEnum platform) { var json_data = string.Empty; if (platform != WeatherDataEnum.OPEN_WEATHER_MAP) throw new WeatherDataServiceException("Unrecognized Enum Type. Try to use OPEN_WEATHER_MAP"); using (var w = new WebClient()) { // attempt to download JSON data as a string try { string url = "http://api.openweathermap.org/data/2.5/weather?lat=" + this.location.latitude.ToString() + "&lon=" + this.location.longitude.ToString(); Console.WriteLine(url); json_data = w.DownloadString(url); // if string with JSON data is not empty, deserialize it to class and return its instance return !string.IsNullOrEmpty(json_data) ? JsonConvert.DeserializeObject<WeatherData>(json_data) : WeatherData.GetInstance(null); //return this.GetWeather(); } catch (WeatherDataServiceException e) { Console.WriteLine("Error : " + e.StackTrace); } } return null; }
public void UpdatePACFromGFWList(Configuration config) { WebClient http = new WebClient(); http.Proxy = new WebProxy(IPAddress.Loopback.ToString(), config.localPort); http.DownloadStringCompleted += http_DownloadStringCompleted; http.DownloadStringAsync(new Uri(GFWLIST_URL)); }
public User GetUserDetailsFrom(string token) { User user = new User(); string parameters = String.Format("apiKey={0}&token={1}&format=xml", ApplicationSettingsFactory.GetApplicationSettings().JanrainApiKey, token); string response; using (var w = new WebClient()) { response = w.UploadString("https://rpxnow.com/api/v2/auth_info", parameters); } var xmlResponse = XDocument.Parse(response); var userProfile = (from x in xmlResponse.Descendants("profile") select new { id = x.Element("identifier").Value, email = (string)x.Element("email") ?? "No Email" }).SingleOrDefault(); if (userProfile != null) { user.AuthenticationToken = userProfile.id; user.Email = userProfile.email; user.IsAuthenticated = true; } else user.IsAuthenticated = false; return user; }
public string downloadBinaryFile_Action(string urlOfFileToFetch, string targetFileOrFolder) { if (urlOfFileToFetch.is_Null() || targetFileOrFolder.is_Null()) return null; var targetFile = targetFileOrFolder; if (Directory.Exists(targetFileOrFolder)) targetFile = targetFileOrFolder.pathCombine(urlOfFileToFetch.fileName()); PublicDI.log.debug("Downloading Binary File {0}", urlOfFileToFetch); lock (this) { using (var webClient = new WebClient()) { try { byte[] pageData = webClient.DownloadData(urlOfFileToFetch); O2Kernel_Files.WriteFileContent(targetFile, pageData); PublicDI.log.debug("Downloaded File saved to: {0}", targetFile); webClient.Dispose(); GC.Collect(); // because of WebClient().GetRequestStream prob return targetFile; } catch (Exception ex) { PublicDI.log.ex(ex); } } } GC.Collect(); // because of WebClient().GetRequestStream prob return null; }
private int DownloadTranslations(int translationId, int chapterNo) { int status = 0; Dispatcher.BeginInvoke(() => { busyIndicator.IsRunning = true; try { String xmlUrl = "http://web.quran360.com/services/Verse.php?translationId=" + translationId + "&chapterId=" + chapterNo + "&format=xml"; WebClient client = new WebClient(); client.OpenReadCompleted += (sender, e) => { if (e.Error != null) return; Stream str = e.Result; XDocument xdoc = XDocument.Load(str); // take results List<Verse> verses = (from verse in xdoc.Descendants("verse") select new Verse() { id = (int)verse.Element("id"), translation_id = (int)verse.Element("translation_id"), chapter_id = (int)verse.Element("chapter_id"), verse_id = (int)verse.Element("verse_id"), verse_text = (string)verse.Element("verse_text") }).ToList(); // close str.Close(); //busyIndicator.Content = "Downloading Chapter " + chapterNo + " ..."; for (int i = 0; i < verses.Count(); i++) { (Application.Current as App).db.AddVerseTrans(verses[i]); System.Diagnostics.Debug.WriteLine(verses[i].chapter_id + ":" + verses[i].verse_id); busyIndicator.Content = "Downloading (" + verses[i].chapter_id + ":" + verses[i].verse_id + ") ..."; } busyIndicator.IsRunning = false; status = 1; FillData(); }; client.OpenReadAsync(new Uri(xmlUrl, UriKind.Absolute)); } catch (Exception e) { System.Diagnostics.Debug.WriteLine(e.StackTrace); MessageBox.Show("Internet connection required."); } }); return status; }
public static void GetStationCollectionAsync(IQueryBuilder url, RealTimeDataDelegate callback) { try { if (url == null) throw new Exception("Cannot work with null-objects"); if (String.IsNullOrEmpty(url.Url)) throw new Exception("Url cannot be empty"); var client = new WebClient(); client.DownloadStringCompleted += (s, e) => { if (e.Error != null) throw e.Error; if (e.Result == null) return; var collection = JsonHelper.Deserialize< IList<Station>>(e.Result); callback(new ObservableCollection<Station>(collection)); }; client.DownloadStringAsync(new Uri(url.Url)); } catch (Exception) { throw; } }
static WebClient SetupClient() { var webClient = new WebClient(); webClient.Headers.Add("user-agent", DefaultUserAgent); webClient.DownloadProgressChanged += OnDownloadProgressChanged; return webClient; }
public override void Use(Player p, string message) { if (p == null) { Player.SendMessage(p, "This command can only be used in-game!"); return; } if (!Directory.Exists("extra/copy")) Directory.CreateDirectory("extra/copy"); if (!File.Exists("extra/copy/christmastree.copy")) { Player.SendMessage(p, "ChrismasTree copy doesn't exist. Downloading..."); try { using (WebClient WEB = new WebClient()) WEB.DownloadFile("http://dekemaserv.com/xmas.copy", "extra/copy/christmastree.copy"); } catch { Player.SendMessage(p, "Sorry, downloading failed. Please try again later."); return; } } Command.all.Find("retrieve").Use(p, "christmastree"); Command.all.Find("paste").Use(p, ""); ushort[] loc = p.getLoc(false); Command.all.Find("click").Use(p, loc[0] + " " + loc[1] + " " + loc[2]); }
// internet connection test method public static EnvironmentCheckResult ConnectedToInternetTest() { EnvironmentCheckResult result = new EnvironmentCheckResult(); result.Message = "You are connected to the Internet."; result.DidPass = true; WebClient client = new WebClient(); try { string results = client.DownloadString( "https://rockrms.blob.core.windows.net/install/html-alive.txt" ); if ( !results.Contains( "success" ) ) { result.DidPass = false; result.Message = "It does not appear you are connected to the Internet. Rock requires a connection to download the installer."; } } catch ( Exception ex ) { result.DidPass = false; result.Message = "Could not connect to the Internet. Error: " + ex.Message; return result; } finally { client = null; } return result; }
public void read_api(string content_id) { WebClient myService = new WebClient(); url = null; try { if (content_id != null) { SetLoadingPanelVisibility(true); url = "http://mstage.truelife.com/api_movietv/drama/music?method=getinfo&content_id="; Debug.WriteLine(url + content_id); myService.DownloadStringAsync(new Uri(url + content_id)); myService.DownloadStringCompleted += new DownloadStringCompletedEventHandler(GetTotal_Completed); } else { throw new Exception("Content id is NULL !"); } } catch (WebException ex) { MessageBox.Show(ex.Message); } }
private ImageSettings GetLatestImageInfo() { ImageSettings iSettings = null; try { using (var wc = new WebClient()) { var json = wc.DownloadString("http://himawari8-dl.nict.go.jp/himawari8/img/D531106/latest.json?" + Guid.NewGuid()); var iInfo = JsonConvert.DeserializeObject<ImageInfo>(json); iSettings = new ImageSettings { Width = 550, Level = "4d", NumBlocks = 4, TimeString = iInfo.Date.AddHours(Settings.Default.Difference).ToString("yyyy/MM/dd/HHmmss", CultureInfo.InvariantCulture) }; } } catch (WebException ex) { _notify(NotifificationType.Error, "Error receiving image information: " + ex.Message); } catch (Exception ex) { _notify(NotifificationType.Error, "Unknown error receiving image information: " + ex.Message); throw; } return iSettings; }
public void Download(DownloadTarget target) { if (target == null) { throw new ArgumentNullException("target"); } Console.WriteLine("[Downloader] Processing " + target.Target.ToString()); try { WebClient client = new WebClient(); target.Content = client.DownloadString(target.Target); Console.WriteLine( string.Format(CultureInfo.InvariantCulture, "URL {0} downloaded", target.TargetAddress)); } catch (System.Net.WebException) { Console.WriteLine( string.Format( CultureInfo.InvariantCulture, "URL could not be downloaded", target.TargetAddress)); return; } this.Harvester.Send(harvester => harvester.HarvestLinks(target)); Console.WriteLine("[Downloader] Processed " + target.Target.ToString()); }
public List<BookData> FindBooksByOLIDs(List<string> oLIDs) { if (oLIDs == null) { throw new ArgumentNullException("oLIDs"); } List<BookData> books = new List<BookData>(); var bibkeys = new StringBuilder(); foreach (var oLID in oLIDs) { bibkeys.Append(oLID); bibkeys.Append(","); } if (bibkeys.Length != 0) { var getUri = baseUrl + "books?bibkeys=OLID:" + bibkeys.ToString().TrimEnd(new char[] { ',' }) + "&format=json&jscmd=data"; using (var webClient = new WebClient()) { var response = JsonConvert.DeserializeObject<Dictionary<string, BookData>>(webClient.DownloadString(getUri)); if (response.Count() > 0) { books = new List<BookData>(); foreach (var value in response.Values) { books.Add(value); } } } } return books; }
public YouTubeDownloader(string youTubeVideoUrl) { _internalDownloader = new WebClient(); _youTubeVideoUrl = youTubeVideoUrl; RegisterDownloadEventHandlers(); }
/// <summary> 根据参数执行WebService </summary> public static object InvokeWebService(string url, string classname, string methodname, object[] args) { try { string _namespace = "WebService"; if (string.IsNullOrEmpty(classname)) { classname = GetClassName(url); } //获取服务描述语言(WSDL) Net.WebClient wc = new Net.WebClient(); Stream stream = wc.OpenRead(url + "?WSDL"); //【1】 Web.Services.Description.ServiceDescription sd = Web.Services.Description.ServiceDescription.Read(stream); //【2】 Web.Services.Description.ServiceDescriptionImporter sdi = new Web.Services.Description.ServiceDescriptionImporter(); //【3】 sdi.AddServiceDescription(sd, "", ""); CodeDom.CodeNamespace cn = new CodeDom.CodeNamespace(_namespace); //【4】 //生成客户端代理类代码 CodeDom.CodeCompileUnit ccu = new CodeDom.CodeCompileUnit(); //【5】 ccu.Namespaces.Add(cn); sdi.Import(cn, ccu); //CSharpCodeProvider csc = new CSharpCodeProvider();//【6】 CodeDom.Compiler.CodeDomProvider csc = CodeDom.Compiler.CodeDomProvider.CreateProvider("CSharp"); //ICodeCompiler icc = csc.CreateCompiler();//【7】 //设定编译器的参数 CodeDom.Compiler.CompilerParameters cplist = new CodeDom.Compiler.CompilerParameters();//【8】 cplist.GenerateExecutable = false; cplist.GenerateInMemory = true; cplist.ReferencedAssemblies.Add("System.dll"); cplist.ReferencedAssemblies.Add("System.XML.dll"); cplist.ReferencedAssemblies.Add("System.Web.Services.dll"); cplist.ReferencedAssemblies.Add("System.Data.dll"); //编译代理类 CodeDom.Compiler.CompilerResults cr = csc.CompileAssemblyFromDom(cplist, ccu);//【9】 if (true == cr.Errors.HasErrors) { System.Text.StringBuilder sb = new StringBuilder(); foreach (CodeDom.Compiler.CompilerError ce in cr.Errors) { sb.Append(ce.ToString()); sb.Append(System.Environment.NewLine); } throw new Exception(sb.ToString()); } //生成代理实例,并调用方法 System.Reflection.Assembly assembly = cr.CompiledAssembly; Type t = assembly.GetType(_namespace + "." + classname, true, true); object bj = Activator.CreateInstance(t); //【10】 System.Reflection.MethodInfo mi = t.GetMethod(methodname); //【11】 return(mi.Invoke(bj, args)); } catch (System.Exception ex) { Common.LogHelper.Instance.WriteError(ex.Message + "|" + ex.StackTrace); //MessageManager.ShowErrorMsg(ex.Message.ToString(), "test"); return(null); } }
public static JsonUtils.JsonObject GetDynamicJsonObject(this Uri uri) { using (Net.WebClient wc = new Net.WebClient()) { wc.Encoding = System.Text.Encoding.UTF8; wc.Headers["User-Agent"] = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 2.0.50727; .NET4.0C; .NET4.0E)"; return(JsonUtils.JsonObject.GetDynamicJsonObject(wc.DownloadString(uri.ToString()))); } }
protected void FillControl() { Project_Master plist = new Project_Master(); List <PI_Master> List_DEPT_PI = new List <PI_Master>(); List <Project_Coordinator_Details> List_Co_Ord = new List <Project_Coordinator_Details>(); try { ShowPanel("entry"); // plist = cl.GetProject_MasterDetailsByID(Convert.ToInt32(Common.iffBlank(HdnId.Value, 0))); ProjectMasterModel pmm = new ProjectMasterModel(); System.Net.WebClient client = new System.Net.WebClient(); client.Headers.Add("content-type", "application/json");//set your header here, you can add multiple headers string arr = client.DownloadString(string.Format("{0}api/ProjectMaster/{1}", Session["WebApiUrl"].ToString(), Convert.ToInt32(Common.iffBlank(HdnId.Value, 0)))); JavaScriptSerializer serializer = new JavaScriptSerializer(); pmm = serializer.Deserialize <ProjectMasterModel>(arr); // BindCombo(); BindCoOrdinator(); plist = pmm._Project_Master; TxtDispProjId.Text = Common.GetReplace(plist.s_Display_Project_ID); DispProjectId.InnerText = TxtDispProjId.Text; TxtstartDate.Text = plist.Project_StartDate; TxtprojTitle.Text = Common.GetReplace(plist.s_Project_Title); TxtShortTitle.Text = Common.GetReplace(plist.s_Short_Title); TxtProjTitleAlias1.Text = Common.GetReplace(plist.s_Project_Alias1); TxtProjTitleAlias2.Text = Common.GetReplace(plist.s_Project_Alias2); TxtProjDescription.Text = Common.GetReplace(plist.s_Project_Desc); TxtIRBno.Text = Common.GetReplace(plist.s_IRB_No); ddlProjCategory.SelectedIndex = ddlProjCategory.Items.IndexOf(ddlProjCategory.Items.FindByValue(Convert.ToString(Common.iffBlank(plist.i_Project_Category_ID, "")))); ddlProjType.SelectedIndex = ddlProjType.Items.IndexOf(ddlProjType.Items.FindByValue(Convert.ToString(Common.iffBlank(plist.i_Project_Type_ID, "")))); ddlProjType_SelectedIndexChanged(null, null); ddlProjSubType.SelectedIndex = ddlProjSubType.Items.IndexOf(ddlProjSubType.Items.FindByValue(Convert.ToString(Common.iffBlank(plist.i_Project_Subtype_ID, "")))); ddlProjSubType.Enabled = (ddlProjSubType.SelectedIndex > 0) ? true : false; ddlFeasibilityStatus.SelectedIndex = ddlFeasibilityStatus.Items.IndexOf(ddlFeasibilityStatus.Items.FindByValue(Convert.ToString(plist.b_IsFeasible))); HdnFeasibilityStatus.Value = Convert.ToString(plist.b_IsFeasible); ddlselectedproject.SelectedIndex = ddlselectedproject.Items.IndexOf(ddlselectedproject.Items.FindByValue(Convert.ToString(plist.b_Isselected_project == true ? "1" : "0"))); ddlCollbrationInv.SelectedIndex = ddlCollbrationInv.Items.IndexOf(ddlCollbrationInv.Items.FindByValue(Convert.ToString(plist.b_Collaboration_Involved == true ? "1" : "0"))); if (ddlProjCategory.SelectedItem.Text.ToLower() == "pharma") { ddlCollbrationInv.Enabled = false; } ddlstartbyTTSH.SelectedIndex = ddlstartbyTTSH.Items.IndexOf(ddlstartbyTTSH.Items.FindByValue(Convert.ToString(plist.b_StartBy_TTSH == true ? "1" : "0"))); ddlfundingReq.SelectedIndex = ddlfundingReq.Items.IndexOf(ddlfundingReq.Items.FindByValue(Convert.ToString(plist.b_Funding_req == true ? "1" : "0"))); ddlChildParent.SelectedIndex = ddlChildParent.Items.IndexOf(ddlChildParent.Items.FindByValue(Convert.ToString(plist.b_Ischild == true ? "0" : "1"))); if (ddlChildParent.SelectedValue == "0") { ddlParentProjName.Enabled = true; txtParentProjId.Enabled = true; ddlParentProjName.SelectedIndex = ddlParentProjName.Items.IndexOf(ddlParentProjName.Items.FindByValue(Convert.ToString(plist.i_Parent_ProjectID))); ddlParentProjName_SelectedIndexChanged(null, null); } else { ddlParentProjName.Enabled = false; txtParentProjId.Enabled = false; } //-------Newly Added 31-08-2015------------ ddlProjectStatus.SelectedIndex = ddlProjectStatus.Items.IndexOf(ddlProjectStatus.Items.FindByValue(Convert.ToString(Common.iffBlank(plist.i_ProjectStatus, "")))); TxtProjectEndDate.Text = Convert.ToString(plist.Dt_ProjectEndDate); ddlEthicsNeeded.SelectedValue = (plist.b_EthicsNeeded == true) ? "1" : "0"; //---- END--------------------------------- ScriptManager.RegisterStartupScript(Page, typeof(Page), "Enable", "BindDoObjects();", true); /*dataowner fill*/ ddlDO_Ethics.SelectedIndex = ddlDO_Ethics.Items.IndexOf(ddlDO_Ethics.Items.FindByValue(Convert.ToString(Common.iffBlank(plist.s_Ethics_DataOwner, "")))); ddlDO_Feasibility.SelectedIndex = ddlDO_Feasibility.Items.IndexOf(ddlDO_Feasibility.Items.FindByValue(Convert.ToString(Common.iffBlank(plist.s_Feasibility_DataOwner, "")))); ddlDO_Contract.SelectedIndex = ddlDO_Contract.Items.IndexOf(ddlDO_Contract.Items.FindByValue(Convert.ToString(Common.iffBlank(plist.s_Contract_DataOwner, "")))); ddlDO_Selected.SelectedIndex = ddlDO_Selected.Items.IndexOf(ddlDO_Ethics.Items.FindByValue(Convert.ToString(Common.iffBlank(plist.s_Selected_DataOwner, "")))); ddlDO_Regulatory.SelectedIndex = ddlDO_Regulatory.Items.IndexOf(ddlDO_Regulatory.Items.FindByValue(Convert.ToString(Common.iffBlank(plist.s_Regulatory_DataOwner, "")))); ddlDO_Grant.SelectedIndex = ddlDO_Grant.Items.IndexOf(ddlDO_Grant.Items.FindByValue(Convert.ToString(Common.iffBlank(plist.s_Grant_DataOwner, "")))); //Page.ClientScript.RegisterStartupScript(this.GetType(), "enable", "alert('Hello!')", true); //ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "enable", "BindDoObjects();", true); /**/ List_DEPT_PI = pmm.DEPT_PI.ToList(); //plist.DEPT_PI.ToList(); var q = (from i in List_DEPT_PI select new { i.i_Dept_ID, i.i_ID }).ToList().ListToDatatable(); rptrPIDetails.DataSource = List_DEPT_PI; rptrPIDetails.DataBind(); txtResearchOrder.Text = Common.GetReplace(plist.s_Research_IO); txtReserchInsurance.Text = Common.GetReplace(plist.s_Research_IP); List_Co_Ord = pmm.pcd.ToList(); //plist.COORDINATOR.ToList(); for (int j = 0; j < chkboxlist.Items.Count; j++) { for (int i = 0; i < List_Co_Ord.Count; i++) { if (chkboxlist.Items[j].Value == Convert.ToString(List_Co_Ord[i].i_Coordinator_ID)) { chkboxlist.Items[j].Selected = true; TextSearch.Text += chkboxlist.Items[j].Text + ","; } } } if (TextSearch.Text != "") { TextSearch.Text = TextSearch.Text.TrimEnd(','); } // TxtDispProjId.Attributes.Add("onblur", "javascript:return GetValidatefrmDB('" + HdnError.ClientID + "','ValidateDispID' ,'" + TxtDispProjId.ClientID + "','" + HdnId.Value + "');"); ScriptManager.RegisterStartupScript(Page, Page.GetType(), "msg", "ClearAll('" + HdnMode.Value + "');", true); if (HdnMode.Value.ToLower() == "update") { // String s = cl.GetValidate("RestrictChild", HdnId.Value, "", "", ""); //if (s != "") //{ // ddlChildParent.Enabled = false; // ddlChildParent.Attributes.Add("title", "Child Project is Created for this Project..!!"); //} } ChangeButtonText(); MakeControlValidate(); } catch (Exception ex) { throw ex; } }
public XmlManager(Uri Url) { System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding(); System.Net.WebClient web = new System.Net.WebClient(); Stream rs = null; StreamReader sr = null; try { try { rs = web.OpenRead(Url.AbsoluteUri); } catch (Exception webex) { _XmlError = true; _XmlErrorDetail = string.Concat(webex.ToString(), " ", webex.Message); return; } try { web.Dispose(); web = null; sr = new StreamReader(rs); string Xml = sr.ReadToEnd(); Load(Xml, XML_TYPE.RawXml); } catch (Exception ex) { _XmlError = true; _XmlErrorDetail = string.Concat(ex.ToString(), " ", ex.Message); } } finally { if ((sr != null)) { sr.Close(); } if ((rs != null)) { rs.Close(); } //Another method. Had really odd, random characters in the beginning making the xml invalid. //Dim enc As New System.Text.ASCIIEncoding //Dim web As New System.Net.WebClient //Dim res As Byte() //Try // res = web.DownloadData(Url.AbsoluteUri) //Catch webex As System.Net.WebException //End Try //Try // web.Dispose() // web = Nothing // Dim Xml As String = enc.GetString(res) // Load(Xml, XML_TYPE.RawXml) //Catch ex As Exception // _XmlError = True // _XmlErrorDetail = String.Concat(ex.ToString, " ", ex.Message) //End Try } }
void OnGUI() { if (!connected) { width = Screen.width / 2; height = Screen.height / 2; if (map == 0 && isenabled) { ip = GUI.TextField(new Rect(width - 100, height - 48, 180, 24), ip); tport = GUI.TextField(new Rect(width + 96, height - 48, 48, 24), tport, 5); if (GUI.Button(new Rect(width - 100, height - 24, 160, 24), "Csatlakozás")) { int.TryParse(tport, out port); Network.Connect(ip, port); StreamWriter sw = new StreamWriter(file_addr, false); sw.WriteLine(ip); sw.Write(port); sw.Close(); } if (masterurl != null) { if (GUI.Button(new Rect(width + 64, height - 24, 160, 24), "Keresés")) { showlist = true; if (showlist) { try { System.Net.WebClient client = new System.Net.WebClient(); Stream webstream = client.OpenRead(masterurl + "/list.txt"); client.Dispose(); StreamReader sr = new StreamReader(webstream, System.Text.Encoding.Default); servlist = sr.ReadToEnd().Split('\n'); if (servlist[servlist.Length - 1].Length < 1) { System.Array.Resize(ref servlist, servlist.Length - 1); } addrlist = new string[servlist.Length]; for (f = 0; f < servlist.Length; f++) { addrlist[f] = servlist[f].Substring(0, servlist[f].IndexOf(';')); servlist[f] = servlist[f].Substring(servlist[f].IndexOf(';') + 1); } sr.Close(); webstream.Close(); } catch { WriteErrorLog("Sikertelen lekérdezés"); showlist = false; } } } } if (showlist) { for (f = 0; f < 4; f++) { if (servlist.Length == f) { break; } if (GUI.Button(new Rect(width - 100, height + 32 + (f * 32), 384, 24), servlist[f + sel_offset])) { tmpstr = addrlist[f + sel_offset]; ip = tmpstr.Substring(0, tmpstr.IndexOf(':')); tport = tmpstr.Substring(tmpstr.IndexOf(':') + 1); } } if (servlist.Length > 4) { if (GUI.Button(new Rect(width - 100, height, 64, 24), "Fel")) { if (sel_offset > 0) { sel_offset -= 1; } } if (GUI.Button(new Rect(width - 100, height + 160, 64, 24), "Le")) { if (sel_offset < servlist.Length - 4) { sel_offset += 1; } } } } if (Event.current.Equals(Event.KeyboardEvent("escape"))) { GameObject.Find("menu").SetActiveRecursively(true); GameObject.Find("ConnectMenu").SetActiveRecursively(false); isenabled = false; } } else if (map != 0) { if (ischange) { if (GameObject.Find("ChangeServ")) { Network.InitializeServer(maxplayers - 1, port, false); Destroy(GameObject.Find("ChangeServ")); ischange = false; } else if (GameObject.Find("ChangeClient")) { if (!isloaded) { StreamReader sr = new StreamReader(file_addr); ip = sr.ReadLine(); if (sr.Peek() > -1) { tport = sr.ReadLine(); } sr.Close(); isloaded = true; } int.TryParse(tport, out port); Network.Connect(ip, port); Destroy(GameObject.Find("ChangeClient")); ischange = false; } } else { if (GUI.Button(new Rect(width - 100, height - 16, 200, 24), "Szerver indítása")) { Network.InitializeServer(maxplayers - 1, port, false); } if (GUI.Button(new Rect(width - 100, height + 16, 200, 24), "Vissza a menübe")) { Network.Disconnect(); Application.LoadLevel(0); connected = false; } } } } }
// get Prospector availability from first isbn //private bool getRegionalAvailability(string id) private bool getRegionalAvailability(string isbn) { const string regionalHome = "http://prospector.coalliance.org/"; const string regionalSearch = regionalHome + "search~S0?/"; string backlink = "&backlink=" + Session["ReferringURL"].ToString(); string i = "i" + isbn; Session["ProspectorItem"] = regionalSearch + i + "/" + i + "/1,1,1,B/detlframeset&FF=" + i + "&1,1," + backlink; Session["ProspectorRequest"] = regionalSearch + i + "/" + i + "/1,1,1,B/request&FF=" + i + "&1,1," + backlink; Session["ProspectorItems"] = regionalHome + "search/?searchtype=i&searcharg=" + isbn + backlink; /* * var b = "z9csup+b" + id; * Session["ProspectorURL"] = regionalSearch + b + "/" + b + "/1,1,1,B/detlframeset&FF=" + b + "&1,1," + backlink; * Session["ProspectorRequest"] = regionalSearch + b + "/" + b + "/1,1,1,B/request&FF=" + b + "&1,1," + backlink; */ // make sure the ISBN is actually found // otherwise regionalHtml returns a false positive with a different ISBN! - gvogl 2013-06-26 string regionalItems; try { using (var wc = new System.Net.WebClient()) regionalItems = wc.DownloadString(Session["ProspectorItems"].ToString()); } catch { return(false); } if (regionalItems.Contains("No matches found")) { return(false); } string regionalHtml; try { using (var wc = new System.Net.WebClient()) regionalHtml = wc.DownloadString(Session["ProspectorItem"].ToString()); } catch { return(false); } // ignore rows with links containing notes about additional volumes, table of contents, etc. regionalHtml = Regex.Replace(regionalHtml, @"<tr><td>[^<]+</td><td[^>]+><a href=""[^""]+"">CLICK HERE</a><font color=""red""> to view additional volumes at</font>[^<]+</td></tr>", ""); regionalHtml = Regex.Replace(regionalHtml, @"<tr><td><a name=""[a-z0-9]+""></a>[^<]+</td>\s*<td> </td>\s*<td[^>]+><a[^>]+>[^>]+</a>\s*<td></td>\s*<td></td>\s*</tr>", ""); // count non-CSU copies and available copies int copies = 0; int available = 0; Match match = Regex.Match(regionalHtml, @"(<tr class=""holdings[a-z0-9]+""><td><a name=""([a-z0-9]+)""><\/a>[^>]+<\/td>(\s*<td>[^>]+<\/td>\s*)+<\/tr>\s*)+", RegexOptions.None); if (match.Success) { for (var j = 0; j < match.Groups[2].Captures.Count; j++) { if (!match.Groups[2].Captures[j].Value.Contains("9csup")) { copies++; if (match.Groups[3].Captures[4 * (j + 1) - 1].Value.Contains("AVAILABLE")) { available++; } } } } Session["ProspectorCopies"] = copies; Session["ProspectorAvailable"] = available; return(true); }
protected void loadExpiredRepeatersReport() { System.Web.UI.ControlCollection pnl = pnlExpiredRepeaters.Controls; string json = ""; if (ViewState["expiredRepeaters"] == null) { using (var webClient = new System.Net.WebClient()) { string url = String.Format(System.Configuration.ConfigurationManager.AppSettings["webServiceRootUrl"] + "ReportNonstandardRepeaters?callsign={0}&password={1}", creds.Username, creds.Password); json = webClient.DownloadString(url); ViewState["expiredRepeaters"] = json; } } else { json = ViewState["expiredRepeaters"].ToString(); } dynamic data = JsonConvert.DeserializeObject <dynamic>(json); lblTitle.Text = data.Report.Title; lblTitle2.Text = data.Report.Title; Table table = new Table(); if (data.Report != null) { foreach (dynamic item in data.Report.Data) { dynamic repeater = item.Repeater; using (TableRow headerRow = new TableRow()) { headerRow.AddCell("ID"); headerRow.AddCell("Callsign"); headerRow.AddCell("Xmit freq"); headerRow.AddCell("Rcv freq"); headerRow.AddCell("City"); headerRow.AddCell("Sponsor"); headerRow.AddCell("Trustee"); headerRow.AddCell("Contact info"); headerRow.CssClass = "expiredRepeaterHeader"; table.Rows.Add(headerRow); } using (TableRow row = new TableRow()) { row.AddCell(string.Format("<a target='_blank' href='/update/?id={0}'>{0}</a>", (string)repeater.ID)); row.AddCell(string.Format("<a target='_blank' href='https://qrz.com/db/{0}'>{0}</a>", (string)repeater.Callsign)); row.AddCell((string)repeater.Output); row.AddCell((string)repeater.Input); row.AddCell((string)repeater.City); row.AddCell((string)repeater.Sponsor); row.AddCell(string.Format("<a target='_blank' href='https://qrz.com/db/{0}'>{1}</a>", (string)repeater.Trustee.Callsign, (string)repeater.Trustee.Name)); string strContact = string.Empty; if ((string)repeater.Trustee.Email != string.Empty) { if (strContact != string.Empty) { strContact += ", "; } strContact += "<a href='mailto:" + (string)repeater.Trustee.Email + "'>" + (string)repeater.Trustee.Email + "</a> "; } string strPhone = string.Empty; if ((string)repeater.Trustee.CellPhone != string.Empty) { if (strContact != string.Empty) { strContact += ", "; } strPhone = (string)repeater.Trustee.CellPhone; strContact += "<a href='tel:" + strPhone + "'>" + strPhone + "</a> (cell)"; } if ((string)repeater.Trustee.HomePhone != string.Empty) { if (strContact != string.Empty) { strContact += ", "; } strPhone = (string)repeater.Trustee.HomePhone; strContact += "<a href='tel:" + strPhone + "'>" + strPhone + "</a> (home)"; } if ((string)repeater.Trustee.WorkPhone != string.Empty) { if (strContact != string.Empty) { strContact += ", "; } strPhone = (string)repeater.Trustee.WorkPhone; strContact += "<a href='tel:" + strPhone + "'>" + strPhone + "</a> (work)"; } row.AddCell(strContact); row.CssClass = "expiredRepeaterData"; table.Rows.Add(row); } using (TableRow row = new TableRow()) { string strNotes = ""; if (repeater.Notes != null) { strNotes = "<ul>"; foreach (dynamic obj in repeater.Notes) { string note = ((string)obj.Note.Text).Replace("•", "<br>•"); strNotes += string.Format("<li>{0} - {1} ({2}, {3})</li>", obj.Note.Timestamp, note, obj.Note.User.Name, obj.Note.User.Callsign); } strNotes += "</ul>"; } else { strNotes = "<ul><li><em>There are no notes on record for this repeater.</em></li></ul>"; } row.AddCell(strNotes, 8); row.CssClass = "expiredRepeaterNotes"; table.Rows.Add(row); } using (TableRow row = new TableRow()) { Label label = new Label(); label.Text = "Note: "; TextBox textbox = new TextBox(); textbox.ID = "txt" + repeater.ID; textbox.CssClass = "expiredRepeaterNote"; Button button = new Button(); button.CommandArgument = repeater.ID; button.CommandName = "saveNote"; button.Click += Button_Click; button.Text = "Save"; TableCell cell = new TableCell(); cell.Controls.Add(label); cell.Controls.Add(textbox); cell.Controls.Add(button); cell.ColumnSpan = 8; row.Cells.Add(cell); row.CssClass = "expiredRepeaterNewNote"; table.Rows.Add(row); } } } pnlExpiredRepeaters.Controls.Add(table); }
private void LoadRepeaterUsers(string repeaterId) { using (var webClient = new System.Net.WebClient()) { string rootUrl = System.Configuration.ConfigurationManager.AppSettings["webServiceRootUrl"].ToString(); string url = String.Format("{0}ListRepeaterUsers?callsign={1}&password={2}&repeaterid={3}", rootUrl, creds.Username, creds.Password, repeaterId); string json = webClient.DownloadString(url); dynamic data = JsonConvert.DeserializeObject <dynamic>(json); tblRepeaterUsers.Rows.Clear(); using (TableHeaderRow thr = new TableHeaderRow()) { using (TableHeaderCell thc = new TableHeaderCell()) { Button btnAddRepeaterUser = new Button(); btnAddRepeaterUser.ID = "btnAddRepeaterUser"; btnAddRepeaterUser.Click += btnAddRepeaterUser_Click; btnAddRepeaterUser.Text = "Add new"; thc.Controls.Add(btnAddRepeaterUser); thr.Cells.Add(thc); } using (TableHeaderCell thc = new TableHeaderCell()) { thc.Text = "Callsign"; thr.Cells.Add(thc); } using (TableHeaderCell thc = new TableHeaderCell()) { thc.Text = "Name"; thr.Cells.Add(thc); } using (TableHeaderCell thc = new TableHeaderCell()) { thc.Text = "Email"; thr.Cells.Add(thc); } tblRepeaterUsers.Rows.Add(thr); } // ID, Callsign, FullName, Email foreach (dynamic obj in data) { TableRow row = new TableRow(); TableCell cell = new TableCell(); if (repeater.Status != "6") { Button btn = new Button(); btn.Text = "Remove"; string userid = obj["ID"].ToString(); btn.Click += (sender, e) => btnRemoveRepeaterUser(sender, e, userid); cell.Controls.Add(btn); } row.Cells.Add(cell); cell = new TableCell(); cell.Text = obj["Callsign"].ToString(); row.Cells.Add(cell); cell = new TableCell(); cell.Text = obj["FullName"].ToString(); row.Cells.Add(cell); cell = new TableCell(); cell.Text = String.Format("<a href='mailto:{0}'>{0}</a>", obj["Email"].ToString()); row.Cells.Add(cell); tblRepeaterUsers.Rows.Add(row); } } }
private void LoadRepeaterLinks(string repeaterId) { using (var webClient = new System.Net.WebClient()) { string rootUrl = System.Configuration.ConfigurationManager.AppSettings["webServiceRootUrl"].ToString(); string url = String.Format("{0}ListRepeaterLinks?repeaterid={1}", rootUrl, repeaterId); string json = webClient.DownloadString(url); dynamic data = JsonConvert.DeserializeObject <dynamic>(json); tblLinks.Rows.Clear(); using (TableHeaderRow thr = new TableHeaderRow()) { using (TableHeaderCell thc = new TableHeaderCell()) { thc.Text = "Direct link?"; thr.Cells.Add(thc); } using (TableHeaderCell thc = new TableHeaderCell()) { thc.Text = "Frequency"; thr.Cells.Add(thc); } using (TableHeaderCell thc = new TableHeaderCell()) { thc.Text = "Callsign"; thr.Cells.Add(thc); } using (TableHeaderCell thc = new TableHeaderCell()) { thc.Text = "City"; thr.Cells.Add(thc); } tblLinks.Rows.Add(thr); } foreach (dynamic obj in data) { TableRow row = new TableRow(); TableCell cell = new TableCell(); if (obj["DirectlyLinked"] == true) { cell = new TableCell(); cell.Text = "Yes"; row.Cells.Add(cell); } else { cell = new TableCell(); cell.Text = "No"; row.Cells.Add(cell); } cell = new TableCell(); cell.Text = string.Format("<a href=\"/repeaters/details/?id={0}\">{1}</a>", obj["ID"], stringify(obj["OutputFrequency"])); row.Cells.Add(cell); cell = new TableCell(); cell.Text = string.Format("<a href=\"/repeaters/details/?id={0}\">{1}</a>", obj["ID"], stringify(obj["Callsign"])); row.Cells.Add(cell); cell = new TableCell(); cell.Text = string.Format("<a href=\"/repeaters/details/?id={0}\">{1}</a>", obj["ID"], stringify(obj["City"])); row.Cells.Add(cell); tblLinks.Rows.Add(row); } } }
public static void NullifyProxy(this System.Net.WebClient web) { web.Proxy = null; }
private void LoadRequestDetails(Credentials creds, string requestid) { using (var webClient = new System.Net.WebClient()) { string rootUrl = System.Configuration.ConfigurationManager.AppSettings["webServiceRootUrl"].ToString(); string url = String.Format("{0}GetCoordinationRequestDetails?callsign={1}&password={2}&requestid={3}", rootUrl, creds.Username, creds.Password, requestid); string strJson = webClient.DownloadString(url); dynamic json = JsonConvert.DeserializeObject <dynamic>(strJson); lblAltitude.Text = json.Request.Altitude; lblAntennaHeight.Text = json.Request.AntennaHeight; lblID.Text = String.Format("Coordination Request #{0}{1}", json.Request.State, json.Request.ID); lblLatitude.Text = json.Request.Latitude; lblLongitude.Text = json.Request.Longitude; lblOutputFrequency.Text = json.Request.OutputFrequency; lblPower.Text = json.Request.OutputPower; lblRequestor.Text = String.Format("{0}, {1}", json.Request.Requestor.Name, json.Request.Requestor.Callsign); lblStatus.Text = json.Request.Status.Description; if (json.Request.Notes != null) { foreach (dynamic note in json.Request.Notes) { using (TableRow row = new TableRow()) { using (TableCell cell = new TableCell()) { cell.Text = String.Format("{0}, {1}", note.Note.User.Name, note.Note.User.Callsign); cell.HorizontalAlign = HorizontalAlign.Left; row.Cells.Add(cell); } using (TableCell cell = new TableCell()) { cell.Text = String.Format("{0}", note.Note.Timestamp); cell.HorizontalAlign = HorizontalAlign.Right; row.Cells.Add(cell); } tblNotes.Rows.Add(row); } using (TableRow row = new TableRow()) { TableCell cell = new TableCell(); cell.Text = note.Note.Text; cell.ColumnSpan = 2; row.Cells.Add(cell); tblNotes.Rows.Add(row); } } } if (json.Request.Workflow != null) { foreach (dynamic step in json.Request.Workflow) { using (TableRow row = new TableRow()) { using (TableCell cell = new TableCell()) { cell.Text = step.Step.State; row.Cells.Add(cell); } using (TableCell cell = new TableCell()) { cell.Text = step.Step.Status.Description; row.Cells.Add(cell); } using (TableCell cell = new TableCell()) { cell.Text = String.Format("{0}<div class='noteDate'>{1}</div>", step.Step.Note, step.Step.TimeStamp); row.Cells.Add(cell); } tblWorkflow.Rows.Add(row); } } } } }
//开始更新 private void StartUpdater() { //string fileName = System.Configuration.ConfigurationSettings.AppSettings["ZipFileName"]; System.Net.WebClient wc = new System.Net.WebClient(); try { if (System.IO.File.Exists(fileName)) { System.IO.File.Delete(fileName); } //进度条累加 for (int i = 1; i < 1300000; i++) { pgbDownload.Value = Convert.ToInt32(i / 30000); } pgbDownload.Refresh(); Tools.FileLog.FileLogOut(start_load_file_from_server); this.Text = downloading_file; wc.DownloadFile(updaterUri + "/" + fileName + "?tmp=" + (new System.Random()).Next(1000000).ToString(), fileName); this.Text = on_update; System.Threading.Thread.Sleep(2000); //Log Tools.FileLog.FileLogOut(process_ok); Tools.FileLog.FileLogOut(start_unzip_file_from_server); UnZipFile(fileName); Tools.FileLog.FileLogOut(process_ok); //进度条累加 for (int i = 600000; i < 10000000; i++) { if (pgbDownload.Value == 100) { break; } pgbDownload.Value = Convert.ToInt32(i / 30000); } if (pgbDownload.Value != 100) { pgbDownload.Value = 100; } pgbDownload.Refresh(); } catch (Exception ex) { Tools.FileLog.FileLogOut(process_failure + "\t" + ex.Message); } finally { Tools.FileLog.FileLogOut(finish_update); wc.Dispose(); } }
public MicrosoftOpenXR(ReadOnlyTargetRules Target) : base(Target) { PCHUsage = ModuleRules.PCHUsageMode.UseExplicitOrSharedPCHs; PrivatePCHHeaderFile = @"Private\OpenXRCommon.h"; PrivateIncludePaths.AddRange( new string[] { // This private include path ensures our newer copy of the openxr headers take precedence over the engine's copy. "MicrosoftOpenXR/Private/External" } ); PrivateDependencyModuleNames.AddRange( new string[] { "Core", "CoreUObject", "ApplicationCore", "Engine", "Slate", "SlateCore", "InputCore", "OpenXRHMD", "MicrosoftOpenXRRuntimeSettings", "HeadMountedDisplay", "AugmentedReality", "OpenXRAR", "RHI", "RenderCore", "Projects", } ); if (Target.bBuildEditor) { PrivateDependencyModuleNames.AddRange( new string[] { "UnrealEd" } ); } PrivateIncludePathModuleNames.AddRange( new string[] { "HeadMountedDisplay" } ); PublicIncludePathModuleNames.AddRange( new string[] { "HeadMountedDisplay" } ); // WinRT with Nuget support if (Target.Platform == UnrealTargetPlatform.Win64 || Target.Platform == UnrealTargetPlatform.HoloLens) { // these parameters mandatory for winrt support bEnableExceptions = true; bUseUnity = false; CppStandard = CppStandardVersion.Cpp17; PublicSystemLibraries.AddRange(new string [] { "shlwapi.lib", "runtimeobject.lib" }); // prepare everything for nuget string MyModuleName = GetType().Name; string NugetFolder = Path.Combine(PluginDirectory, "Intermediate", "Nuget", MyModuleName); Directory.CreateDirectory(NugetFolder); string BinariesSubFolder = Path.Combine("Binaries", "ThirdParty", Target.Type.ToString(), Target.Platform.ToString(), Target.Architecture); PrivateDefinitions.Add(string.Format("THIRDPARTY_BINARY_SUBFOLDER=\"{0}\"", BinariesSubFolder.Replace(@"\", @"\\"))); string BinariesFolder = Path.Combine(PluginDirectory, BinariesSubFolder); Directory.CreateDirectory(BinariesFolder); // download nuget string NugetExe = Path.Combine(NugetFolder, "nuget.exe"); if (!File.Exists(NugetExe)) { using (System.Net.WebClient myWebClient = new System.Net.WebClient()) { // we aren't focusing on a specific nuget version, we can use any of them but the latest one is preferable myWebClient.DownloadFile(@"https://dist.nuget.org/win-x86-commandline/latest/nuget.exe", NugetExe); } } // run nuget to update the packages { var StartInfo = new System.Diagnostics.ProcessStartInfo(NugetExe, string.Format("install \"{0}\" -OutputDirectory \"{1}\"", Path.Combine(ModuleDirectory, "packages.config"), NugetFolder)); StartInfo.UseShellExecute = false; StartInfo.CreateNoWindow = true; var ExitCode = Utils.RunLocalProcessAndPrintfOutput(StartInfo); if (ExitCode < 0) { throw new BuildException("Failed to get nuget packages. See log for details."); } } // get list of the installed packages, that's needed because the code should get particular versions of the installed packages string[] InstalledPackages = Utils.RunLocalProcessAndReturnStdOut(NugetExe, string.Format("list -Source \"{0}\"", NugetFolder)).Split(new char[] { '\r', '\n' }); // get WinRT package string CppWinRTPackage = InstalledPackages.FirstOrDefault(x => x.StartsWith("Microsoft.Windows.CppWinRT")); if (!string.IsNullOrEmpty(CppWinRTPackage)) { string CppWinRTName = CppWinRTPackage.Replace(" ", "."); string CppWinRTExe = Path.Combine(NugetFolder, CppWinRTName, "bin", "cppwinrt.exe"); string CppWinRTFolder = Path.Combine(PluginDirectory, "Intermediate", CppWinRTName, MyModuleName); Directory.CreateDirectory(CppWinRTFolder); // search all downloaded packages for winmd files string[] WinMDFiles = Directory.GetFiles(NugetFolder, "*.winmd", SearchOption.AllDirectories); // all downloaded winmd file with WinSDK to be processed by cppwinrt.exe var WinMDFilesStringbuilder = new System.Text.StringBuilder(); foreach (var winmd in WinMDFiles) { WinMDFilesStringbuilder.Append(" -input \""); WinMDFilesStringbuilder.Append(winmd); WinMDFilesStringbuilder.Append("\""); } // generate winrt headers and add them into include paths var StartInfo = new System.Diagnostics.ProcessStartInfo(CppWinRTExe, string.Format("{0} -input \"{1}\" -output \"{2}\"", WinMDFilesStringbuilder, Target.WindowsPlatform.WindowsSdkVersion, CppWinRTFolder)); StartInfo.UseShellExecute = false; StartInfo.CreateNoWindow = true; var ExitCode = Utils.RunLocalProcessAndPrintfOutput(StartInfo); if (ExitCode < 0) { throw new BuildException("Failed to get generate WinRT headers. See log for details."); } PrivateIncludePaths.Add(CppWinRTFolder); } else { // fall back to default WinSDK headers if no winrt package in our list PrivateIncludePaths.Add(Path.Combine(Target.WindowsPlatform.WindowsSdkDir, "Include", Target.WindowsPlatform.WindowsSdkVersion, "cppwinrt")); } // WinRT lib for some job string QRPackage = InstalledPackages.FirstOrDefault(x => x.StartsWith("Microsoft.MixedReality.QR")); if (!string.IsNullOrEmpty(QRPackage)) { string QRFolderName = QRPackage.Replace(" ", "."); // copying dll and winmd binaries to our local binaries folder // !!!!! please make sure that you use the path of file! Unreal can't do it for you !!!!! SafeCopy(Path.Combine(NugetFolder, QRFolderName, @"lib\uap10.0.18362\Microsoft.MixedReality.QR.winmd"), Path.Combine(BinariesFolder, "Microsoft.MixedReality.QR.winmd")); SafeCopy(Path.Combine(NugetFolder, QRFolderName, string.Format(@"runtimes\win10-{0}\native\Microsoft.MixedReality.QR.dll", Target.WindowsPlatform.Architecture.ToString())), Path.Combine(BinariesFolder, "Microsoft.MixedReality.QR.dll")); // also both both binaries must be in RuntimeDependencies, unless you get failures in Hololens platform RuntimeDependencies.Add(Path.Combine(BinariesFolder, "Microsoft.MixedReality.QR.dll")); RuntimeDependencies.Add(Path.Combine(BinariesFolder, "Microsoft.MixedReality.QR.winmd")); } if (Target.Platform == UnrealTargetPlatform.Win64) { // Microsoft.VCRTForwarders.140 is needed to run WinRT dlls in Win64 platforms string VCRTForwardersPackage = InstalledPackages.FirstOrDefault(x => x.StartsWith("Microsoft.VCRTForwarders.140")); if (!string.IsNullOrEmpty(VCRTForwardersPackage)) { string VCRTForwardersName = VCRTForwardersPackage.Replace(" ", "."); foreach (var Dll in Directory.EnumerateFiles(Path.Combine(NugetFolder, VCRTForwardersName, "runtimes/win10-x64/native/release"), "*_app.dll")) { string newDll = Path.Combine(BinariesFolder, Path.GetFileName(Dll)); SafeCopy(Dll, newDll); RuntimeDependencies.Add(newDll); } } string RemotingPackage = InstalledPackages.FirstOrDefault(x => x.StartsWith("Microsoft.Holographic.Remoting.OpenXr")); if (!string.IsNullOrEmpty(RemotingPackage)) { string RemotingFolderName = RemotingPackage.Replace(" ", "."); SafeCopy(Path.Combine(NugetFolder, RemotingFolderName, @"build\native\bin\x64\Desktop\Microsoft.Holographic.AppRemoting.OpenXr.dll"), Path.Combine(BinariesFolder, "Microsoft.Holographic.AppRemoting.OpenXr.dll")); SafeCopy(Path.Combine(NugetFolder, RemotingFolderName, @"build\native\bin\x64\Desktop\RemotingXR.json"), Path.Combine(BinariesFolder, "RemotingXR.json")); PrivateIncludePaths.Add(Path.Combine(NugetFolder, RemotingFolderName, @"build\native\include\openxr")); RuntimeDependencies.Add(Path.Combine(BinariesFolder, "Microsoft.Holographic.AppRemoting.OpenXr.dll")); RuntimeDependencies.Add(Path.Combine(BinariesFolder, "RemotingXR.json")); } } } }
protected void login1_Authenticate(object sender, AuthenticateEventArgs e) { using (var webClient = new System.Net.WebClient()) { string username = login1.UserName.Trim(); string password = login1.Password.Trim(); string parameters = string.Format("callsign={0}&password={1}", username, password); string strUrl = string.Format("{0}{1}{2}", System.Configuration.ConfigurationManager.AppSettings["webServiceRootUrl"], "DoLogin?", parameters); string json = webClient.DownloadString(strUrl); dynamic data = JsonConvert.DeserializeObject <dynamic>(json); if ((int)data[0].Return == 1) { e.Authenticated = true; HttpCookie ckLogin = new HttpCookie("login", Utilities.Base64Encode(username + "|" + password)); if (login1.RememberMeSet) { ckLogin.Expires = DateTime.Now.AddDays(364); } Response.Cookies.Add(ckLogin); if ((int)data[0].isReportViewer == 1) { HttpCookie peanutbutter = new HttpCookie("peanutbutter", "1"); Response.Cookies.Add(peanutbutter); } if ((int)data[0].isAdmin == 1) { HttpCookie chocolatechip = new HttpCookie("chocolatechip", "1"); Response.Cookies.Add(chocolatechip); } if ((int)data[0].isCoordinator == 1) { isCoordinator = true; HttpCookie oatmeal = new HttpCookie("oatmeal", "1"); Response.Cookies.Add(oatmeal); } } else { e.Authenticated = false; } if (e.Authenticated) { HttpCookie hc = HttpContext.Current.Request.Cookies["redirectAfterLogin"]; if ((hc != null) && (hc.Value != string.Empty)) { string url = hc.Value; HttpCookie cookie = HttpContext.Current.Request.Cookies["redirectAfterLogin"]; cookie.Expires = DateTime.Now.AddDays(-1); cookie.Value = null; HttpContext.Current.Response.SetCookie(cookie); Response.Redirect(url); } else { if ((int)data[0].profileIncomplete == 1) { Response.Redirect("/profile/?ip=1"); } else { if (isCoordinator) { Response.Redirect("/request-interstate/"); } else { Response.Redirect("/Dashboard/"); } } } } } }
/// <summary> /// 微信登录 /// </summary> private void WeChatLoad() { // https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx18dba54a978196fb&redirect_uri=http://ptweb.x76.com.cn/Danace/&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect string accessToken = string.Empty; string DeBugMsg = string.Empty; string AppId = "wx18dba54a978196fb";//与微信公众账号后台的AppId设置保持一致,区分大小写。 string AppSecret = "9b624176c34f4d0c00d045727731b096"; var code = string.Empty; var opentid = string.Empty; try { code = Request.QueryString["code"]; DeBugMsg += "code:" + code; } catch { } if (string.IsNullOrEmpty(code)) { } else { string strWeixin_OpenID = string.Empty; string STRUSERID = string.Empty; if (strWeixin_OpenID == string.Empty || STRUSERID == string.Empty) { DeBugMsg += "<br> 没有所需的OPENID!"; // this.Label1.Text = "没有所需的OPENID"; var client = new System.Net.WebClient(); client.Encoding = System.Text.Encoding.UTF8; var url = string.Format("https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code", AppId, AppSecret, code); var data = client.DownloadString(url); var serializer = new JavaScriptSerializer(); var obj = serializer.Deserialize <Dictionary <string, string> >(data); if (!obj.TryGetValue("access_token", out accessToken)) { DeBugMsg += "<br> Token获取错误!"; } else { opentid = obj["openid"]; //MessageBox("", "opentid:" + opentid); } // string tempToken = GetaccessWebToken(code); url = string.Format("https://api.weixin.qq.com/sns/userinfo?access_token={0}&openid={1}&lang=zh_CN", accessToken, opentid); data = client.DownloadString(url); var userInfo = serializer.Deserialize <Dictionary <string, object> >(data); DeBugMsg += "userInfo:" + data.ToString(); int vsex = 2; var vcity = "中国"; if (userInfo["sex"].ToString() == "1") { vsex = 0; } vcity = userInfo["country"].ToString() + userInfo["province"].ToString() + userInfo["city"].ToString(); DeBugMsg += "城市:" + vcity; if (opentid.Length == 0) { opentid = "test111"; } string UserName = "******"; string HeadUserUrl = ""; UserName = userInfo["nickname"].ToString(); DeBugMsg += "昵称:" + UserName; HeadUserUrl = userInfo["headimgurl"].ToString(); DeBugMsg += "头像:" + HeadUserUrl; string strSQL; strSQL = " Select * from Dance_User where WeChatOpenID='" + opentid.ToString() + "'"; if (OP_Mode.SQLRUN(strSQL)) { if (OP_Mode.Dtv.Count > 0) { /// 如果数据库有ID,则直接登录。 Response.Cookies[Constant.COOKIENAMEUSER][Constant.COOKIENAMEUSER_USERID] = OP_Mode.Dtv[0]["ID"].ToString().Trim(); Response.Cookies["Dance"]["USERID"] = OP_Mode.Dtv[0]["ID"].ToString().Trim(); Response.Cookies["Dance"]["COPENID"] = opentid.ToString(); Response.Cookies["Dance"]["CNAME"] = HttpUtility.UrlEncode(UserName); Response.Cookies["Dance"]["LTIME"] = OP_Mode.Dtv[0]["LTIME"].ToString().Trim(); Response.Cookies["Dance"]["HEADURL"] = HeadUserUrl; Response.Cookies["Dance"]["LOGIN"] = "******"; Response.Cookies[Constant.COOKIENAMEUSER][Constant.COOKIENAMEUSER_CNAME] = UserName; Response.Cookies[Constant.COOKIENAMEUSER][Constant.COOKIENAMEUSER_CTX] = HeadUserUrl; ///设置COOKIE最长时间 //Response.Cookies["Dance"].Expires = DateTime.MaxValue; /// 更新登录时间 OP_Mode.SQLRUN("Update Dance_User set Ltime=getdate(),HeadImage='" + HeadUserUrl + "',Nick=" + UserName + " where WeChatOpenID='" + opentid.ToString() + "'"); return; } else { try { strSQL = " INSERT INTO Dance_User (WeChatOpenID,Nick,HeadImage) VALUES ('" + opentid + "','" + UserName + "','" + HeadUserUrl + "')"; strSQL += " Select * from Dance_User where WeChatOpenID='" + opentid + "'"; DeBugMsg += "+" + strSQL + "+"; if (OP_Mode.SQLRUN(strSQL)) { if (OP_Mode.Dtv.Count > 0) { Response.Cookies[Constant.COOKIENAMEUSER][Constant.COOKIENAMEUSER_USERID] = OP_Mode.Dtv[0]["ID"].ToString().Trim(); Response.Cookies["Dance"]["USERID"] = OP_Mode.Dtv[0]["ID"].ToString().Trim(); Response.Cookies["Dance"]["COPENID"] = OP_Mode.Dtv[0]["WeChatOpenID"].ToString().Trim(); Response.Cookies["Dance"]["CNAME"] = HttpUtility.UrlEncode(OP_Mode.Dtv[0]["Nick"].ToString()); //HttpUtility.UrlDecode(Request.Cookies["SK_WZGY"]["CNAME"].ToString().Trim(), Encoding.GetEncoding("UTF-8")) Response.Cookies["Dance"]["LTIME"] = OP_Mode.Dtv[0]["LTIME"].ToString().Trim(); Response.Cookies["Dance"]["HEADURL"] = OP_Mode.Dtv[0]["HeadImage"].ToString().Trim(); Response.Cookies["Dance"][Constant.COOKIENAMEUSER_CNAME] = OP_Mode.Dtv[0]["Nick"].ToString().Trim(); Response.Cookies[Constant.COOKIENAMEUSER][Constant.COOKIENAMEUSER_CTX] = OP_Mode.Dtv[0]["HeadImage"].ToString().Trim(); Response.Cookies["Dance"]["LOGIN"] = "******"; Response.Cookies[Constant.COOKIENAMEOPENDOOR][Constant.COOKIENAMEOPENDOOR_LGOIN] = "true"; ///设置COOKIE最长时间 不设置时间,窗口关闭则丢失 // Response.Cookies["WeChat_Yanwo"].Expires = DateTime.MaxValue; string MSG = string.Empty;// string.Format("<img class=\"img-rounded\" src=\"{1}\" width=\"60PX\" />欢迎 {0} 注册成功。<br/>祝您生活愉快。", OP_Mode.Dtv[0]["CNAME"].ToString(), OP_Mode.Dtv[0]["HEADURL"].ToString()); MSG = "<img class=\"img-rounded\" src=\"" + OP_Mode.Dtv[0]["HeadImage"].ToString() + "\" width=\"60PX\" />欢迎 " + OP_Mode.Dtv[0]["Nick"].ToString() + " 注册成功。<br/>祝您生活愉快。"; MessageBox("", MSG); return; } } } catch (Exception ex) { DeBugMsg += "<br>" + ex.ToString(); MessageBox("", "4:" + DeBugMsg); } } } else { DeBugMsg += OP_Mode.strErrMsg; MessageBox("", "5:" + DeBugMsg); } } } }
protected void btnNotify_Click(object sender, EventArgs e) { string url = ""; try { string strReturnValue = txtReturnValue.Text.Trim(); string payType = rblPayType.SelectedValue; if (string.IsNullOrEmpty(strReturnValue)) { Page.ClientScript.RegisterStartupScript(this.GetType(), DateTime.Now.Ticks.ToString(), "alert('请输入通知内容!');", true); } else if (payType == "0") { Page.ClientScript.RegisterStartupScript(this.GetType(), DateTime.Now.Ticks.ToString(), "alert('请选择支付方式!');", true); } else if (payType == "1") { #region 支付宝 string hiddenStr = ""; string[] strReturnValueS = strReturnValue.Split(new string[] { "\r\n", "\r" }, StringSplitOptions.RemoveEmptyEntries); for (int i = 0; i < strReturnValueS.Length; i++) { if (strReturnValueS[i] != "") { string[] strs = strReturnValueS[i].Split('='); hiddenStr += "<input type='hidden' name='" + strs[0].Trim() + "' value='" + strs[1].Trim() + "' />"; } } if (!string.IsNullOrEmpty(hiddenStr)) { hiddenStr = "<form name='aliPay' id='aliPay' method='post' action='ReturnPage/AliPayNotifyUrl.aspx'>" + hiddenStr; hiddenStr += "</form><script>document.aliPay.submit()</script>"; Response.Write(hiddenStr); } else { Page.ClientScript.RegisterStartupScript(this.GetType(), DateTime.Now.Ticks.ToString(), "alert('提交数据错误!');", true); } #endregion } else if (payType == "2") { #region 快钱 string hiddenStr = ""; string[] strReturnValueS = strReturnValue.Split(new string[] { "\r\n", "\r" }, StringSplitOptions.RemoveEmptyEntries); for (int i = 0; i < strReturnValueS.Length; i++) { if (strReturnValueS[i] != "") { string[] strs = strReturnValueS[i].Split('='); hiddenStr += "<input type='hidden' name='" + strs[0].Trim() + "' value='" + strs[1].Trim() + "' />"; } } if (!string.IsNullOrEmpty(hiddenStr)) { hiddenStr = "<form name='kqPay' id='kqPay' method='post' action='ReturnPage/99BillNotifyUrl.aspx'>" + hiddenStr; hiddenStr += "</form><script>document.kqPay.submit()</script>"; Response.Write(hiddenStr); } else { Page.ClientScript.RegisterStartupScript(this.GetType(), DateTime.Now.Ticks.ToString(), "alert('提交数据错误!');", true); } #endregion } else if (payType == "3") { #region 汇付 string hiddenStr = ""; string[] strReturnValueS = strReturnValue.Split(new string[] { "\r\n", "\r" }, StringSplitOptions.RemoveEmptyEntries); for (int i = 0; i < strReturnValueS.Length; i++) { if (strReturnValueS[i] != "") { string[] strs = strReturnValueS[i].Split('='); hiddenStr += "<input type='hidden' name='" + strs[0].Trim() + "' value='" + strs[1].Trim() + "' />"; } } if (!string.IsNullOrEmpty(hiddenStr)) { hiddenStr = "<form name='hfPay' id='hfPay' method='post' action='ReturnPage/ChinaPnrNotifyUrl.aspx'>" + hiddenStr; hiddenStr += "</form><script>document.hfPay.submit()</script>"; Response.Write(hiddenStr); } else { Page.ClientScript.RegisterStartupScript(this.GetType(), DateTime.Now.Ticks.ToString(), "alert('提交数据错误!');", true); } #endregion } else if (payType == "4") { #region 财付通 #endregion } else if (payType == "9") { #region 支付宝POS Byte[] strByte = System.Text.Encoding.Default.GetBytes(strReturnValue); System.Net.WebClient wc = new System.Net.WebClient(); //本地测试 //url = "http://" + Request.Url.Authority + "/PiaoBaoWork/Pay/Pos/AliPayPosNotifyUrl.aspx"; //正式地址 url = "http://" + Request.Url.Authority + "/Pay/Pos/AliPayPosNotifyUrl.aspx"; wc.UploadData(url, "POST", strByte); #endregion } else if (payType == "12") { #region 汇付POS //Byte[] strByte = System.Text.Encoding.Default.GetBytes(strReturnValue); //System.Net.WebClient wc = new System.Net.WebClient(); ////本地测试 //url = "http://" + Request.Url.Authority + "/PiaoBaoWork/Pay/Pos/ChinaPnrPosNotifyUrl.aspx"; ////正式地址 ////url = "http://" + Request.Url.Authority + "/Pay/Pos/ChinaPnrPosNotifyUrl.aspx"; //wc.UploadData(url, "POST", strByte); string hiddenStr = ""; string[] strReturnValueS = strReturnValue.Split(new string[] { "\r\n", "\r" }, StringSplitOptions.RemoveEmptyEntries); for (int i = 0; i < strReturnValueS.Length; i++) { if (strReturnValueS[i] != "") { string[] strs = strReturnValueS[i].Split('='); hiddenStr += "<input type='hidden' name='" + strs[0].Trim() + "' value='" + strs[1].Trim() + "' />"; } } if (!string.IsNullOrEmpty(hiddenStr)) { hiddenStr = "<form name='ChinaPnr' id='ChinaPnr' method='post' action='Pos/ChinaPnrPosNotifyUrl.aspx'>" + hiddenStr; hiddenStr += "</form><script>document.ChinaPnr.submit()</script>"; Response.Write(hiddenStr); } else { Page.ClientScript.RegisterStartupScript(this.GetType(), DateTime.Now.Ticks.ToString(), "alert('提交数据错误!');", true); } #endregion } else if (payType == "13") { #region 易宝POS Byte[] strByte = System.Text.Encoding.Default.GetBytes(strReturnValue); System.Net.WebClient wc = new System.Net.WebClient(); //本地测试 //url = "http://" + Request.Url.Authority + "/PiaoBaoWork/Pay/Pos/YeePayPosNotifyUrl.aspx"; //正式地址 url = "http://" + Request.Url.Authority + "/Pay/Pos/YeePayPosNotifyUrl.aspx"; wc.UploadData(url, "POST", strByte); #endregion } else if (payType == "20") { #region 支付宝 string hiddenStr = ""; string[] strReturnValueS = strReturnValue.Split(new string[] { "\r\n", "\r" }, StringSplitOptions.RemoveEmptyEntries); for (int i = 0; i < strReturnValueS.Length; i++) { if (strReturnValueS[i] != "") { string[] strs = strReturnValueS[i].Split('='); hiddenStr += "<input type='hidden' name='" + strs[0].Trim() + "' value='" + strs[1].Trim() + "' />"; } } if (!string.IsNullOrEmpty(hiddenStr)) { hiddenStr = "<form name='aliPay' id='aliPay' method='post' action='PTReturnPage/AutoPayByAlipayNotifyUrl.aspx'>" + hiddenStr; hiddenStr += "</form><script>document.aliPay.submit()</script>"; Response.Write(hiddenStr); } else { Page.ClientScript.RegisterStartupScript(this.GetType(), DateTime.Now.Ticks.ToString(), "alert('提交数据错误!');", true); } #endregion } } catch (Exception ex) { Page.ClientScript.RegisterStartupScript(this.GetType(), DateTime.Now.Ticks.ToString(), "alert('操作异常!');", true); } lblUrl.Text = url; }
public void CallQuery() { console.text += "\n after gameobject find"; //SceneManager.LoadScene ("Location Menu", LoadSceneMode.Single); // string monthVar = System.DateTime.Now.Month.ToString (); // string dateVar = System.DateTime.Now.Date.ToString (); // if (monthVar < 10) // monthVar = "0" + monthVar; // if (dateVar < 10) // dateVar = "0" + dateVar; //console.text += "\n PRe using"; Debug.Log("Pre using"); using (var wc = new System.Net.WebClient()) { Debug.Log("Origin: " + origin); Debug.Log("Duration: " + duration); Debug.Log("Max Price: " + max_price); url = "http://api.sandbox.amadeus.com/v1.2/flights/inspiration-search?" + "apikey=" + apikey + "&origin=" + origin + "&one-way=false" + "&duration=" + duration + "&direct=true" + "&max_price=" + max_price; // url = "http://api.sandbox.amadeus.com/v1.2/flights/" + // "inspiration-search?apikey=5ydifrkNfmgRtCgp7lGDA4GYuOtsUlHG&" + // "origin=LAX&one-way=false&duration=3&direct=true&max_price=100"; var jsonString = wc.DownloadString(url); // Debug.Log (jsonString); q.CreateFromJson(jsonString); int len; if (q.results.Count < 4) { len = q.results.Count; } else { len = 4; } console.text += "\nlength: " + len; for (int i = 0; i < len; i++) { using (var wcTwo = new System.Net.WebClient()) { string cityurl = "https://api.sandbox.amadeus.com/v1.2/location/" + q.results [i].destination + "?apikey=" + apikey; // console.text += "\n" + cityurl; var tempJsonString = wcTwo.DownloadString(cityurl); // console.text += "\njson: " + tempJsonString; // console.text += "\nha: " + q.results [i].destination; // console.text += "\napikey: " + apikey; var N = SimpleJSON.JSON.Parse(tempJsonString); // console.text += "\nTEMPJSON: " + N; // console.text += "\nINSIDE LOOP"; // string city = "PORTLAND";//bs.GetCity (q.results [i].destination); // console.text += "\nCITY: " + city; // Debug.Log ("CITY: " + city); string city = N ["city"] ["name"]; // console.text += "\n" + city; airports.Add(q.results [i].destination); console.text += "\n firebase: " + q.results [i].destination; if (bs.reference.Child(q.results [i].destination) == null) { bs.reference.Child(q.results [i].destination).Child("city").SetValueAsync(city); bs.reference.Child(q.results [i].destination).Child("vrUrl").SetValueAsync(""); } cities.Add(city); Debug.Log(city); console.text += "\ncity " + i + ": " + city; } } // WWW www = new WWW (url); // yield return www; GameObject.Find("UserInfo").GetComponent <StoreUserInfo>().setAirportList(airports); GameObject.Find("UserInfo").GetComponent <StoreUserInfo>().setCityList(cities); console.text += "\n after gameobject find"; // SceneManager.LoadScene ("Location Menu", LoadSceneMode.Single); SceneManager.LoadSceneAsync("Location Menu", LoadSceneMode.Single); } }
/// <param name="context">The Context in which the receiver is running.</param> /// <param name="intent">The Intent being received.</param> /// <summary> /// This method is called when the BroadcastReceiver is receiving an Intent /// broadcast. /// </summary> public override void OnReceive(Context context, Intent intent) { //get action from intent string action = intent.Action; //get command from action string cmd = intent.GetStringExtra("command"); //write info Console.WriteLine("mIntentReceiver.onReceive " + action + " / " + cmd); //get artist from intent String artist = intent.GetStringExtra("artist"); //get album from intent String album = intent.GetStringExtra("album"); //get track from intent String track = intent.GetStringExtra("track"); //write all info Console.WriteLine(artist + ":" + album + ":" + track); //set content title to notification builder builder.SetContentTitle(artist); //set contennt text to notification builder builder.SetContentText(track + "-" + album); //set big style to builder builder.SetStyle(new NotificationCompat.BigTextStyle().BigText(track + "-" + album)); try { //seach album thumbnail from itunes api var json = new System.Net.WebClient().DownloadString("http://itunes.apple.com/search?term=" + Uri.EscapeDataString(track + " " + album + " " + artist) + "&country=mx&limit=1&entity=song"); //parse json downloaded to json object Newtonsoft.Json.Linq.JObject o = Newtonsoft.Json.Linq.JObject.Parse(json); //get json results child var n = o["results"]; //get firts "artworkUrl100" property string val = (string)n[0]["artworkUrl100"]; //check if exist thumbnail if (string.IsNullOrEmpty(val)) { //if thumbnail doesnt exists set default image to largeicon builder.SetLargeIcon(BitmapFactory.DecodeResource(null, Resource.Drawable.ic_launcher)); } else { //change 100x100 size of thumbnail to 600x600 image StringBuilder builde = new StringBuilder(val); builde.Replace("100x100", "600x600"); //webclient to download image WebClient c = new WebClient(); //downloadimage to bytearray byte[] data = c.DownloadData(builde.ToString()); //convert byte[] downloaded to bitmap and set large icon to builder builder.SetLargeIcon(Bitmap.CreateScaledBitmap(BitmapFactory.DecodeByteArray(data, 0, data.Length), 150, 150, false)); } } catch (Exception e) { //set default image to largeicon builder.SetLargeIcon(BitmapFactory.DecodeResource(null, Resource.Drawable.ic_launcher)); } //update/create a notification notificationManager.Notify(0, builder.Build()); }
public async Task <IViewComponentResult> InvokeAsync(string MemberMobile, List <CartsViewModel> Carts, ContactDataViewModel ContactData, int CartTobal) { TradeSPToken RtnModel = null; List <CartListViewModel> lstCLVM = null; string OrderId = ""; try { //檢查商品庫存 foreach (var o in Carts) { int stock = await IMR.MemberCartCheck(o.productId, o.sizeId, o.colorId, o.quantity); if (stock != 0) { return(View(new PostOrderViewModel1 { ret = stock, product = o.product })); } } // 8.系統讀取當日最後一張訂單號。 DateTime dt = DateTime.Now; OrderIdViewModel Order = await IMR.GetNewOrderId(dt); if (Order != null) { // 9.系統判斷8傳回值!=null。 // 10.系統設定OrderId=年月日+<8讀取值最後4碼加1>。 OrderId = Data.GetNewId(Order.OrderId, 9, 4); } else { // 9a.系統判斷8傳回值==null。 // 9a-1.系統設定OrderId=年月日+<0201>。 // 9a-2.回11。 OrderId = Data.GetStartId("B", dt); } // 6.系統在ViewComponent【Cart/PostOrder】中建立一筆綠界訂單。 string MerchantIDTmp = config["MerchantID"]; string TradeDesc = config["TradeDesc"]; //測試環境轉正式環境 //測試 //string MerchantID = "2000132"; //string HashKey = "5294y06JbISpM5x9"; //string HashIV = "v77hoKGq4kWxNNIS"; //string PostURL = "https://payment-stage.ecpay.com.tw/SP/CreateTrade"; //正式 string MerchantID = "3084097"; string HashKey = "AIlPEruFqmb1fZmz"; string HashIV = "oKf58WmB9vgevdrj"; string PostURL = "https://payment.ecpay.com.tw/SP/CreateTrade"; SortedDictionary <string, string> PostCollection = new SortedDictionary <string, string>(); PostCollection.Add("MerchantID", MerchantID); PostCollection.Add("MerchantTradeNo", $"{OrderId}{MerchantIDTmp}"); //PostCollection.Add("MerchantTradeNo", DateTime.Now.ToString("yyyyMMddHHmmss")); //PostCollection.Add("MerchantTradeNo", "sdfg1561/"); PostCollection.Add("MerchantTradeDate", dt.ToString("yyyy/MM/dd HH:mm:ss")); PostCollection.Add("PaymentType", "aio"); PostCollection.Add("TotalAmount", CartTobal.ToString()); PostCollection.Add("TradeDesc", TradeDesc); string ItemName = ""; foreach (var item in Carts) { ItemName += $"{item.product}{item.price}元#"; } ItemName = ItemName.Substring(0, ItemName.Length - 1); PostCollection.Add("ItemName", ItemName); PostCollection.Add("ReturnURL", config.GetConnectionString("ReturnURL")); PostCollection.Add("PaymentInfoURL", config.GetConnectionString("PaymentInfoURL")); PostCollection.Add("ChoosePayment", "ALL"); PostCollection.Add("EncryptType", "1"); PostCollection.Add("NeedExtraPaidInfo", "N"); PostCollection.Add("IgnorePayment", ""); //記憶卡號 //PostCollection.Add("BidingCard", ""); //PostCollection.Add("MerchantMemberID", ""); //分期付款 //PostCollection.Add("StoreID", ""); // PostCollection.Add("CustomField1", ""); //PostCollection.Add("CustomField2", ""); //PostCollection.Add("CustomField3", ""); // PostCollection.Add("CustomField4", ""); //定期定額 //PostCollection.Add("PeriodAmount", "5"); //PostCollection.Add("PeriodType", "Y"); //PostCollection.Add("Frequency", "1"); //PostCollection.Add("ExecTimes", "6"); //PostCollection.Add("PeriodReturnURL", "http://127.0.0.1/01/CheckOutFeedback.php"); //紅利折抵 //PostCollection.Add("Redeem", "Y"); //ATM繳費期限 //PostCollection.Add("ExpireDate", ""); //CVS&BARCODE繳費期限 //PostCollection.Add("StoreExpireDate", ""); //電子發票 //PostCollection.Add("InvoiceMark", "N");//電子發票開立註記 //PostCollection.Add("RelateNumber", DateTime.Now.ToString("yyyyMMddHHmmss")); //會員自訂編號 //PostCollection.Add("CustomerID", "");//客戶代號 //PostCollection.Add("CustomerName", "");//客戶名稱 //PostCollection.Add("CustomerAddr", "");//客戶地址 //PostCollection.Add("CustomerPhone", "0912345678");//客戶手機號碼 //PostCollection.Add("CustomerEmail", ""); //PostCollection.Add("TaxType", "1");//課稅類別 //PostCollection.Add("CarruerType", "");//載具類別 //PostCollection.Add("CarruerNum", ""); //PostCollection.Add("Donation", "2");//捐贈註記 //PostCollection.Add("LoveCode", "");//捐贈註記 //PostCollection.Add("Print", "0");//列印註記 //PostCollection.Add("InvoiceItemName", "商品名稱");//商品名稱 //PostCollection.Add("InvoiceItemCount", "1");//商品數量 //PostCollection.Add("InvoiceItemWord", "個");//商品單位 //PostCollection.Add("InvoiceItemPrice", "100");//商品價格 //PostCollection.Add("InvoiceItemTaxType", "");//商品課稅別 //PostCollection.Add("InvoiceRemark", "");//備註 //PostCollection.Add("DelayDay", "0");//延遲天數 //PostCollection.Add("InvType", "07");//字軌類別 //計算檢查碼 string str = string.Empty; string str_pre = string.Empty; foreach (var test in PostCollection) { str += string.Format("&{0}={1}", test.Key, test.Value); } str_pre += string.Format("HashKey={0}" + str + "&HashIV={1}", HashKey, HashIV); string urlEncodeStrPost = HttpUtility.UrlEncode(str_pre); string ToLower = urlEncodeStrPost.ToLower(); string sCheckMacValue = Data.GetSHA256(ToLower); PostCollection.Add("CheckMacValue", sCheckMacValue); string Result = ""; string ParameterString = string.Join("&", PostCollection.Select(p => p.Key + "=" + p.Value)); //### Server Post using (WebClient wc = new System.Net.WebClient()) { ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072; wc.Encoding = Encoding.UTF8; wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded"; Result = wc.UploadString(PostURL, ParameterString); } //### 轉Model RtnModel = JsonConvert.DeserializeObject <TradeSPToken>(Result); if (RtnModel.RtnCode != "1") { // 7a.系統判斷6執行失敗。 // 7a-1.系統回傳null。 RtnModel = null; } // 7.系統判斷6成功執行。 lstCLVM = new List <CartListViewModel>(); CartListViewModel CLVM; if (MemberMobile != "" && MemberMobile != null) { // 11.系統判斷MemberMobile!=""。 // 12.系統讀取購物車清單。 lstCLVM = await IMER.GetCartList(MemberMobile); foreach (var item in lstCLVM) { item.OrderId = OrderId; } } else { // 11a.系統判斷MemberMobile==""。 // 11a-1.系統將carts轉換為List<CartListViewModel>。 foreach (CartsViewModel item in Carts) { CLVM = new CartListViewModel(); CLVM.ProductId = item.productId; CLVM.Product = item.product; CLVM.ProducSizeId = item.sizeId; CLVM.ProductColorId = item.colorId; CLVM.Quantity = item.quantity; CLVM.Price = item.price; CLVM.ProductSize = item.size; CLVM.ProductColor = item.color; CLVM.OrderId = OrderId; lstCLVM.Add(CLVM); } // 11a-2.回13。 } // 13.系統新增一筆內部訂單。 int ret = await IMR.InsertOrder(OrderId, dt, MemberMobile, ContactData.Freight, CartTobal - ContactData.Freight, CartTobal, ContactData.MemberName, ContactData.eMail, ContactData.Phone, ContactData.ContactAddress, sCheckMacValue, lstCLVM, $"{OrderId}{MerchantIDTmp}", ContactData.MemberMobile); if (ret == 0) { // 14.系統判斷13執行成功。 // 15.系統設定傳回值=12讀取值。 } else { // 14a.系統判斷13執行失敗。 // 14a-1.系統設定傳回Model=null。 lstCLVM = null; RtnModel = null; // 14a-2.回16。 } } catch (Exception ex) { RtnModel = null; } // 16.系統回傳View【Cart/PostOrder】,並傳回new PostOrderViewModel1 // { OrderDetail=15設定傳回值, ContactData=contactData, CartTobal= cartTobal, OrderId=10設定OrderId, RtnModel=金流公司的TradeSPToken }。 return(View(new PostOrderViewModel1 { OrderDetail = lstCLVM, ContactData = ContactData, CartTobal = CartTobal, OrderId = OrderId, RtnModel = RtnModel })); }
protected void loadMostWanted() { //lblMostWanted.Text = "<h3>10 most wanted</h3>"; System.Web.UI.ControlCollection pnl = pnlMostWanted.Controls; string json = ""; using (var webClient = new System.Net.WebClient()) { string url = String.Format("{0}{1}", System.Configuration.ConfigurationManager.AppSettings["webServiceRootUrl"], "ReportExpiredRepeaters"); json = webClient.DownloadString(url); ViewState["expiredRepeaters"] = json; } dynamic data = JsonConvert.DeserializeObject <dynamic>(json); if (data.Report != null) { Label lbl = new Label(); lbl.Text = string.Format("<h3>{0}</h3><p>These repeaters have expired their coordination. If you know anything that may lead to the <del>arrest and conviction</del> updating of this record, please contact us or the repeater owner.", data.Report.Title); pnl.Add(lbl); Table table = new Table(); using (TableRow headerRow = new TableRow()) { headerRow.AddCell("Expired"); headerRow.AddCell("Repeater"); headerRow.AddCell("City"); headerRow.AddCell("Sponsor"); headerRow.AddCell("Trustee"); headerRow.CssClass = "expiredRepeaterHeader"; table.Rows.Add(headerRow); } if (data.Report.Data != null) { foreach (dynamic item in data.Report.Data) { dynamic repeater = item.Repeater; using (TableRow row = new TableRow()) { row.AddCell((string)repeater.YearsExpired + " yrs"); row.AddCell(string.Format("<a target='_blank' title='Details' href='/repeaters/details/?id={0}'>{1}<br>{2}</a>", (string)repeater.ID, (string)repeater.Output, (string)repeater.Callsign)); row.AddCell((string)repeater.City); row.AddCell((string)repeater.Sponsor); row.AddCell(string.Format("<a target='_blank' title='QRZ' href='https://qrz.com/db/{0}'>{1}</a>", (string)repeater.Trustee.Callsign, (string)repeater.Trustee.Name)); row.CssClass = "expiredRepeaterData"; table.Rows.Add(row); } } } else { using (TableRow row = new TableRow()) { row.AddCell("None! We're all current! Yay!", 5); row.CssClass = "expiredRepeaterData"; table.Rows.Add(row); } } pnl.Add(table); } }
private void LoadRepeaterLinks(string repeaterId) { using (var webClient = new System.Net.WebClient()) { string rootUrl = System.Configuration.ConfigurationManager.AppSettings["webServiceRootUrl"].ToString(); string url = String.Format("{0}ListRepeaterLinks?repeaterid={1}", rootUrl, repeaterId); string json = webClient.DownloadString(url); dynamic data = JsonConvert.DeserializeObject <dynamic>(json); tblLinks.Rows.Clear(); using (TableHeaderRow thr = new TableHeaderRow()) { using (TableHeaderCell thc = new TableHeaderCell()) { Button btnAddRepeaterLink = new Button(); btnAddRepeaterLink.ID = "btnLoadLinks"; btnAddRepeaterLink.Click += btnLoadLinks_Click; btnAddRepeaterLink.Text = "Add new"; thc.Controls.Add(btnAddRepeaterLink); thr.Cells.Add(thc); } using (TableHeaderCell thc = new TableHeaderCell()) { thc.Text = "Frequency"; thr.Cells.Add(thc); } using (TableHeaderCell thc = new TableHeaderCell()) { thc.Text = "Callsign"; thr.Cells.Add(thc); } using (TableHeaderCell thc = new TableHeaderCell()) { thc.Text = "City"; thr.Cells.Add(thc); } tblLinks.Rows.Add(thr); } foreach (dynamic obj in data) { TableRow row = new TableRow(); TableCell cell = new TableCell(); if (obj["DirectlyLinked"] == true) { cell = new TableCell(); Button btn = new Button(); btn.Text = "Remove"; string userid = obj["ID"].ToString(); btn.Click += (sender, e) => btnRemoveRepeaterLink(sender, e, userid); cell.Controls.Add(btn); row.Cells.Add(cell); } else { cell = new TableCell(); Button btn = new Button(); btn.Text = "Indirect Link"; btn.ToolTip = "This is linked through a linked repeater. You can't delete this."; btn.Enabled = false; cell.Controls.Add(btn); row.Cells.Add(cell); } cell = new TableCell(); cell.Text = stringify(obj["OutputFrequency"]); row.Cells.Add(cell); cell = new TableCell(); cell.Text = stringify(obj["Callsign"]); row.Cells.Add(cell); cell = new TableCell(); cell.Text = stringify(obj["City"]); row.Cells.Add(cell); tblLinks.Rows.Add(row); } } }
public static void Main(string[] args) { try { var directory = Environment.CurrentDirectory; var referencesDirectory = Environment.ExpandEnvironmentVariables(@"%USERPROFILE%\Documents\My Games\Terraria\ModLoader\references"); Directory.CreateDirectory(referencesDirectory); const string TML_CORE = "https://raw.githubusercontent.com/tModLoader/tModLoader/master/patches/tModLoader/Terraria.ModLoader/ModLoader.cs"; var wc = new System.Net.WebClient(); Console.Write("tModLoader version: "); var coreMatcher = Regex.Match(wc.DownloadString(TML_CORE), "new Version\\((.*?)\\)"); var tmlVercode = wc.DownloadString(TML_CORE); var version = new Version(coreMatcher.Groups[1].Value.Replace(",", ".").Replace(" ", "")); Console.WriteLine(version); var fileName = Path.Combine(referencesDirectory, "Mono.Cecil.dll"); wc.DownloadFile("https://github.com/tModLoader/tModLoader/raw/master/references/Mono.Cecil.dll", fileName); Console.WriteLine("Download Mono.Cecil to " + fileName); if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { fileName = Path.Combine(directory, "ModCompile_XNA.zip"); wc.DownloadFile("https://github.com/tModLoader/tModLoader/releases/download/v" + version + "/ModCompile_XNA.zip", fileName); Console.WriteLine("Download ModCompile XNA to " + fileName); ZipFile.ExtractToDirectory(Path.Combine(directory, "ModCompile_XNA.zip"), referencesDirectory); fileName = Path.Combine(directory, "xnafx40_redist.msi"); wc.DownloadFile("https://download.microsoft.com/download/5/3/A/53A804C8-EC78-43CD-A0F0-2FB4D45603D3/xnafx40_redist.msi", fileName); Console.WriteLine("Download XNA to " + fileName); Process.Start("msiexec", $"/i \"{fileName}\" /quiet").WaitForExit(); Console.WriteLine("XNA installed."); } var types = Assembly.Load(File.ReadAllBytes(Path.Combine(referencesDirectory, "Mono.Cecil.dll"))).GetTypes(); dynamic assemblyDef; foreach (var type in types) { if (type.FullName == "Mono.Cecil.AssemblyDefinition") { foreach (var method in type.GetMethods()) { if (method.ToString() == "Mono.Cecil.AssemblyDefinition ReadAssembly(System.String)") { assemblyDef = method.Invoke(null, new object[] { Path.Combine(referencesDirectory, "tModLoader.XNA.exe") }); foreach (var resource in assemblyDef.MainModule.Resources) { if (resource.Name.EndsWith(".dll")) { fileName = Path.Combine(referencesDirectory, resource.Name); Console.Write("Write Resource " + resource.Name + " to " + fileName); try { File.WriteAllBytes(fileName, resource.GetResourceData()); Console.WriteLine(); } catch (Exception e) { Console.WriteLine(" failed " + e.ToString()); } } } } } } } } catch (Exception e) { Console.WriteLine(e); } }
public static void CheckUpdate(string MyCurrentVersion) { if (wManager.Information.Version.Contains("1.7.2")) { Logger.Log($"AIO couldn't load (v {wManager.Information.Version})"); Products.ProductStop(); return; } DateTime dateBegin = new DateTime(2020, 1, 1); DateTime currentDate = DateTime.Now; long elapsedTicks = currentDate.Ticks - dateBegin.Ticks; elapsedTicks /= 10000000; double timeSinceLastUpdate = elapsedTicks - AIOTBCSettings.CurrentSetting.LastUpdateDate; // If last update try was < 10 seconds ago, we exit to avoid looping if (timeSinceLastUpdate < 10) { Logger.Log($"Update failed {timeSinceLastUpdate} seconds ago. Exiting updater."); return; } try { AIOTBCSettings.CurrentSetting.LastUpdateDate = elapsedTicks; AIOTBCSettings.CurrentSetting.Save(); Logger.Log("Starting updater"); string onlineFile = "https://github.com/Wholesome-wRobot/Z.E.TBC_AllInOne_FightClasses/raw/newsettings/AIO/Compiled/Wholesome_TBC_AIO_Fightclasses.dll"; // Version check string onlineVersion = "https://raw.githubusercontent.com/Wholesome-wRobot/Z.E.TBC_AllInOne_FightClasses/newsettings/AIO/Compiled/Version.txt"; var onlineVersionContent = new System.Net.WebClient { Encoding = Encoding.UTF8 }.DownloadString(onlineVersion); if (onlineVersionContent == null || onlineVersionContent.Length > 10 || onlineVersionContent == MyCurrentVersion) { Logger.Log($"Your version is up to date ({MyCurrentVersion})"); return; } // File check string currentFile = Others.GetCurrentDirectory + @"\FightClass\" + wManager.wManagerSetting.CurrentSetting.CustomClass; var onlineFileContent = new System.Net.WebClient { Encoding = Encoding.UTF8 }.DownloadData(onlineFile); if (onlineFileContent != null && onlineFileContent.Length > 0) { Logger.Log($"Your version : {MyCurrentVersion}"); Logger.Log($"Online Version : {onlineVersionContent}"); Logger.Log("Trying to update"); System.IO.File.WriteAllBytes(currentFile, onlineFileContent); // replace user file by online file Thread.Sleep(5000); new Thread(CustomClass.ResetCustomClass).Start(); } } catch (Exception e) { Logging.WriteError("Auto update: " + e); } }
/// <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 = string.Empty; DA.GetData(2, ref filePath); if (!filePath.EndsWith(@"\")) { filePath = filePath + @"\"; } string prefix = string.Empty; DA.GetData(3, ref prefix); if (prefix == string.Empty) { prefix = slippySource; } string URL = slippyURL; string userAgent = string.Empty; 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"; if (!tilesOut) { //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; } List <Rectangle3d> tileRectangles = new List <Rectangle3d>(); ///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 List <Point3d> boxPts = Convert.GetTileAsPolygon(zoom, y, x).ToList(); boxPtList.AddRange(Convert.GetTileAsPolygon(zoom, y, x).ToList()); string cacheFilePath = cacheLoc + slippySource.Replace(" ", "") + zoom + "-" + x + "-" + y + ".jpg"; cacheFilePaths.Add(cacheFilePath); tileTotalCount = tileTotalCount + 1; if (tilesOut) { mapList.Append(new GH_String(cacheFilePath), path); Rectangle3d tileRectangle = BBoxToRect(new BoundingBox(boxPts)); tileRectangles.Add(tileRectangle); imgFrame.Append(new GH_Rectangle(tileRectangle), path); } } } 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); if (!tilesOut) { 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) && !tilesOut) { 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."); AddPreviewItem(imgPath, boundary[i], rect); continue; } } } if (tilesOut) { for (int t = 0; t < cacheFilePaths.Count; t++) { if (File.Exists(cacheFilePaths[t])) { AddPreviewItem(cacheFilePaths[t], tileRectangles[t].ToNurbsCurve(), tileRectangles[t]); } } 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; 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); Bitmap tmpImage = new Bitmap(256, 256); System.Net.WebClient client = new System.Net.WebClient(); ///insert header if required client.Headers.Add("user-agent", userAgent); if (run == true) { try { client.DownloadFile(urlAuth, tileCacheLoc); tmpImage = new Bitmap(Image.FromFile(tileCacheLoc)); } catch (WebException e) { using (Graphics tmp = Graphics.FromImage(tmpImage)) { tmp.Clear(Color.White); } AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, e.Message); } } 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(); if (!tilesOut) { AddPreviewItem(imgPath, boundary[i], rect); } else { for (int t = 0; t < cacheFilePaths.Count; t++) { if (File.Exists(cacheFilePaths[t])) { AddPreviewItem(cacheFilePaths[t], tileRectangles[t].ToNurbsCurve(), tileRectangles[t]); } } } //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); ///Add copyright info here DA.SetDataList(3, ""); }
public static void CheckUpdate(string mainVersion) { DateTime dateBegin = new DateTime(2020, 1, 1); DateTime currentDate = DateTime.Now; long elapsedTicks = currentDate.Ticks - dateBegin.Ticks; elapsedTicks /= 10000000; double timeSinceLastUpdate = elapsedTicks - WholesomeProfessionsSettings.CurrentSetting.LastUpdateDate; string currentFile = Others.GetCurrentDirectory + $@"\Products\{Main.productName}.dll"; string oldFile = Others.GetCurrentDirectory + $@"\Products\{Main.productName} dmp"; // On supprime la vieille version if (File.Exists(oldFile)) { try { var fs = new FileStream(oldFile, FileMode.Open); if (fs.CanWrite) { Logger.Log("Deleting dump file"); fs.Close(); File.Delete(oldFile); } fs.Close(); } catch { ShowReloadMessage(); return; } } // If last update try was < 10 seconds ago, we exit to avoid looping if (timeSinceLastUpdate < 10) { Logger.Log($"Last update attempt was {timeSinceLastUpdate} seconds ago. Exiting updater."); return; } try { WholesomeProfessionsSettings.CurrentSetting.LastUpdateDate = elapsedTicks; WholesomeProfessionsSettings.CurrentSetting.Save(); Logger.Log("Starting updater"); string onlineFile = "https://github.com/Wholesome-wRobot/Wholesome-professions/raw/master/Wholesome_Professions_WotlK/Compiled/WRobot/Products/Wholesome%20Professions%20WotlK.dll"; string onlineVersion = "https://raw.githubusercontent.com/Wholesome-wRobot/Wholesome-professions/master/Wholesome_Professions_WotlK/Compiled/Version.txt"; var onlineVersionContent = new System.Net.WebClient { Encoding = Encoding.UTF8 }.DownloadString(onlineVersion); Logger.Log($"Online Version : {onlineVersionContent}"); if (onlineVersionContent == null || onlineVersionContent.Length > 10 || onlineVersionContent == mainVersion) { Logger.Log($"Your version is up to date ({mainVersion})"); return; } var onlineFileContent = new System.Net.WebClient { Encoding = Encoding.UTF8 }.DownloadData(onlineFile); Logger.LogDebug(onlineFileContent.Length.ToString()); if (onlineFileContent != null && onlineFileContent.Length > 0) { Logger.Log($"Your version : {mainVersion}"); Logger.Log("Trying to update"); File.Move(currentFile, oldFile); Logger.Log("Writing file"); File.WriteAllBytes(currentFile, onlineFileContent); // replace user file by online file Thread.Sleep(2000); ShowReloadMessage(); } } catch (Exception e) { Logging.Write("Auto update: " + e); } }
public static string loadFromRect(Rect a) { System.Net.WebClient wc = new System.Net.WebClient(); return(wc.DownloadString(buildUrl(a))); }
private static double objectiveValue(Chromosome chromosome) { double[] weights = new double[3]; double price = 0; double distance = 0; double changes = 0; double objValue = 0; weights[0] = globals.weight1; weights[1] = globals.weight2; weights[2] = globals.weight3; string origin = null; string destination = null; foreach (var gene in chromosome.Genes) { destination = globals.iata[(int)gene.RealValue]; if (origin != null) { using (var webClient = new System.Net.WebClient()) { var json = webClient.DownloadString("http://api.travelpayouts.com/v2/prices/month-matrix?latest?currency=usd&origin=" + origin + "&destination=" + destination + "&beginning_of_period=" + globals.date + "&period_type=month&page=1&limit=30&show_to_affiliates=fALSE&sorting=price&trip_class=0&token=6ef8913be158c79f08b3ba1098cb2f07"); JToken flightData = JObject.Parse(json); var json3 = webClient.DownloadString("http://api.travelpayouts.com/v2/prices/latest?currency=usd&origin=" + origin + "&destination=" + destination + "&period_type=year&page=1&limit=30&show_to_affiliates=true&sorting=price&trip_class=0&token=6ef8913be158c79f08b3ba1098cb2f07"); JToken flightData3 = JObject.Parse(json3); var json2 = webClient.DownloadString("http://api.travelpayouts.com/v1/prices/cheap?currency=USD&origin=" + origin + "&destination=" + destination + "&token=6ef8913be158c79f08b3ba1098cb2f07"); JToken flightData2 = JObject.Parse(json2); if (flightData.SelectToken("data[0].distance") != null) { distance = distance + (int)flightData.SelectToken("data[0].distance"); } else if (flightData3.SelectToken("data[0].distance") != null) { distance = distance + (int)flightData3.SelectToken("data[0].distance"); } else { globals.errorOutput = true; } if (flightData.SelectToken("data[0].number_of_changes") != null) { changes = changes + (int)flightData.SelectToken("data[0].number_of_changes"); } else if (flightData3.SelectToken("data[0].number_of_changes") != null) { changes = changes + (int)flightData3.SelectToken("data[0].number_of_changes"); } else { globals.errorOutput = true; } if (flightData2.SelectToken("data." + destination + ".0.price") != null) { price = price + (int)flightData2.SelectToken("data." + destination + ".0.price"); } else if (flightData3.SelectToken("data[0].value") != null) { price = price + (int)flightData3.SelectToken("data[0].value"); } else if (flightData.SelectToken("data[0].value") != null) { price = price + (int)flightData.SelectToken("data[0].value"); } else { globals.errorOutput = true; } } } origin = destination; } price = (price * 0.01) * weights[0]; distance = (distance * 0.01) * weights[1]; changes = changes * weights[2]; objValue = price + distance + changes; return(1 - objValue / 10000); }
public static void ga_OnRunComplete(object sender, GaEventArgs e) { double price = 0; double distance = 0; double changes = 0; string origin = null; string destination = null; var fittest = e.Population.GetTop(1)[0]; foreach (var gene in fittest.Genes) { destination = globals.iata[(int)gene.RealValue]; System.Diagnostics.Debug.WriteLine(globals.iata[(int)gene.RealValue]); globals.orderOfDestinations.Add(globals.iata[(int)gene.RealValue]); if (origin != null) { using (var webClient = new System.Net.WebClient()) { var json = webClient.DownloadString("http://api.travelpayouts.com/v2/prices/month-matrix?latest?currency=usd&origin=" + origin + "&destination=" + destination + "&beginning_of_period=" + globals.date + "&period_type=month&page=1&limit=30&show_to_affiliates=fALSE&sorting=price&trip_class=0&token=6ef8913be158c79f08b3ba1098cb2f07"); JToken flightData = JObject.Parse(json); var json3 = webClient.DownloadString("http://api.travelpayouts.com/v2/prices/latest?currency=usd&origin=" + origin + "&destination=" + destination + "&period_type=year&page=1&limit=30&show_to_affiliates=true&sorting=price&trip_class=0&token=6ef8913be158c79f08b3ba1098cb2f07"); JToken flightData3 = JObject.Parse(json3); var json2 = webClient.DownloadString("http://api.travelpayouts.com/v1/prices/cheap?currency=USD&origin=" + origin + "&destination=" + destination + "&token=6ef8913be158c79f08b3ba1098cb2f07"); JToken flightData2 = JObject.Parse(json2); if (flightData.SelectToken("data[0].distance") != null) { distance = distance + (int)flightData.SelectToken("data[0].distance"); } else if (flightData3.SelectToken("data[0].distance") != null) { distance = distance + (int)flightData3.SelectToken("data[0].distance"); } else { globals.errorOutput = true; } if (flightData.SelectToken("data[0].number_of_changes") != null) { changes = changes + (int)flightData.SelectToken("data[0].number_of_changes"); } else if (flightData3.SelectToken("data[0].number_of_changes") != null) { changes = changes + (int)flightData3.SelectToken("data[0].number_of_changes"); } else { globals.errorOutput = true; } if (flightData2.SelectToken("data." + destination + ".0.price") != null) { price = price + (int)flightData2.SelectToken("data." + destination + ".0.price"); } else if (flightData3.SelectToken("data[0].value") != null) { price = price + (int)flightData3.SelectToken("data[0].value"); } else if (flightData.SelectToken("data[0].value") != null) { price = price + (int)flightData.SelectToken("data[0].value"); } else { globals.errorOutput = true; } } } origin = destination; } globals.totalPrice = price; globals.totalDistance = distance; globals.totalChanges = changes; System.Diagnostics.Debug.WriteLine(globals.totalPrice); System.Diagnostics.Debug.WriteLine(globals.totalDistance); System.Diagnostics.Debug.WriteLine(globals.totalChanges); }
private static void EventLoop( string inputLine, string addresser, string fromChannel, PingSender.cs.PingSender ping, bool joined1, bool joined2, string nickname, bool identified, object stream) { while (true) { inputLine = reader.ReadLine(); string parsedLine = null; foreach (var channel in settings.channels) { if (inputLine.Contains(channel.name)) { fromChannel = inputLine.Substring(inputLine.IndexOf("#")).Split(' ')[0]; } if (inputLine.Contains(settings.nick + " = " + channel.name) || inputLine.Contains(settings.nick + " = " + channel.name)) //if (inputLine.Contains(settings.nick + " = " + settings.channels[0].name)) { CsBot.CommandHandler.ParseUsers(inputLine); } //if (inputLine.Contains(settings.channels[0].name)) if (joined1 && !inputLine.EndsWith(fromChannel)) { //parsedLine = inputLine.Substring(inputLine.IndexOf(m_fromChannel) + m_fromChannel.Length + 1); if (!inputLine.EndsWith(channel.name) && (parsedLine == null || !parsedLine.StartsWith(":" + settings.command_start))) { parsedLine = inputLine.Substring(inputLine.IndexOf(fromChannel) + channel.name.Length + 1).Trim(); } } } if (!joined1 || !joined2) { Console.WriteLine(inputLine); } if (inputLine.Contains("NICK :")) { string origUser = inputLine.Substring(1, inputLine.IndexOf("!") - 1); string newUser = inputLine.Substring(inputLine.IndexOf("NICK :") + 6); CsBot.CommandHandler.UpdateUserName(origUser, newUser); } if (inputLine.EndsWith("JOIN " + fromChannel)) { // Parse nickname of person who joined the channel nickname = inputLine.Substring(1, inputLine.IndexOf("!") - 1); if (nickname == settings.nick) { if (fromChannel == settings.channels[0].name) { joined1 = true; } else if (fromChannel == settings.channels[1].name) { joined2 = true; } ch.HandleMessage(":" + settings.command_start + "say I'm back baby!", fromChannel, addresser); continue; } // Welcome the nickname to channel by sending a notice writer.WriteLine("NOTICE " + nickname + ": Hi " + nickname + " and welcome to " + fromChannel + " channel!"); ch.HandleMessage(":" + settings.command_start + "say " + nickname + ": Hi and welcome to " + fromChannel + " channel!", fromChannel, addresser); ch.AddUser(nickname); writer.Flush(); // Sleep to prevent excess flood Thread.Sleep(2000); } else if (inputLine.StartsWith(":NickServ") && inputLine.Contains("You are now identified")) { identified = true; Console.WriteLine(inputLine); } else if (inputLine.Contains("!") && inputLine.Contains(" :" + settings.command_start + "quit")) { addresser = inputLine.Substring(1, inputLine.IndexOf("!") - 1); bool useChannel = false; if (inputLine.IndexOf("#") >= 0) { useChannel = true; fromChannel = inputLine.Substring(inputLine.IndexOf("#")).Split(' ')[0]; } if (settings.admins != null && Array.IndexOf(settings.admins, addresser) >= 0) { foreach (Channel channel in settings.channels) { ch.HandleMessage(":" + settings.command_start + "say Awe, Crap!", channel.name, addresser); } ping.Stop(); IrcBot.CloseProgram(writer, reader, m_irc); } else { CsBot.CommandHandler.Say("You don't have permissions.", useChannel ? fromChannel : addresser); } } else if (inputLine.Contains("!") && inputLine.Contains(" :" + settings.command_start + "reload")) { addresser = inputLine.Substring(1, inputLine.IndexOf("!") - 1); bool useChannel = false; if (inputLine.IndexOf("#") >= 0) { useChannel = true; fromChannel = inputLine.Substring(inputLine.IndexOf("#")).Split(' ')[0]; } if (settings.admins != null && Array.IndexOf(settings.admins, addresser) >= 0) { using (var webClient = new System.Net.WebClient()) { Stream setting_file = webClient.OpenRead(SETTINGS_FILE); DataContractJsonSerializer js = new DataContractJsonSerializer(typeof(Settings)); settings = (Settings)js.ReadObject(setting_file); } //setting_file = new FileStream(SETTINGS_FILE, FileMode.Open); //settings = (Settings)js.ReadObject(setting_file); //setting_file.Close(); //setting_file = null; CsBot.CommandHandler.settings = settings; CsBot.CommandHandler.Say("Reloaded settings from web service.", useChannel ? fromChannel : addresser); } else { CsBot.CommandHandler.Say("You don't have permissions.", useChannel ? fromChannel : addresser); } } else if (inputLine.Contains(settings.command_start) && parsedLine != null && parsedLine.StartsWith(":" + settings.command_start)) { addresser = inputLine.Substring(1, inputLine.IndexOf("!") - 1); fromChannel = inputLine.Substring(inputLine.IndexOf("#")).Split(' ')[0]; ch.HandleMessage(parsedLine, fromChannel, addresser); } else if (inputLine.StartsWith("PING :")) { writer.WriteLine("PONG :" + inputLine.Substring(inputLine.IndexOf(":") + 1)); writer.Flush(); } else if (inputLine.Contains("PONG") && (!joined1 || !joined2)) { if (isUnderscoreNick) { writer.WriteLine("PRIVMSG NickServ :ghost " + settings.nick + " " + settings.password); writer.WriteLine("NICK " + settings.nick); Console.WriteLine("NICK " + settings.nick); ch.HandleMessage(":" + settings.command_start + "say identify " + settings.password, "NickServ", settings.nick); isUnderscoreNick = false; } else { for (int i = 0; i < settings.channels.Count; i++) { if (settings.channels[i].key != "") { writer.WriteLine("JOIN " + settings.channels[i].name + " " + settings.channels[i].key); } else { writer.WriteLine("JOIN " + settings.channels[i].name); } writer.Flush(); } } } else if (inputLine.Contains("PONG") && (joined1 || joined2) && !identified) { ch.HandleMessage(":" + settings.command_start + "say identify " + settings.password, "NickServ", addresser); } else if (inputLine.Contains(":Nickname is already in use.")) { Console.WriteLine("Reopening with _ nick."); writer.Close(); reader.Close(); m_irc.Close(); m_irc = new TcpClient(); m_irc.Connect(settings.server, settings.port); if (settings.secure == "1") { stream = new SslStream(m_irc.GetStream(), true, new RemoteCertificateValidationCallback(ValidateServerCertificate)); SslStream sslStream = (SslStream)stream; sslStream.AuthenticateAsClient(settings.server); } else { stream = m_irc.GetStream(); } reader = new StreamReader((Stream)stream); writer = new StreamWriter((Stream)stream); Console.WriteLine(settings.user); // Start PingSender thread ping = new PingSender.cs.PingSender(); ping.Start(); writer.WriteLine(settings.user); writer.Flush(); writer.WriteLine("NICK _" + settings.nick); Console.WriteLine("NICK _" + settings.nick); ch = new CommandHandler(writer, reader); isUnderscoreNick = true; } else if (inputLine.Contains(settings.nick) && inputLine.Contains("PRIVMSG") && (inputLine.Contains("rock") || inputLine.Contains("paper") || inputLine.Contains("scissors"))) { Console.WriteLine(inputLine); addresser = inputLine.Substring(inputLine.IndexOf(":") + 1, inputLine.IndexOf("!") - inputLine.IndexOf(":") - 1); string choice = inputLine.Substring(inputLine.LastIndexOf(":") + 1); ch.DirectRoShamBo(choice); } else if (inputLine.Contains(settings.nick) && inputLine.Contains("PRIVMSG") && inputLine.Contains(":" + settings.command_start)) { Console.WriteLine("PrivateMessage: " + inputLine); addresser = inputLine.Substring(1, inputLine.IndexOf("!") - 1); string command = inputLine.Substring(inputLine.LastIndexOf(":" + settings.command_start)); ch.HandleMessage(command, addresser, addresser); } else { if (inputLine.Contains("PRIVMSG") && inputLine.Contains("!")) { string userName = inputLine.Substring(1, inputLine.IndexOf("!") - 1); ch.LastMessage(userName, inputLine, fromChannel); } } } }
public void iAcqua() { try { Label2.Text = "Communicating with Server..."; spinny.Visible = true; iphone.Visible = false; Label3.Visible = false; Center_Label(spinny); Center_Label(Label2); Center_Label(availableshsh); Center_Label(dlallBTN); Center_Label(dlblobBTN); if (DoIgiveAshit == true) { return; } Delay(1); File_Delete(temppath + "\\available.xml"); if (DoIgiveAshit == true) { return; } try { string Check = "http://iacqua.ih8sn0w.com/req.php?ecid=" + ECID; Uri CheckURI = new Uri(Check); dynamic clientCheck = new System.Net.WebClient(); clientCheck.Headers.Add("user-agent", "iacqua/1.0-452"); clientCheck.DownloadFileAsync(CheckURI, temppath + "\\available.xml"); if (DoIgiveAshit == true) { return; } while (!(clientCheck.IsBusy == false)) { Delay(0.5); } } catch (Exception ex) { Interaction.MsgBox("Error 3 : We have failed trying to connect to iFaith's SHSH Cache server!", MsgBoxStyle.Critical); // Display a child form. Form frm = new Form(); frm.MdiParent = MDIMain; frm.Width = this.Width / 2; frm.Height = this.Height / 2; frm.Show(); frm.Hide(); Welcome.MdiParent = MDIMain; Welcome.Show(); Welcome.Button1.Enabled = false; About.MdiParent = MDIMain; About.Show(); About.BringToFront(); this.Dispose(); return; } try { while (!(File_Exists(temppath + "\\available.xml") == true)) { if (DoIgiveAshit == true) { return; } Delay(0.1); } Delay(2); thatbox.LoadFile(temppath + "\\available.xml", RichTextBoxStreamType.PlainText); spinny.Visible = false; if (DoIgiveAshit == true) { return; } availableshsh.Items.AddRange(thatbox.Lines); if (availableshsh.Items.Count >= 1) { availableshsh.Items.Remove(availableshsh.Items.Item(availableshsh.Items.Count - 1)); } if (DoIgiveAshit == true) { return; } Label2.Text = "Available Blobs:"; Center_Label(Label2); Button1.Visible = true; //Show drop down menu. if (availableshsh.Items.Count == 0) { availableshsh.Items.Add("None"); dlallBTN.Enabled = false; dlblobBTN.Enabled = false; } else { dlallBTN.Enabled = true; dlblobBTN.Enabled = true; } availableshsh.Visible = true; availableshsh.SelectedIndex = 0; dlallBTN.Visible = true; dlblobBTN.Visible = true; } catch (Exception ex) { } } catch (Exception ex) { } }