//protected void btnLuuGiaytonopkem_Click(object sender, EventArgs e) //{ // String sDangkyChungnhan = btnLuuGiaytonopkem.CommandArgument; // if(sDangkyChungnhan != null) // { // Int16 iDangkyChungnhan = Int16.Parse(sDangkyChungnhan); // List<HosokemtheoTochucchungnhanEntity> lstHosonopkem = HosokemtheoTochucchungnhanBRL.GetByFK_iDangkyChungnhanVietGapID(iDangkyChungnhan); // HosokemtheoTochucchungnhanEntity oHosonopkem = null; // foreach (ListItem chk in cblGiaytonopkem.Items) // { // oHosonopkem = null; // oHosonopkem = lstHosonopkem.Find( // delegate(HosokemtheoTochucchungnhanEntity oHosonopkemFound) // { // return oHosonopkemFound.FK_iGiaytoID.ToString().Equals(chk.Value); // } // ); // if (oHosonopkem == null) // { // if (chk.Selected) // { // HosokemtheoTochucchungnhanEntity oHosonopkemNew = new HosokemtheoTochucchungnhanEntity(); // oHosonopkemNew.FK_iGiaytoID = int.Parse(chk.Value); // oHosonopkemNew.FK_iDangkyChungnhanVietGapID = iDangkyChungnhan; // HosokemtheoTochucchungnhanBRL.Add(oHosonopkemNew); // } // } // else // { // if (!chk.Selected) // { // HosokemtheoTochucchungnhanBRL.Remove(oHosonopkem.PK_iHosokemtheoID); // } // lstHosonopkem.Remove(oHosonopkem); //Loại bỏ phần tử đã tìm thấy để tối ưu // } // } // lstHosonopkem = null; // lblThongbao.Text = "Lưu thành công!"; // } //} //protected void btnHuygiaytonopkem_Click(object sender, EventArgs e) //{ // panGiayto.Visible = false; //} protected void btnAnChitiet_Click(object sender, EventArgs e) { pnThongTin.Visible = false; NameValueCollection filtered = new NameValueCollection(Request.QueryString); filtered.Remove("iTochucchungnhanID"); filtered.Remove("PK_iDangkyChungnhanVietGapID"); }
protected void bt_AddApply_Click(object sender, EventArgs e) { if ((int)ViewState["ID"] == 0) { MessageBox.Show(this, "对不起,请您先保存后在发起申请"); return; } Org_StaffBLL bll = new Org_StaffBLL((int)ViewState["ID"]); if (Org_StaffNumberLimitBLL.CheckAllowAdd(bll.Model.OrganizeCity, bll.Model.Position) < 0) { MessageBox.Show(this, "对不起当前城市该职位员工人数满额,要想继续新增请与人事经理联系"); return; } int budget = Org_StaffNumberLimitBLL.CheckOverBudget(bll.Model.OrganizeCity, bll.Model.Position); NameValueCollection dataobjects = new NameValueCollection(); dataobjects.Add("ID", ViewState["ID"].ToString()); dataobjects.Add("OrganizeCity", bll.Model.OrganizeCity.ToString()); dataobjects.Add("Position", bll.Model.Position.ToString()); dataobjects.Add("SalaryFlag", bll.Model["SalaryFlag"].ToString()); dataobjects.Add("StaffName", bll.Model.RealName.ToString()); dataobjects.Add("IsOverBudget", budget < 0 ? "1" : "2"); int TaskID = EWF_TaskBLL.NewTask("Add_Staff", (int)Session["UserID"], "人员入职流程,姓名:" + bll.Model.RealName, "~/SubModule/StaffManage/StaffDetail.aspx?ID=" + ViewState["ID"].ToString(), dataobjects); if (TaskID > 0) { bll.Model["TaskID"] = TaskID.ToString(); bll.Model["State"] = "2"; bll.Update(); } Response.Redirect("~/SubModule/EWF/Apply.aspx?TaskID=" + TaskID.ToString()); }
public void ServerLoop() { while (server_status == "online") { NameValueCollection pa = new NameValueCollection(); pa.Add("sid", host_id); byte[] data = client.UploadValues(AppConst.SERVER_DOMAIN + AppConst.SERVER_PATH + "?act=SetServerAct", pa); current_server_activity = HoUtility.ByteToString(data); //main.Log("current_server_activity: " + current_server_activity); if (current_server_activity == "client_connected") { data = client.UploadValues(AppConst.SERVER_DOMAIN + AppConst.SERVER_PATH + "?act=ClientIP", pa); revitClientIP = HoUtility.ByteToString(data).Trim(); } else if (current_server_activity == "model_uploaded") { System.IO.File.Delete("building.fbx"); client.DownloadFile(AppConst.SERVER_DOMAIN + AppConst.SERVER_PATH + AppConst.SERVER_MODEL_PATH + host_id + ".fbx", "building.fbx"); data = client.UploadValues(AppConst.SERVER_DOMAIN + AppConst.SERVER_PATH + "?act=GetSemanticFile", pa); main.SetSemanticInfo(HoUtility.ByteToString(data)); main.DownloadModelCb(); } Thread.Sleep(1000); } }
private void GetToken(string code) { using (var wb = new WebClient()) { var parameters = new NameValueCollection { {"client_id", "7be60d85e67648d490d3126f73c77434"}, {"client_secret", "fba7cd45089e4cf7922b086310d19913"}, {"grant_type", "authorization_code"}, {"redirect_uri", "http://localhost:4719/"}, {"code", code} }; var response = wb.UploadValues("https://api.instagram.com/oauth/access_token", "POST", parameters); string json = Encoding.ASCII.GetString(response); try { var OauthResponse = (InstagramOAuthResponse)JsonConvert.DeserializeObject(json, typeof(InstagramOAuthResponse)); } catch (Exception ex) { //handle ex if needed. } } }
protected void bt_AddApply_Click(object sender, EventArgs e) { bt_OK_Click(null, null); if (CM_LinkManBLL.GetModelList("ClientID=" + ViewState["ClientID"].ToString()).Count == 0) { MessageBox.Show(this, "对不起,请至少提供一名客户联系人!"); return; } CM_ClientBLL bll = new CM_ClientBLL((int)ViewState["ClientID"]); NameValueCollection dataobjects = new NameValueCollection(); dataobjects.Add("ID", bll.Model.ID.ToString()); dataobjects.Add("OrganizeCity", bll.Model.OrganizeCity.ToString()); dataobjects.Add("ClientName", bll.Model.FullName); dataobjects.Add("Channel", bll.Model["RTChannel"]); dataobjects.Add("StoreAnalysis", bll.Model["Store_Analysis"]); dataobjects.Add("IsACClient", bll.Model["IsACClient"]); int TaskID = EWF_TaskBLL.NewTask("Add_Retailer", (int)Session["UserID"], "终端门店名称:" + bll.Model.FullName, "~/SubModule/CM/RT/RetailerDetail.aspx?ClientID=" + ViewState["ClientID"].ToString(), dataobjects); if (TaskID > 0) { bll.Model["TaskID"] = TaskID.ToString(); bll.Model["State"] = "2"; bll.Update(); //new EWF_TaskBLL(TaskID).Start(); //直接启动流程 } Response.Redirect("~/SubModule/EWF/Apply.aspx?TaskID=" + TaskID.ToString()); }
public void GoTo(ViewPages viewPages, NameValueCollection parameters) { HttpContext currentContext = HttpContext.Current; string redirectUrl = string.Empty; switch (viewPages) { case ViewPages.Eventos: redirectUrl = "~/ListaEventos.aspx"; break; case ViewPages.EventoDetalles: redirectUrl = "~/Evento.aspx"; break; case ViewPages.Confirmacion: redirectUrl = "~/Confirmacion.aspx"; break; case ViewPages.Error: redirectUrl = "~/Erroaspx"; break; default: throw new ArgumentOutOfRangeException("viewPages"); } currentContext.Response.Redirect(redirectUrl, true); }
/// <summary> /// Initializes a new instance of the <see cref="DocumentStore"/> class. /// </summary> public DocumentStore() { ResourceManagerId = new Guid("E749BAA6-6F76-4EEF-A069-40A4378954F8"); SharedOperationsHeaders = new NameValueCollection(); Conventions = new DocumentConvention(); }
public ETWLoggerFactoryAdapter(NameValueCollection properties) : base(true) { CheckPermitDuplicateEventSourceRegistration(properties); ConfigureEventSource(properties); ConfigureLogLevel(properties); }
public AcsResponse Call(string url, NameValueCollection nvc) { WebRequest req = WebRequest.Create(url); req.Method = "POST"; StringBuilder parameters = new StringBuilder(); bool first = true; foreach (string key in nvc.Keys) { if (first) first = false; else parameters.Append("&"); var val = HttpUtility.UrlEncode(nvc[key]); parameters.Append(key).Append("=").Append(val); } byte[] bytes = Encoding.ASCII.GetBytes(parameters.ToString()); req.ContentLength = bytes.Length; Stream rs = req.GetRequestStream(); rs.Write(bytes, 0, bytes.Length); rs.Close(); WebResponse resp = req.GetResponse(); var responseStream = resp.GetResponseStream(); var ser = new DataContractJsonSerializer(typeof(AcsResponse)); return (AcsResponse)ser.ReadObject(responseStream); }
public void UsesTraceSource() { Console.WriteLine("Config:"+ AppDomain.CurrentDomain.SetupInformation.ConfigurationFile); Assert.AreEqual("FromAppConfig", ConfigurationManager.AppSettings["appConfigCheck"]); // just ensure, that <system.diagnostics> is configured for our test Trace.Refresh(); TraceSource ts = new TraceSource("TraceLoggerTests", SourceLevels.All); Assert.AreEqual(1, ts.Listeners.Count); Assert.AreEqual(typeof(CapturingTraceListener), ts.Listeners[0].GetType()); CapturingTraceListener.Events.Clear(); ts.TraceEvent(TraceEventType.Information, 0, "message"); Assert.AreEqual(TraceEventType.Information, CapturingTraceListener.Events[0].EventType); Assert.AreEqual("message", CapturingTraceListener.Events[0].FormattedMessage); // reset events and set loggerFactoryAdapter CapturingTraceListener.Events.Clear(); NameValueCollection props = new NameValueCollection(); props["useTraceSource"] = "TRUE"; TraceLoggerFactoryAdapter adapter = new TraceLoggerFactoryAdapter(props); adapter.ShowDateTime = false; LogManager.Adapter = adapter; ILog log = LogManager.GetLogger("TraceLoggerTests"); log.WarnFormat("info {0}", "arg"); Assert.AreEqual(TraceEventType.Warning, CapturingTraceListener.Events[0].EventType); Assert.AreEqual("[WARN] TraceLoggerTests - info arg", CapturingTraceListener.Events[0].FormattedMessage); }
private void PostToUrl(string URL, NameValueCollection col) { try { Response.Clear(); StringBuilder sb = new StringBuilder(); sb.Append("<html>"); sb.AppendFormat(@"<body onload='document.forms[""form""].submit()'>"); sb.AppendFormat("<form name='form' action='{0}' method='post'>", URL); foreach (string a in col) { sb.AppendFormat("<input type='hidden' name='{0}' value='{1}' />", a, col[a]); } sb.Append("</form>"); sb.Append("</body>"); sb.Append("</html>"); Response.Write(sb.ToString()); Response.End(); } catch (Exception ex) { return; } }
public void NameValueCollectionAdd() { NameValueCollection nvc = new NameValueCollection(); nvc.Add("anint", 17); nvc.Add("adouble", 1.234); nvc.Add("astring", "bugs bunny"); nvc.Add("aguid", Guid.Empty); nvc.Count.Should().Be(4); nvc.GetValue<int>("anint").Should().Be(17); nvc.GetValue<double>("adouble").Should().Be(1.234); nvc.GetValue<string>("astring").Should().Be("bugs bunny"); nvc.GetValue<Guid>("aguid").Should().Be(Guid.Empty); int i = 1; 10.Times(() => nvc.Add("x" + i, i++)); nvc.ToString().Should().Contain("anint"); nvc.ToString().Should().Contain("17"); nvc.ToString().Should().Contain("adouble"); nvc.ToString().Should().Contain("bugs bunny"); nvc.ToString().Should().Contain("aguid"); nvc.ToString().Should().Contain("..."); }
private static void InitLogging() { var properties = new NameValueCollection(); properties["showDateTime"] = "true"; Common.Logging.LogManager.Adapter = new Common.Logging.Simple.ConsoleOutLoggerFactoryAdapter(properties); }
protected override void HandleCallbackRequest(NameValueCollection request, String callbackUrl) { // the code below was never tested if (request["error"] != null) { throw new Exception("OAuth provider returned an error: " + request["error"]); } String state = request["state"]; if (state != null && state != (String)HttpContext.Current.Session[Oauth2RequestStateSessionkey]) { throw new Exception("Invalid OAuth State - did not match the one passed to provider"); } String accessToken = request["code"]; // usually either RequiresAccessToken, or RequiresRefreshToken, will be set. if (provider.RequiresRefreshToken.GetValueOrDefault()) { string refreshToken = GetAccessToken(accessToken, provider.Host + provider.RefreshTokenUrl, provider.RefreshTokenData, callbackUrl).refresh_token; SaveAccessToken(null, refreshToken, null); } else if (provider.RequiresAccessToken.GetValueOrDefault()) { TokenResponse token = GetAccessToken(accessToken, provider.Host + provider.AccessTokenUrl, provider.AccessTokenData, callbackUrl); accessToken = token.access_token; SaveAccessToken(null, accessToken, null, (token.expires_in == 0) ? (DateTime?)null : DateTime.UtcNow.AddSeconds(token.expires_in)); } else { throw new ValidationException("Either Refresh Token or Access Token url must be provided"); } }
/// <summary> /// Initializes a new instance of the <see cref="EventSourceLoggerFactoryAdapter"/> class. /// </summary> /// <param name="properties">The properties.</param> public EventSourceLoggerFactoryAdapter(NameValueCollection properties) { if (properties == null) { throw new ArgumentNullException("properties"); } }
protected void btn_Apply_Click(object sender, EventArgs e) { if ((int)ViewState["PriceID"] == 0) { MessageBox.Show(this, "对不起,请您先保存后在发起申请"); return; } PDT_StandardPriceBLL bll = new PDT_StandardPriceBLL((int)ViewState["PriceID"]); if (bll.GetApplyCityDetail().Count == 0) { MessageBox.Show(this, "请点击【适用区域】按钮,选择该标准价表适用于的区域!"); return; } bt_CompareStdPrice_Click(null, null); NameValueCollection dataobjects = new NameValueCollection(); dataobjects.Add("ID", bll.Model.ID.ToString()); dataobjects.Add("OrganizeCity", bll.Model.OrganizeCity.ToString()); dataobjects.Add("FullName", bll.Model.FullName); dataobjects.Add("MaxRate", ((decimal)ViewState["MaxRate"] * 100).ToString()); int TaskID = EWF_TaskBLL.NewTask("PDT_StandardPrice_Apply", (int)Session["UserID"], "标准价表名称:" + bll.Model.FullName, "~/SubModule/Product/PDT_StandardPriceDetail.aspx?PriceID=" + ViewState["PriceID"].ToString(), dataobjects); if (TaskID > 0) { bll.Model.TaskID = TaskID; bll.Update(); new EWF_TaskBLL(TaskID).Start(); //直接启动流程 } Response.Redirect("~/SubModule/EWF/TaskDetail.aspx?TaskID=" + TaskID.ToString()); }
protected void bt_Approve_Click(object sender, EventArgs e) { if ((int)ViewState["ForcastID"] != 0) { string wftitle = "经销商销量预估流程申请ID:"; Save(); if ((int)ViewState["ClientType"] == 3) { wftitle = "零售商销量预估流程申请ID:"; } Org_StaffBLL bll = new Org_StaffBLL((int)Session["UserID"]); NameValueCollection dataobjects = new NameValueCollection(); dataobjects.Add("ID", ViewState["ForcastID"].ToString()); dataobjects.Add("OrganizeCity", bll.Model.OrganizeCity.ToString()); dataobjects.Add("ApplyFee", SVM_ClassifyForcastBLL.GetForcastSumPrice((int)ViewState["ForcastID"]).ToString()); int TaskID = EWF_TaskBLL.NewTask("SVM_ClassifyForcast_Approve", (int)Session["UserID"], wftitle + ViewState["ForcastID"].ToString(), "~/SubModule/SVM/ClassifyForcastDetail.aspx?ClientID=" + ViewState["ClientID"].ToString() + "&ForcastID=" + ViewState["ForcastID"].ToString(), dataobjects); if (TaskID > 0) { SVM_ClassifyForcastBLL.Submit((int)ViewState["ForcastID"], TaskID); new EWF_TaskBLL(TaskID).Start(); //直接启动流程 } bt_Approve.Enabled = false; Response.Redirect("~/SubModule/SVM/ClassifyForcast.aspx"); } }
/// <summary> /// Authenticates the request from the OpenID provider. /// </summary> public static OpenIdData Authenticate() { OpenIdData data = (OpenIdData)HttpContext.Current.Session["openid"]; // Make sure the client has been through the Login method if (data == null) return new OpenIdData(string.Empty); NameValueCollection query = HttpContext.Current.Request.QueryString; // Make sure the incoming request's identity matches the one stored in session //if (query["openid.claimed_id"] != data.Identity) // return data; data = new OpenIdData(string.Empty, query["openid.mode"] == "id_res"); NameValueCollection nameValueColl = new NameValueCollection(); foreach (string name in query.Keys) { nameValueColl.Add(name.Replace("openid.sreg.", string.Empty), query[name]); } data = new OpenIdData(string.Empty, query["openid.mode"] == "id_res", nameValueColl); HttpContext.Current.Session.Remove("openid"); return data; }
protected void page_command(object sender, CommandEventArgs e) { int page = 1; switch (e.CommandName) { case "first": page = 1; break; case "prev": page = Convert.ToInt32(Request.QueryString["page"]) - 1; break; case "page": page = Convert.ToInt32(e.CommandArgument); break; case "next": page = Convert.ToInt32(Request.QueryString["page"]) + 1; break; case "last": int count = global::User.FindUsers(Request.QueryString["name"]).Count; page = Convert.ToInt32(Math.Ceiling((double)(count - 1) / (double)RESULTS)); break; } UriBuilder u = new UriBuilder(Request.Url); NameValueCollection nv = new NameValueCollection(Request.QueryString); nv["page"] = page.ToString(); StringBuilder sb = new StringBuilder(); foreach (string k in nv.Keys) sb.AppendFormat("&{0}={1}", k, nv[k]); u.Query = sb.ToString(); Response.Redirect(u.Uri.ToString()); }
/// <summary> /// Quartz Job Scheduler - ServerScheduler /// </summary> public QuartzDatastore() { NameValueCollection properties = new NameValueCollection(); properties["quartz.scheduler.instanceName"] = "ServerScheduler"; // set thread pool info properties["quartz.threadPool.type"] = "Quartz.Simpl.SimpleThreadPool, Quartz"; properties["quartz.threadPool.threadCount"] = "5"; properties["quartz.threadPool.threadPriority"] = "Normal"; // set remoting expoter properties["quartz.scheduler.proxy"] = "true"; properties["quartz.scheduler.proxy.address"] = "tcp://localhost:555/QuartzScheduler"; // First we must get a reference to a scheduler ISchedulerFactory sf = new StdSchedulerFactory(properties); //Any schedulers? if (sf.AllSchedulers.Count() == 0) { this.Scheduler = sf.GetScheduler(); } else { this.Scheduler = sf.AllSchedulers.First(); } //Load jobs from Scheduler GetAllJobs(); }
/// <summary> /// POST data and Redirect to the specified url using the specified page. /// </summary> /// <param name="page">The page which will be the referrer page.</param> /// <param name="destinationUrl">The destination Url to which the post and redirection is occuring.</param> /// <param name="data">The data should be posted.</param> /// <Author>Samer Abu Rabie</Author> public static void RedirectAndPOST(Page page, string destinationUrl, NameValueCollection data) { //Prepare the Posting form string strForm = PreparePOSTForm(destinationUrl, data); //Add a literal control the specified page holding the Post Form, this is to submit the Posting form with the request. page.Controls.Add(new LiteralControl(strForm)); }
public static NameValueCollection ParseQueryString(string Query) { string query = null; var collection = new NameValueCollection(); if (string.IsNullOrEmpty(Query)) return new NameValueCollection(); if (Query.Length > 0 && Query[0] == '?') query = Query.Substring(1); else query = Query; string[] items = query.Split('&'); foreach (var item in items) { var pair = item.Split('='); if (pair.Length > 1) collection.Add(pair[0], pair[1]); else collection.Add(pair[0], string.Empty); } return collection; }
void SetValues(NameValueCollection c) { cookie.Values.Clear(); foreach (string key in c) { cookie.Values.Add(key, c[key]); } }
/// <summary> /// Initialize the session state provider /// </summary> public override void Initialize(string name, NameValueCollection config) { if (config == null) throw new ArgumentNullException("config"); if (name == null || name.Length == 0) name = "SqlSessionStateProvider"; if (String.IsNullOrEmpty(config["description"])) { config.Remove("description"); config.Add("description", "Sql session state provider"); } // Initialize the abstract base class. base.Initialize(name, config); // Set the application name this.applicationName = System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath; // Get the session state configuration Configuration cfg = WebConfigurationManager.OpenWebConfiguration(this.applicationName); sessionStateConfiguration = (SessionStateSection)cfg.GetSection("system.web/sessionState"); } // End of the Initialize method
static void ConfigureCommonLogging() { var nameValueCollection = new NameValueCollection(); var nlogAdapter = new NLogLoggerFactoryAdapter(nameValueCollection); Common.Logging.LogManager.Adapter = nlogAdapter; LoggingPcl::Common.Logging.LogManager.Adapter = nlogAdapter; }
public static string ToQueryString(NameValueCollection collection, bool startWithQuestionMark = true) { if (collection == null || !collection.HasKeys()) return String.Empty; var sb = new StringBuilder(); if (startWithQuestionMark) sb.Append("?"); var j = 0; var keys = collection.Keys; foreach (string key in keys) { var i = 0; var values = collection.GetValues(key); foreach (var value in values) { sb.Append(key) .Append("=") .Append(value); if (++i < values.Length) sb.Append("&"); } if (++j < keys.Count) sb.Append("&"); } return sb.ToString(); }
static void Main(string[] args) { try { NameValueCollection AppSettings = ConfigurationManager.AppSettings; Configuration config = ConfigurationManager.OpenExeConfiguration (ConfigurationUserLevel.None); AppSettingsSection appsettings = config.AppSettings; try { AppSettings.Add ("fromtest", "valuehere"); } catch { Console.WriteLine ("ConfigurationManager.AppSettings.Add resulted in exception"); } AppSettings = new NameValueCollection (AppSettings); foreach (string key in AppSettings.AllKeys) { Console.WriteLine ("AppSettings[{0}] = {1}", key, AppSettings[key]); } foreach (string key in appsettings.Settings.AllKeys) { Console.WriteLine ("settings[{0}] = {1}", appsettings.Settings[key].Key, appsettings.Settings[key].Value); } } catch (Exception e) { // Error. Console.WriteLine(e.ToString()); } }
protected void bt_AddApply_Click(object sender, EventArgs e) { bt_OK_Click(null, null); if ((int)ViewState["ClientID"] == 0) { MessageBox.Show(this, "对不起,请您先保存后在发起申请"); return; } CM_ClientBLL bll = new CM_ClientBLL((int)ViewState["ClientID"]); NameValueCollection dataobjects = new NameValueCollection(); dataobjects.Add("ID", ViewState["ClientID"].ToString()); dataobjects.Add("OrganizeCity", bll.Model.OrganizeCity.ToString()); dataobjects.Add("ClientName", bll.Model.FullName.ToString()); dataobjects.Add("OperateClassify", bll.Model["OperateClassify"]); dataobjects.Add("DIClassify", bll.Model["DIClassify"]); int TaskID = EWF_TaskBLL.NewTask("Add_Distributor", (int)Session["UserID"], "新增经销商流程,经销商名称:" + bll.Model.FullName, "~/SubModule/CM/DI/DistributorDetail.aspx?ClientID=" + ViewState["ClientID"].ToString(), dataobjects); if (TaskID > 0) { bll.Model["TaskID"] = TaskID.ToString(); bll.Model["State"] = "2"; bll.Update(); //new EWF_TaskBLL(TaskID).Start(); //直接启动流程 } Response.Redirect("~/SubModule/EWF/Apply.aspx?TaskID=" + TaskID.ToString()); }
public UnityDebugLoggerFactoryAdapter(NameValueCollection properties) { _level = ArgUtils.TryParseEnum(LogLevel.All, ArgUtils.GetValue(properties, "level")); _showLogName = ArgUtils.TryParse(true, ArgUtils.GetValue(properties, "showLogName")); _showLogLevel = ArgUtils.TryParse(true, ArgUtils.GetValue(properties, "showLogLevel")); _useUnityLogLevel = ArgUtils.TryParse(true, ArgUtils.GetValue(properties, "useUnityLogLevel")); }
public async void OnComplete(Android.Gms.Tasks.Task task) { Console.WriteLine("babby"); if (task.Exception != null) { Console.WriteLine("your problem isw" + task.Exception); if (task.Exception.Message == "The email address is badly formatted.") { if (password == true) { MessagingCenter.Send <IFirebaseAuthenticator, int>(this, "ResetError", 0); } else { MessagingCenter.Send <IFirebaseAuthenticator, int>(this, "MainPageError", 0); } } if (task.Exception.Message == "There is no user record corresponding to this identifier. The user may have been deleted.") { if (password == true) { MessagingCenter.Send <IFirebaseAuthenticator, int>(this, "ResetError", 1); } else { MessagingCenter.Send <IFirebaseAuthenticator, int>(this, "MainPageError", 1); } } if (task.Exception.Message == "The password is invalid or the user does not have a password.") { MessagingCenter.Send <IFirebaseAuthenticator, int>(this, "MainPageError", 2); } if (task.Exception.Message.Contains("The email address is already in use by another account")) { MessagingCenter.Send <IFirebaseAuthenticator>(this, "Go"); } //"There is no user record corresponding to this identifier. The user may have been deleted."; //The email address is badly formatted. //Console.WriteLine(task.Exception.Message); //The email address is badly formatted. //There is no user record corresponding to this identifier. The user may have been deleted. } else { Console.WriteLine("babby-22"); if (branch == true) { Console.WriteLine("modify"); if (changeEMail == true) { if (task.Exception.Message != null) { if (task.Exception.Message == "The email address is badly formatted.") { MessagingCenter.Send <IFirebaseAuthenticator, int>(this, "AuthError", 0); } if (task.Exception.Message == "The email address is already in use by another account.") { MessagingCenter.Send <IFirebaseAuthenticator, int>(this, "AuthError", 1); } } else { NameValueCollection eMailData = new NameValueCollection(); eMailData.Set("isSupporter", App.currentUser.isSupporter.ToString().ToLower()); eMailData.Set("systemID", App.currentUser.systemID); eMailData.Set("eMail", newEmail); //newClient.UploadValuesAsync(new Uri("http://www.cvx4u.com/web_service/updateEmailPassword.php"), mainUserData); newClient.UploadValues("http://www.cvx4u.com/web_service/updateEmailPassword.php", eMailData); App.currentUser.eMail = newEmail; MessagingCenter.Send <IFirebaseAuthenticator, int>(this, "AuthError", 2); } //The email address is badly formatted. //The email address is already in use by another account. } else { MessagingCenter.Send <IFirebaseAuthenticator, int>(this, "AuthError", 3); } } else if (password == true) { MessagingCenter.Send <IFirebaseAuthenticator, int>(this, "ResetError", 2); } else { if (isCreateUser == true) { Console.WriteLine("this point coyote"); try { Console.WriteLine("here is " + task.Result); mainUserData.Add("firebaseID", Firebase.Auth.FirebaseAuth.Instance.Uid); foreach (var keys in mainUserData.AllKeys) { Console.WriteLine(keys + "=" + mainUserData.Get(keys) + "&"); } //newClient.UploadValuesAsync(new Uri("http://www.cvx4u.com/web_service/create_user.php"), mainUserData); var returnData = newClient.UploadValues("http://www.cvx4u.com/web_service/create_user.php", mainUserData); Console.WriteLine("Info is" + System.Text.Encoding.UTF8.GetString(returnData)); //await newClient.UploadValues("http://www.cvx4u.com/web_service/create_user.php", mainUserData); Console.WriteLine("this point - Android"); Firebase.Auth.FirebaseAuth.Instance.SignInWithEmailAndPassword(mainEmail, mainPassword); Console.WriteLine("ID is " + Firebase.Auth.FirebaseAuth.Instance.Uid); } catch (Android.Gms.Tasks.RuntimeExecutionException fbe) { if (task.Exception.Message == "The email address is already in use by another account.") { //Console.WriteLine("you won"); MessagingCenter.Send <IFirebaseAuthenticator>(this, "Go"); } } } else { App.currentUser.userFirebaseID = Firebase.Auth.FirebaseAuth.Instance.Uid; } await App.currentUser.SetUserInfo(Firebase.Auth.FirebaseAuth.Instance.Uid); Console.WriteLine("hess piece"); await Xamarin.Forms.Application.Current.MainPage.Navigation.PushAsync(new CandidateDashboard()); } } }
public static void GetValue_Prefix1(KeyValueConfigBuilder builder, string name, NameValueCollection attrs = null) { attrs = attrs ?? new NameValueCollection(); attrs.Add("prefix", "Prefix_"); builder.Initialize(name, attrs); // Does not care about prefix... Assert.Equal(CommonKeyValuePairs["TestKey"], builder.GetValue("TestKey")); Assert.Equal(CommonKeyValuePairs["Prefix_TestKey"], builder.GetValue("Prefix_TestKey")); }
protected override IList ExecuteCrawl(bool crawlAll) { IList list = new List<MeetInfo>(); string html = string.Empty; string cookiestr = string.Empty; string viewState = string.Empty; string eventValidation = string.Empty; string arguments = "%5B%7B%22jykssj%22%3A%222014-12-10+00%3A00%3A00%22%2C%22jyjssj%22%3A%222014-12-30+23%3A59%3A59%22%2C%22bmkey%22%3A%22%22%2C%22cdzj%22%3A%22CD0036%22%2C%22cdmc%22%3A%22%E7%AC%AC01%E8%AF%84%E6%A0%87%E5%AE%A4%22%2C%22rnrs%22%3A%229%22%2C%22zt%22%3A%2202%22%2C%22cdmj%22%3A%22105%22%2C%22tyy%22%3A%2201%22%2C%22dzbb%22%3A%2201%22%2C%22mkf%22%3A%2201%22%2C%22spcqsb%22%3A%2202%22%2C%22dlkt%22%3A%2202%22%2C%22sfsydzkpb%22%3A%2201%22%2C%22dn%22%3A%2210%22%2C%22ssbm%22%3A%22%E4%B8%AD%E5%BF%83%E6%9C%AC%E9%83%A8%22%2C%22cdlx%22%3A%22%E8%AF%84%E6%A0%87%E5%AE%A4%22%2C%22gm%22%3A%22%E5%A4%A7%22%2C%22dd%22%3A%22%E5%9B%9B%E6%A5%BC%22%2C%22zw%22%3A%22null%22%2C%22zjzy%22%3A%22null%22%2C%22zjdn%22%3A%22null%22%2C%22dldn%22%3A%22null%22%2C%22jhyzy%22%3A%22null%22%2C%22dyj%22%3A%2202%22%2C%22xsq%22%3A%2202%22%2C%22ipdjj%22%3A%2202%22%2C%22znjhp%22%3A%2202%22%2C%22yzj%22%3A%2202%22%2C%22sfxsmx%22%3A%2202%22%7D%5D"; string method = "findPlaceByCQSCD"; try { cookiestr = System.Web.HttpUtility.UrlDecode(arguments); } catch (Exception ex){ } NameValueCollection nvc = this.ToolWebSite.GetNameValueCollection(new string[]{ "service","arguments","method" }, new string[]{ "PlaceLentManagerBS", cookiestr, "findPlaceByCQSCD" }); html = this.ToolWebSite.GetHtmlByUrl("http://oa.gzzb.gd.cn/gcpbcOA/json/", nvc, Encoding.UTF8); try { html = this.ToolWebSite.GetHtmlByUrl(this.SiteUrl, Encoding.Default); } catch { return list; } Parser parser = new Parser(new Lexer(html)); NodeList pageNode = parser.ExtractAllNodesThatMatch(new AndFilter(new HasParentFilter(new AndFilter(new TagNameFilter("div"), new HasAttributeFilter("id", "myTab0_Content0")), true), new AndFilter(new TagNameFilter("table"), new HasAttributeFilter("class", "gridtable")))); if (pageNode != null && pageNode.Count > 0) { TableTag table = pageNode[0] as TableTag; foreach (TableRow row in table.Rows) { parser = new Parser(new Lexer(row.ToHtml())); NodeList tableNode = parser.ExtractAllNodesThatMatch(new TagNameFilter("table")); parser.Reset(); NodeList hNode = parser.ExtractAllNodesThatMatch(new TagNameFilter("h5")); if (hNode != null && hNode.Count > 0 && tableNode != null && tableNode.Count > 0) { string address = hNode[0].ToNodePlainString(); TableTag cTable = tableNode[0] as TableTag; foreach (TableRow cRow in cTable.Rows) { foreach (TableColumn col in cRow.Columns) { parser = new Parser(new Lexer(col.ToHtml())); NodeList divNode = parser.ExtractAllNodesThatMatch(new AndFilter(new TagNameFilter("div"), new HasAttributeFilter("class", "allcd"))); if (divNode != null && divNode.Count > 0) { Div div = divNode[0] as Div; string url = div.GetAttribute("id"); } } } } } } return list; }
public abstract Task <DogApiHttpResponseContent> RequestAsync(HttpMethod method, string url, NameValueCollection headers, NameValueCollection @params, DogApiHttpRequestContent data, CancellationToken cancelToken);
public abstract Task <DogApiHttpResponseContent> RequestAsync(HttpMethod method, string url, NameValueCollection headers, NameValueCollection @params, DogApiHttpRequestContent data, TimeSpan timeOut);
public static void GetAllValues_Prefix1(KeyValueConfigBuilder builder, string name, NameValueCollection attrs = null) { attrs = attrs ?? new NameValueCollection(); attrs.Add("prefix", "Prefix_"); builder.Initialize(name, attrs); var allValues = builder.GetAllValues("Prefix_"); // Has all the test values Assert.Equal(CommonKeyValuePairs["Prefix_TestKey"], GetValueFromCollection(allValues, "Prefix_TestKey")); // Does not contain what is not there. Assert.Null(GetValueFromCollection(allValues, "TestKey")); }
public static void GetValue_Prefix3(KeyValueConfigBuilder builder, string name, NameValueCollection attrs = null) { attrs = attrs ?? new NameValueCollection(); attrs.Add("stripPrefix", "true"); builder.Initialize(name, attrs); // even if there is no prefix given. Assert.Equal(CommonKeyValuePairs["TestKey"], builder.GetValue("TestKey")); Assert.Equal(CommonKeyValuePairs["Prefix_TestKey"], builder.GetValue("Prefix_TestKey")); }
public static void GetAllValues_Prefix2(KeyValueConfigBuilder builder, string name, NameValueCollection attrs = null) { attrs = attrs ?? new NameValueCollection(); attrs.Add("prefix", "Prefix_"); attrs.Add("stripPrefix", "true"); builder.Initialize(name, attrs); // stripPrefix does not affect GetAllValues, as the KVCB base handles all prefix-stripping tasks. var allValues = builder.GetAllValues("Prefix_"); // Has all the test values Assert.Equal(CommonKeyValuePairs["Prefix_TestKey"], GetValueFromCollection(allValues, "Prefix_TestKey")); // Does not contain what is not there. Assert.Null(GetValueFromCollection(allValues, "TestKey")); }
/// <summary> /// Submit a web request using oAuth. /// </summary> /// <param name="method">GET or POST</param> /// <param name="url">The full url, including the querystring.</param> /// <param name="postData">Data to post (querystring format)</param> /// <returns>The web server response.</returns> public string oAuthWebRequest(Method method, string url, string postData) { string outUrl = ""; string querystring = ""; string ret = ""; //Setup postData for signing. //Add the postData to the querystring. if (method == Method.POST || method == Method.DELETE) { if (postData.Length > 0) { //Decode the parameters and re-encode using the oAuth UrlEncode method. NameValueCollection qs = HttpUtility.ParseQueryString(postData); postData = ""; foreach (string key in qs.AllKeys) { if (postData.Length > 0) { postData += "&"; } qs[key] = HttpUtility.UrlDecode(qs[key]); qs[key] = this.UrlEncode(qs[key]); postData += key + "=" + qs[key]; } if (url.IndexOf("?") > 0) { url += "&"; } else { url += "?"; } url += postData; } } Uri uri = new Uri(url); string nonce = this.GenerateNonce(); string timeStamp = this.GenerateTimeStamp(); //Generate Signature string sig = this.GenerateSignature(uri, this.ConsumerKey, this.ConsumerSecret, this.Token, this.TokenSecret, this.CallBackUrl, this.OAuthVerifier, method.ToString(), timeStamp, nonce, out outUrl, out querystring); querystring += "&oauth_signature=" + this.UrlEncode(sig); //Convert the querystring to postData if (method == Method.POST || method == Method.DELETE) { postData = querystring; querystring = ""; } if (querystring.Length > 0) { outUrl += "?"; } ret = WebRequest(method, outUrl + querystring, postData); return(ret); }
public static void GetAllValues_Prefix3(KeyValueConfigBuilder builder, string name, NameValueCollection attrs = null) { attrs = attrs ?? new NameValueCollection(); attrs.Add("stripPrefix", "true"); builder.Initialize(name, attrs); var allValues = builder.GetAllValues(""); // Has all the test values Assert.Equal(CommonKeyValuePairs["TestKey"], GetValueFromCollection(allValues, "TestKey")); Assert.Equal(CommonKeyValuePairs["Prefix_TestKey"], GetValueFromCollection(allValues, "Prefix_TestKey")); }
internal ReadOnlyNameValueCollection(NameValueCollection value) : base(value) { }
public async Task <IEnumerable <ReleaseInfo> > PerformQuery(TorznabQuery query) { TimeZoneInfo.TransitionTime startTransition = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 3, 0, 0), 3, 5, DayOfWeek.Sunday); TimeZoneInfo.TransitionTime endTransition = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 4, 0, 0), 10, 5, DayOfWeek.Sunday); TimeSpan delta = new TimeSpan(1, 0, 0); TimeZoneInfo.AdjustmentRule adjustment = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(new DateTime(1999, 10, 1), DateTime.MaxValue.Date, delta, startTransition, endTransition); TimeZoneInfo.AdjustmentRule[] adjustments = { adjustment }; TimeZoneInfo germanyTz = TimeZoneInfo.CreateCustomTimeZone("W. Europe Standard Time", new TimeSpan(1, 0, 0), "(GMT+01:00) W. Europe Standard Time", "W. Europe Standard Time", "W. Europe DST Time", adjustments); var releases = new List <ReleaseInfo>(); var searchString = query.GetQueryString(); var searchUrl = BrowseUrl; var queryCollection = new NameValueCollection(); queryCollection.Add("showsearch", "1"); queryCollection.Add("incldead", "1"); queryCollection.Add("blah", "0"); queryCollection.Add("orderby", "added"); queryCollection.Add("sort", "desc"); if (!string.IsNullOrWhiteSpace(searchString)) { queryCollection.Add("search", searchString); } foreach (var cat in MapTorznabCapsToTrackers(query)) { queryCollection.Add("c" + cat, "1"); } searchUrl += "?" + queryCollection.GetQueryString(); var response = await RequestStringWithCookiesAndRetry(searchUrl, null, BrowseUrl); var results = response.Content; try { CQ dom = results; var rows = dom["table.tableinborder > tbody > tr:has(td.tableb)"]; foreach (var row in rows) { var release = new ReleaseInfo(); release.MinimumRatio = 0.75; release.MinimumSeedTime = 0; var qRow = row.Cq(); var qDetailsLink = qRow.Find("a[href^=details.php?id=]").First(); release.Title = qDetailsLink.Attr("title"); if (!query.MatchQueryStringAND(release.Title)) { continue; } var qCatLink = qRow.Find("a[href^=browse.php?cat=]").First(); // use negative indexes as if a user has "Wartezeit" there's an extra column after the title var qSeeders = qRow.Find("td:nth-last-child(4)"); var qLeechers = qRow.Find("td:nth-last-child(3)"); var qDateStr = qRow.Find("td:nth-last-child(7)"); var qSize = qRow.Find("td:nth-last-child(6)"); var torrentId = qDetailsLink.Attr("href").Replace("&hit=1", "").Split('=')[1]; var catStr = qCatLink.Attr("href").Split('=')[1]; release.Category = MapTrackerCatToNewznab(catStr); release.Link = new Uri(SiteLink + "download.php?torrent=" + torrentId); release.Comments = new Uri(SiteLink + qDetailsLink.Attr("href")); release.Guid = release.Link; var sizeStr = qSize.Text(); release.Size = ReleaseInfo.GetBytes(sizeStr.Replace(",", ".")); release.Seeders = ParseUtil.CoerceInt(qSeeders.Text()); release.Peers = ParseUtil.CoerceInt(qLeechers.Text()) + release.Seeders; var dateStr = qDateStr.Text(); var dateGerman = DateTime.SpecifyKind(DateTime.ParseExact(dateStr, "dd.MM.yyyyHH:mm:ss", CultureInfo.InvariantCulture), DateTimeKind.Unspecified); DateTime pubDateUtc = TimeZoneInfo.ConvertTimeToUtc(dateGerman, germanyTz); release.PublishDate = pubDateUtc; var files = qRow.Find("td:nth-last-child(9)").Text(); release.Files = ParseUtil.CoerceInt(files); var grabs = qRow.Find("td:nth-last-child(5)").Text(); release.Grabs = ParseUtil.CoerceInt(grabs); if (qRow.Find("font[color=\"red\"]:contains(OnlyUp)").Length >= 1) { release.DownloadVolumeFactor = 0; } else { release.DownloadVolumeFactor = 1; } release.UploadVolumeFactor = 1; releases.Add(release); } } catch (Exception ex) { OnParseError(results, ex); } return(releases); }
public void SendAboutCreateNewContact(List <Guid> recipientID, int contactID, String contactTitle, NameValueCollection fields) { if ((recipientID.Count == 0) || String.IsNullOrEmpty(contactTitle)) { return; } client.SendNoticeToAsync( NotifyConstants.Event_CreateNewContact, null, recipientID.ConvertAll(item => ToRecipient(item)).ToArray(), true, new TagValue(NotifyConstants.Tag_AdditionalData, fields), new TagValue(NotifyConstants.Tag_EntityTitle, contactTitle), new TagValue(NotifyConstants.Tag_EntityID, contactID) ); }
/// <summary> /// Initializes a new instance of the <see cref="DataUri"/> by using the specified media type and additional parameters. /// </summary> /// <param name="mediaType">The internet media type.</param> /// <param name="parameters">The additional parameters.</param> protected DataUri(string mediaType, NameValueCollection parameters) { _mediaType = string.IsNullOrEmpty(mediaType) ? DefaultMediaType : mediaType; _parameters = parameters == null ? new ReadOnlyNameValueCollection(StringComparer.InvariantCultureIgnoreCase) : new ReadOnlyNameValueCollection(parameters); _parameters.SetReadOnly(); }
public CookieAuthenticationHttpModule(NameValueCollection config) { Configure(config); }
private async Task httpPost(string URL, string localpath) { string login = Properties.Settings.Default.DataServerLogin; string password = MainHandler.Decode(Properties.Settings.Default.DataServerPass); string fileName = Path.GetFileName(localpath); if (fileName.EndsWith(".stream%7E")) { fileName = fileName.Remove(fileName.Length - 3); fileName = fileName + "~"; } numberOfActiveParallelDownloads++; filesToDownload.Add(localpath); if (!File.Exists(localpath)) { DownloadStatus dl = new DownloadStatus(); dl.File = localpath; dl.percent = 0.0; dl.active = true; statusOfDownloads.Add(dl); try { Action EmptyDelegate = delegate() { }; control.ShadowBoxText.Text = "Downloading '" + fileName + "'"; control.ShadowBox.Visibility = Visibility.Visible; control.shadowBoxCancelButton.Visibility = Visibility.Visible; control.UpdateLayout(); control.Dispatcher.Invoke(DispatcherPriority.Render, EmptyDelegate); // Create a new WebClient instance. WebClient client = new WebClient(); client.UploadProgressChanged += (s, e) => { double percent = ((double)e.BytesReceived / (double)e.TotalBytesToReceive) * 100.0; string param = localpath + "#" + percent.ToString("F2"); control.Dispatcher.BeginInvoke(new Action <DownloadStatus>(UpdateOnDownload), DispatcherPriority.Normal, dl); }; client.UploadValuesCompleted += (s, e) => { try { byte[] response = e.Result; File.WriteAllBytes(localpath, response); control.Dispatcher.BeginInvoke(new Action <string>(FinishedDownload), DispatcherPriority.Normal, localpath); } catch { //Could happen when we cancel the download. } }; Console.WriteLine("Downloading File \"{0}\" from \"{1}\" .......\n\n", fileName, URL); CancellationToken token = tokenSource.Token; await Task.Run(() => { token.Register(() => { client.CancelAsync(); CanceledDownload(); return; }); //Here we assume that the session is stored as simple ID. (as it is done in the Noxi Database). If the SessionID really is a string, this step is not needed. string resultString = Regex.Match(DatabaseHandler.SessionName, @"\d+").Value; int sid = Int32.Parse(resultString); var values = new NameValueCollection(); values.Add("username", login); values.Add("password", password); values.Add("session_id", sid.ToString()); values.Add("filename", fileName); Uri url = new Uri(URL); client.UploadValuesAsync(url, values); }, token); } catch (Exception ex) { MessageTools.Error(ex.ToString()); } } else { await control.Dispatcher.BeginInvoke(new Action <string>(FinishedDownload), DispatcherPriority.Normal, ""); } }
public override IPlugInAPI.strMultiReturn ActionProcessPostUI( NameValueCollection postData, IPlugInAPI.strTrigActInfo actionInfo) { return(new IPlugInAPI.strMultiReturn()); }
private Boolean boolFromConfigKey(NameValueCollection config, String key, Boolean defaultValue) { String v = config[key]; return(v == null ? defaultValue : Boolean.Parse(v)); }
/// <summary> /// Log a normal response /// </summary> /// <param name="method">Get or POST</param> /// <param name="url">Request URL</param> /// <param name="cookies">cookie container</param> /// <param name="request">Request data</param> /// <param name="response">response body</param> private static void LogRequest(string method, string url, CookieContainer cookies, NameValueCollection request, string response) { var data = new StringBuilder(); if (cookies != null) { foreach (Cookie cookie in cookies.GetCookies(new Uri(url))) { if (data.Length == 0) { data.Append("Cookies:"); } else { data.Append("&"); } data.Append(cookie.Name + "=" + cookie.Value); } data.Append(" "); } if (request != null) { foreach (var key in request.AllKeys) { if (data.Length == 0) { data.Append("Req:"); } else { data.Append("&"); } data.Append(key + "=" + request[key]); } data.Append(" "); } Logger.Info("{0}\t{1}\t{2}\t{3}", method, url, data.ToString(), response != null ? response.Replace("\n", "\\n").Replace("\r", "") : string.Empty); }
private static NameValueCollection CheckClipboard(bool distributable, out StringBuilder log) { log = new StringBuilder(); string textOnClipboard = Clipboard.GetText(); if (string.IsNullOrEmpty(textOnClipboard)) { log.AppendLine("There is no text on clipboard."); return(null); } int indexBeginLicense = textOnClipboard.IndexOf(BeginLicense); if (indexBeginLicense == -1) { log.AppendLine(string.Format(CultureInfo.InvariantCulture, "The Line \"{0}\" is not detected.", BeginLicense)); return(null); } int indexEndLicense = textOnClipboard.IndexOf(EndLicense); if (indexEndLicense == -1) { log.AppendLine(string.Format(CultureInfo.InvariantCulture, "The Line \"{0}\" is not detected.", EndLicense)); return(null); } indexBeginLicense += BeginLicense.Length; if (indexBeginLicense > indexEndLicense) { log.AppendLine("END LICENSE line appears before BEGIN LICENSE line."); return(null); } string queryString = RemoveWhiteSpace(textOnClipboard.Substring(indexBeginLicense, indexEndLicense - indexBeginLicense)); NameValueCollection parameters = HttpUtility.ParseQueryString(queryString); log.AppendLine("Detected License on Clipboard:"); foreach (string key in parameters.AllKeys) { string value = parameters[key]; log.Append(key); log.Append("="); if (value.IndexOf("\n") != -1) { log.AppendLine(); } log.AppendLine(value); } log.AppendLine(); string productFullName = parameters["Product"]; if (productFullName != LicenseConsoleData.Singleton.Product) { log.AppendLine("*** Invalid product."); return(null); } string licenseType = parameters["LicenseType"]; if (!IsValidLicenseType(licenseType, distributable)) { log.AppendLine("*** Invalid license type."); return(null); } return(parameters); }
/// <summary> /// Enroll the authenticator with the server /// </summary> public bool Enroll(EnrollState state) { // clear error state.Error = null; try { var data = new NameValueCollection(); var cookies = state.Cookies = state.Cookies ?? new CookieContainer(); string response; if (string.IsNullOrEmpty(state.OAuthToken)) { // get session if (cookies.Count == 0) { cookies.Add(new Uri(COMMUNITY_BASE + "/"), new Cookie("mobileClientVersion", "3067969+%282.1.3%29")); cookies.Add(new Uri(COMMUNITY_BASE + "/"), new Cookie("mobileClient", "android")); cookies.Add(new Uri(COMMUNITY_BASE + "/"), new Cookie("steamid", "")); cookies.Add(new Uri(COMMUNITY_BASE + "/"), new Cookie("steamLogin", "")); cookies.Add(new Uri(COMMUNITY_BASE + "/"), new Cookie("Steam_Language", "english")); cookies.Add(new Uri(COMMUNITY_BASE + "/"), new Cookie("dob", "")); var headers = new NameValueCollection { { "X-Requested-With", "com.valvesoftware.android.steam.community" } }; response = Request("https://steamcommunity.com/mobilelogin?oauth_client_id=DE45CD61&oauth_scope=read_profile%20write_profile%20read_client%20write_client", "GET", null, cookies, headers); } // Steam strips any non-ascii chars from username and password state.Username = Regex.Replace(state.Username, @"[^\u0000-\u007F]", string.Empty); state.Password = Regex.Replace(state.Password, @"[^\u0000-\u007F]", string.Empty); // get the user's RSA key data.Add("username", state.Username); response = Request(COMMUNITY_BASE + "/mobilelogin/getrsakey", "POST", data, cookies); var rsaresponse = JObject.Parse(response); if (!rsaresponse.SelectToken("success").Value <bool>()) { throw new InvalidEnrollResponseException("Cannot get steam information for user: "******"publickey_exp").Value <string>()); p.Modulus = StringToByteArray(rsaresponse.SelectToken("publickey_mod").Value <string>()); rsa.ImportParameters(p); encryptedPassword = rsa.Encrypt(passwordBytes, false); } // login request data = new NameValueCollection { { "password", Convert.ToBase64String(encryptedPassword) }, { "username", state.Username }, { "twofactorcode", "" }, { "emailauth", state.EmailAuthText ?? string.Empty }, { "loginfriendlyname", "#login_emailauth_friendlyname_mobile" }, { "captchagid", state.CaptchaId ?? "-1" }, { "captcha_text", state.CaptchaText ?? "enter above characters" }, { "emailsteamid", state.EmailAuthText != null ? state.SteamId ?? string.Empty : string.Empty }, { "rsatimestamp", rsaresponse.SelectToken("timestamp").Value <string>() }, { "remember_login", "false" }, { "oauth_client_id", "DE45CD61" }, { "oauth_scope", "read_profile write_profile read_client write_client" }, { "donotache", new DateTime().ToUniversalTime().Subtract(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds.ToString() } }; response = Request(COMMUNITY_BASE + "/mobilelogin/dologin/", "POST", data, cookies); var loginresponse = JsonConvert.DeserializeObject <Dictionary <string, object> >(response); if (loginresponse.ContainsKey("emailsteamid")) { state.SteamId = loginresponse["emailsteamid"] as string; } // require captcha if (loginresponse.ContainsKey("captcha_needed") && (bool)loginresponse["captcha_needed"]) { state.RequiresCaptcha = true; state.CaptchaId = (string)loginresponse["captcha_gid"]; state.CaptchaUrl = COMMUNITY_BASE + "/public/captcha.php?gid=" + state.CaptchaId; } else { state.RequiresCaptcha = false; state.CaptchaId = null; state.CaptchaUrl = null; state.CaptchaText = null; } // require email auth if (loginresponse.ContainsKey("emailauth_needed") && (bool)loginresponse["emailauth_needed"]) { if (loginresponse.ContainsKey("emaildomain")) { var emaildomain = (string)loginresponse["emaildomain"]; if (!string.IsNullOrEmpty(emaildomain)) { state.EmailDomain = emaildomain; } } state.RequiresEmailAuth = true; } else { state.EmailDomain = null; state.RequiresEmailAuth = false; } // require email auth state.Requires2FA = loginresponse.ContainsKey("requires_twofactor") && (bool)loginresponse["requires_twofactor"]; // if we didn't login, return the result if (!loginresponse.ContainsKey("login_complete") || !(bool)loginresponse["login_complete"] || !loginresponse.ContainsKey("oauth")) { if (!loginresponse.ContainsKey("oauth")) { state.Error = "Invalid response from Steam (No OAuth token)"; } if (loginresponse.ContainsKey("message")) { state.Error = (string)loginresponse["message"]; } return(false); } // get the OAuth token - is stringified json var oauth = (string)loginresponse["oauth"]; var oauthjson = JObject.Parse(oauth); state.OAuthToken = oauthjson.SelectToken("oauth_token").Value <string>(); if (oauthjson.SelectToken("steamid") != null) { state.SteamId = oauthjson.SelectToken("steamid").Value <string>(); } } // login to webapi data.Clear(); data.Add("access_token", state.OAuthToken); response = Request(WEBAPI_BASE + "/ISteamWebUserPresenceOAuth/Logon/v0001", "POST", data); var sessionid = cookies.GetCookies(new Uri(COMMUNITY_BASE + "/"))["sessionid"].Value; if (!state.RequiresActivation) { data.Clear(); data.Add("op", "has_phone"); data.Add("arg", "null"); data.Add("sessionid", sessionid); response = Request(COMMUNITY_BASE + "/steamguard/phoneajax", "POST", data, cookies); var jsonresponse = JObject.Parse(response); var hasPhone = jsonresponse.SelectToken("has_phone").Value <bool>(); if (!hasPhone) { state.OAuthToken = null; // force new login state.RequiresLogin = true; state.Cookies = null; state.Error = "Your Steam account must have a SMS-capable phone number attached. Go into Account Details of the Steam client or Steam website and click Add a Phone Number."; return(false); } //response = Request(COMMUNITY_BASE + "/steamguard/phone_checksms?bForTwoFactor=1&bRevoke2fOnCancel=", "GET", null, cookies); // add a new authenticator data.Clear(); var deviceId = BuildRandomId(); data.Add("access_token", state.OAuthToken); data.Add("steamid", state.SteamId); data.Add("authenticator_type", "1"); data.Add("device_identifier", deviceId); data.Add("sms_phone_id", "1"); response = Request(WEBAPI_BASE + "/ITwoFactorService/AddAuthenticator/v0001", "POST", data); var tfaresponse = JObject.Parse(response); if (response.IndexOf("status") == -1 && tfaresponse.SelectToken("response.status").Value <int>() == 84) { // invalid response state.OAuthToken = null; // force new login state.RequiresLogin = true; state.Cookies = null; state.Error = "Unable to send SMS. Check your phone is registered on your Steam account."; return(false); } if (response.IndexOf("shared_secret") == -1) { // invalid response state.OAuthToken = null; // force new login state.RequiresLogin = true; state.Cookies = null; state.Error = "Invalid response from Steam: " + response; return(false); } // save data into this authenticator var secret = tfaresponse.SelectToken("response.shared_secret").Value <string>(); SecretKey = Convert.FromBase64String(secret); Serial = tfaresponse.SelectToken("response.serial_number").Value <string>(); DeviceId = deviceId; state.RevocationCode = tfaresponse.SelectToken("response.revocation_code").Value <string>(); // add the steamid into the data var steamdata = JObject.Parse(tfaresponse.SelectToken("response").ToString()); if (steamdata.SelectToken("steamid") == null) { steamdata.Add("steamid", state.SteamId); } if (steamdata.SelectToken("steamguard_scheme") == null) { steamdata.Add("steamguard_scheme", "2"); } SteamData = steamdata.ToString(Formatting.None); // calculate server drift var servertime = tfaresponse.SelectToken("response.server_time").Value <long>() * 1000; ServerTimeDiff = servertime - CurrentTime; LastServerTime = DateTime.Now.Ticks; state.RequiresActivation = true; return(false); } // finalize adding the authenticator data.Clear(); data.Add("access_token", state.OAuthToken); data.Add("steamid", state.SteamId); data.Add("activation_code", state.ActivationCode); // try and authorize var retries = 0; while (state.RequiresActivation && retries < ENROLL_ACTIVATE_RETRIES) { data.Add("authenticator_code", CalculateCode(false)); data.Add("authenticator_time", ServerTime.ToString()); response = Request(WEBAPI_BASE + "/ITwoFactorService/FinalizeAddAuthenticator/v0001", "POST", data); var finalizeresponse = JObject.Parse(response); if (response.IndexOf("status") != -1 && finalizeresponse.SelectToken("response.status").Value <int>() == INVALID_ACTIVATION_CODE) { state.Error = "Invalid activation code"; return(false); } // reset our time if (response.IndexOf("server_time") != -1) { var servertime = finalizeresponse.SelectToken("response.server_time").Value <long>() * 1000; ServerTimeDiff = servertime - CurrentTime; LastServerTime = DateTime.Now.Ticks; } // check success if (finalizeresponse.SelectToken("response.success").Value <bool>()) { if (response.IndexOf("want_more") != -1 && finalizeresponse.SelectToken("response.want_more").Value <bool>()) { ServerTimeDiff += Period * 1000L; retries++; continue; } state.RequiresActivation = false; break; } ServerTimeDiff += Period * 1000L; retries++; } if (state.RequiresActivation) { state.Error = "There was a problem activating. There might be an issue with the Steam servers. Please try again later."; return(false); } // mark and successful and return key state.Success = true; state.SecretKey = ByteArrayToString(SecretKey); // send confirmation email data.Clear(); data.Add("access_token", state.OAuthToken); data.Add("steamid", state.SteamId); data.Add("email_type", "2"); response = Request(WEBAPI_BASE + "/ITwoFactorService/SendEmail/v0001", "POST", data); return(true); } catch (UnauthorizedRequestException ex) { throw new InvalidEnrollResponseException("You are not allowed to add an authenticator. Have you enabled 'community-generated content' in Family View?", ex); } catch (InvalidRequestException ex) { throw new InvalidEnrollResponseException("Error enrolling new authenticator", ex); } }
internal static bool Contains(this NameValueCollection collection, string name, string value) => collection[name]?.Split(Strings.CommaSplitChar) .Any(val => val.Trim().Equals(value, StringComparison.OrdinalIgnoreCase)) == true;
private int GetCount(NameValueCollection components, Content?content) { var count = 2; if (FixedCountOverride != null) { return(FixedCountOverride.Value); } if (CountOverride == null) //question: will this cause issues with streaming cos the second page have the wrong count { var countStr = components["count"]; if (countStr != null && countStr != "0" && countStr != "500" && countStr != "*") { count = Convert.ToInt32(countStr); } if (components["filter_objid"] != null) { count = 1; var values = components.GetValues("filter_objid"); if (values?.Length > 1) { count = 2; } else { if (values?.First() == "-2") { if (content != Content.Devices) { count = 0; } } if (values?.First() == "-3") { if (content != Content.Groups) { count = 0; } } else if (values?.First() == "-4") { count = 0; } } } } else { if (content != null && CountOverride.ContainsKey(content.Value)) { count = CountOverride[content.Value]; } } return(count); }
/// <summary> /// Log an exception from a Request /// </summary> /// <param name="method">Get or POST</param> /// <param name="url">Request URL</param> /// <param name="cookies">cookie container</param> /// <param name="request">Request data</param> /// <param name="ex">Thrown exception</param> private static void LogException(string method, string url, CookieContainer cookies, NameValueCollection request, Exception ex) { var data = new StringBuilder(); if (cookies != null) { foreach (Cookie cookie in cookies.GetCookies(new Uri(url))) { if (data.Length == 0) { data.Append("Cookies:"); } else { data.Append("&"); } data.Append(cookie.Name + "=" + cookie.Value); } data.Append(" "); } if (request != null) { foreach (var key in request.AllKeys) { if (data.Length == 0) { data.Append("Req:"); } else { data.Append("&"); } data.Append(key + "=" + request[key]); } data.Append(" "); } Logger.Error(ex, "{0}\t{1}\t{2}", method, url, data.ToString()); }
protected override async Task <HttpResponseMessage> SendAsync( HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) { var response = await base.SendAsync(request, cancellationToken); RunnableClientSampleMethod runnableMethod = ClientSampleContext.CurrentRunnableMethod; if (runnableMethod != null) { bool suppressOutput; if (!ClientSampleContext.CurrentContext.TryGetValue <bool>(PropertySuppressOutput, out suppressOutput)) { suppressOutput = false; } string operationName; if (!ClientSampleContext.CurrentContext.TryGetValue <string>(PropertyOperationName, out operationName)) { operationName = ClientSampleContext.CurrentRunnableMethod.MethodBase.Name; } else { // TODO: add validation around the operation name } if (!suppressOutput) { DirectoryInfo baseOutputPath; if (ClientSampleContext.CurrentContext.TryGetValue <DirectoryInfo>(PropertyOutputFilePath, out baseOutputPath)) { Dictionary <string, string> requestHeaders = ProcessHeaders(request.Headers); Dictionary <string, string> responseHeaders = ProcessHeaders(response.Headers); dynamic requestBody = null; try { string requestBodyString = await request.Content.ReadAsStringAsync(); if (!String.IsNullOrEmpty(requestBodyString)) { requestBody = JValue.Parse(requestBodyString); } } catch (Exception) { } JObject responseBody = null; try { if (IsJsonResponse(response)) { string responseBodyString = await response.Content.ReadAsStringAsync(); responseBody = JObject.Parse(responseBodyString); } } catch (Exception) { } ApiResponseMetadata responseData = new ApiResponseMetadata() { Body = responseBody, Headers = responseHeaders }; Dictionary <string, object> requestParameters = new Dictionary <string, object>(); // Add the request body (if there is one) if (requestBody != null) { requestParameters["body"] = requestBody; } // Add query parameters (if any) if (!String.IsNullOrEmpty(request.RequestUri.Query)) { NameValueCollection queryParams = HttpUtility.ParseQueryString(request.RequestUri.Query); foreach (string param in queryParams.Keys) { requestParameters[param] = queryParams[param]; } } // Add request headers foreach (var rh in requestHeaders) { // Look for api-version if (rh.Key.Equals("Accept") && rh.Value.Contains("api-version=")) { int s = rh.Value.IndexOf("api-version=") + "api-version=".Length; int e = rh.Value.IndexOf(';', s); requestParameters.Add("api-version", e != -1 ? rh.Value.Substring(s, e) : rh.Value.Substring(s)); } else { requestParameters.Add(rh.Key, rh.Value); } } // Add sample account name if "account" parameter not already set if (!requestParameters.ContainsKey("account")) { requestParameters["account"] = "fabrikam"; } ApiRequestResponseMetdata data = new ApiRequestResponseMetdata() { Area = runnableMethod.Area, Resource = runnableMethod.Resource, HttpMethod = request.Method.ToString().ToUpperInvariant(), RequestUrl = request.RequestUri.ToString(), Parameters = requestParameters, Responses = new Dictionary <string, ApiResponseMetadata>() { { ((int)response.StatusCode).ToString(), responseData } }, Generated = true, GeneratedDate = DateTime.Now }; string outputPath = Path.Combine(baseOutputPath.FullName, char.ToLower(data.Area[0]) + data.Area.Substring(1), char.ToLower(data.Resource[0]) + data.Resource.Substring(1)); string outputFileName = operationName + ".json"; DirectoryInfo outputDirectory = Directory.CreateDirectory(outputPath); string outputFile = Path.Combine(outputDirectory.FullName, outputFileName); string output = JsonConvert.SerializeObject(data, this.serializerSettings); File.WriteAllText(outputFile, output); } } } return(response); }
/// <summary> /// Perform a request to the Steam WebAPI service /// </summary> /// <param name="url">API url</param> /// <param name="method">GET or POST</param> /// <param name="data">Name-data pairs</param> /// <param name="cookies">current cookie container</param> /// <returns>response body</returns> private string Request(string url, string method, NameValueCollection data = null, CookieContainer cookies = null, NameValueCollection headers = null, int timeout = 0) { // create form-encoded data for query or body var query = data == null ? string.Empty : string.Join("&", Array.ConvertAll(data.AllKeys, key => string.Format("{0}={1}", HttpUtility.UrlEncode(key), HttpUtility.UrlEncode(data[key])))); if (string.Compare(method, "GET", true) == 0) { url += (url.IndexOf("?") == -1 ? "?" : "&") + query; } // call the server var request = WebRequest.CreateHttp(url); request.Method = method; request.Accept = "text/javascript, text/html, application/xml, text/xml, */*"; request.ServicePoint.Expect100Continue = false; request.UserAgent = "Mozilla/5.0 (Linux; U; Android 4.1.1; en-us; Google Nexus 4 - 4.1.1 - API 16 - 768x1280 Build/JRO03S) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30"; request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip; request.Referer = COMMUNITY_BASE; // + "/mobilelogin?oauth_client_id=DE45CD61&oauth_scope=read_profile%20write_profile%20read_client%20write_client"; if (headers != null) { request.Headers.Add(headers); } if (cookies != null) { request.CookieContainer = cookies; } if (timeout != 0) { request.Timeout = timeout; } if (string.Compare(method, "POST", true) == 0) { request.ContentType = "application/x-www-form-urlencoded; charset=UTF-8"; request.ContentLength = query.Length; var requestStream = new StreamWriter(request.GetRequestStream()); requestStream.Write(query); requestStream.Close(); } try { using (var response = (HttpWebResponse)request.GetResponse()) { LogRequest(method, url, cookies, data, response.StatusCode.ToString() + " " + response.StatusDescription); // OK? if (response.StatusCode != HttpStatusCode.OK) { throw new InvalidRequestException(string.Format("{0}: {1}", (int)response.StatusCode, response.StatusDescription)); } // load the response using (var responseStream = new StreamReader(response.GetResponseStream())) { var responseData = responseStream.ReadToEnd(); LogRequest(method, url, cookies, data, responseData); return(responseData); } } } catch (Exception ex) { LogException(method, url, cookies, data, ex); if (ex is WebException webException && webException.Response != null && ((HttpWebResponse)webException.Response).StatusCode == HttpStatusCode.Forbidden) { throw new UnauthorizedRequestException(ex); } throw new InvalidRequestException(ex.Message, ex); } }
public static string Pager(this HtmlHelper helper, string routeName, string actionName, string controllerName, IDictionary <string, object> values, string pageParamName, bool appendQueryString, int pageCount, int noOfPageToShow, int noOfPageInEdge, int currentPage) { Func <string, int, string> getPageLink = (text, page) => { RouteValueDictionary newValues = new RouteValueDictionary(); foreach (KeyValuePair <string, object> pair in values) { Guid t; if ((string.Compare(pair.Key, "controller", StringComparison.OrdinalIgnoreCase) != 0) && (string.Compare(pair.Key, "action", StringComparison.OrdinalIgnoreCase) != 0) && Guid.TryParse(pair.Key, out t) == false) { newValues[pair.Key] = pair.Value; } } if (page > 0) { newValues[pageParamName] = page; } if (appendQueryString) { NameValueCollection queryString = helper.ViewContext.HttpContext.Request.QueryString; foreach (string key in queryString) { if (key != null) { if (!newValues.ContainsKey(key)) { if (!string.IsNullOrEmpty(queryString[key])) { newValues[key] = queryString[key]; } } } } } string link; if (!string.IsNullOrEmpty(routeName)) { link = helper.RouteLink(text, routeName, newValues).ToHtmlString(); } else { actionName = actionName ?? values["action"].ToString(); controllerName = controllerName ?? values["controller"].ToString(); link = helper.ActionLink(text, actionName, controllerName, newValues, null).ToHtmlString(); } return(string.Concat(" ", link)); }; var pagerHtml = new StringBuilder(); if (pageCount > 1) { pagerHtml.Append("<div class=\"pager\">"); double half = Math.Ceiling(Convert.ToDouble(Convert.ToDouble(noOfPageToShow) / 2)); int start = Convert.ToInt32((currentPage > half) ? Math.Max(Math.Min((currentPage - half), (pageCount - noOfPageToShow)), 0) : 0); int end = Convert.ToInt32((currentPage > half) ? Math.Min(currentPage + half, pageCount) : Math.Min(noOfPageToShow, pageCount)); //if (currentPage > 1) //{ // pagerHtml.Append(getPageLink("Previous", currentPage - 1)); //} //else //{ // pagerHtml.Append(" <span class=\"disabled\">Previous</span>"); //} if (start > 0) { int startingEnd = Math.Min(noOfPageInEdge, start); for (int i = 0; i < startingEnd; i++) { int pageNo = (i + 1); pagerHtml.Append(getPageLink(pageNo.ToString(Constants.CurrentCulture), pageNo)); } if (noOfPageInEdge < start) { pagerHtml.Append("<span>...</span>"); } } for (int i = start; i < end; i++) { int pageNo = (i + 1); if (pageNo == currentPage) { pagerHtml.Append(" <span class=\"active\">{0}</span>".FormatWith(pageNo)); } else { pagerHtml.Append(getPageLink(pageNo.ToString(Constants.CurrentCulture), pageNo)); } } if (end < pageCount) { if ((pageCount - noOfPageInEdge) > end) { pagerHtml.Append("<span>...</span>"); } int endingStart = Math.Max(pageCount - noOfPageInEdge, end); for (int i = endingStart; i < pageCount; i++) { int pageNo = (i + 1); pagerHtml.Append(getPageLink(pageNo.ToString(Constants.CurrentCulture), pageNo)); } } //if (currentPage < pageCount) //{ // pagerHtml.Append(getPageLink("Next", currentPage + 1)); //} //else //{ // pagerHtml.Append(" <span class=\"disabled\">Next</span>"); //} pagerHtml.Append("</div>"); } return(pagerHtml.ToString()); }
/// <summary> /// Creates and initializes a new instance of the ClientMessage2 class. /// </summary> private ClientMessage2() { Options = new NameValueCollection(); InitialVector = new byte[0]; }
protected override IList ExecuteCrawl(bool crawlAll) { IList list = new List <InviteInfo>(); string html = string.Empty; string cookiestr = string.Empty; string viewState = string.Empty; int pageInt = 1; string eventValidation = string.Empty; try { html = this.ToolWebSite.GetHtmlByUrl(this.SiteUrl, Encoding.UTF8, ref cookiestr); } catch { return(null); } Parser parser = new Parser(new Lexer(html)); NodeList pageNode = parser.ExtractAllNodesThatMatch(new AndFilter(new TagNameFilter("div"), new HasAttributeFilter("id", "zbggmore2_Pager"))); if (pageNode != null && pageNode.Count > 0) { try { string temp = pageNode.AsString().GetRegexBegEnd("总页数:", "当前"); pageInt = int.Parse(temp); } catch { } } for (int i = 1; i <= pageInt; i++) { if (i > 1) { viewState = this.ToolWebSite.GetAspNetViewState(html); eventValidation = this.ToolWebSite.GetAspNetEventValidation(html); NameValueCollection nvc = this.ToolWebSite.GetNameValueCollection(new string[] { "__VIEWSTATE", "__EVENTTARGET", "__EVENTARGUMENT", "__EVENTVALIDATION" }, new string[] { viewState, "zbggmore2$Pager", i.ToString(), eventValidation }); try { html = this.ToolWebSite.GetHtmlByUrl(this.SiteUrl, nvc, Encoding.UTF8, ref cookiestr); } catch { continue; } } parser = new Parser(new Lexer(html)); NodeList listNode = parser.ExtractAllNodesThatMatch(new AndFilter(new TagNameFilter("table"), new HasAttributeFilter("id", "zbggmore2_DataGrid1"))); if (listNode != null && listNode.Count > 0) { TableTag table = listNode[0] as TableTag; for (int j = 0; j < table.RowCount; j++) { string code = string.Empty, buildUnit = string.Empty, prjName = string.Empty, prjAddress = string.Empty, inviteCtx = string.Empty, inviteType = string.Empty, specType = string.Empty, beginDate = string.Empty, endDate = string.Empty, remark = string.Empty, inviteCon = string.Empty, InfoUrl = string.Empty, CreateTime = string.Empty, msgType = string.Empty, otherType = string.Empty, HtmlTxt = string.Empty, area = string.Empty; TableRow tr = table.Rows[j]; ATag aTag = tr.Columns[1].GetATag(); prjName = aTag.GetAttribute("title"); area = tr.ToNodePlainString().GetRegexBegEnd("【", "】"); endDate = tr.Columns[2].ToPlainTextString().GetDateRegex(); InfoUrl = "http://www.lnzb.cn" + aTag.Link; string htmldtl = string.Empty; try { htmldtl = this.ToolWebSite.GetHtmlByUrl(InfoUrl, Encoding.UTF8).GetJsString(); } catch { continue; } parser = new Parser(new Lexer(htmldtl)); NodeList dtlNode = parser.ExtractAllNodesThatMatch(new AndFilter(new TagNameFilter("table"), new HasAttributeFilter("id", "tblInfo"))); if (dtlNode != null && dtlNode.Count > 0) { HtmlTxt = dtlNode.AsHtml(); inviteCtx = HtmlTxt.ToLower().GetReplace("</p>,<br/>,<br>", "\r\n").ToCtxString(); beginDate = inviteCtx.GetRegex("发布时间").GetDateRegex("yyyy/MM/dd"); prjAddress = inviteCtx.GetAddressRegex(); buildUnit = inviteCtx.GetBuildRegex(); if (buildUnit.Contains("公司")) { buildUnit = buildUnit.Remove(buildUnit.IndexOf("公司")) + "公司"; } if (buildUnit.Contains("地址")) { buildUnit = buildUnit.Remove(buildUnit.IndexOf("地址")); } msgType = "辽宁省建设厅招标投标管理处"; specType = "建设工程"; inviteType = "施工"; InviteInfo info = ToolDb.GenInviteInfo("辽宁省", "辽宁省及地市", area, string.Empty, code, prjName, prjAddress, buildUnit, beginDate, endDate, inviteCtx, remark, msgType, inviteType, specType, otherType, InfoUrl, HtmlTxt); list.Add(info); if (!crawlAll && list.Count >= this.MaxCount) { return(list); } } } } } return(list); }
public async Task <bool> UploadUserData(string url, NameValueCollection input) { newClient.UploadValues(new Uri(url), input); return(true); }
private void fredTries() { try { using (var client = new WebClient()) { var values = new NameValueCollection(); //key and value mapping values["user_name"] = "chupacabra"; values["user_email"] = @"*****@*****.**"; values["user_password_new"] = "omnomnom"; var response = client.UploadValues("http://tral-ee.lo5.org/requestHandler.php", values); //google responds with error here...expected....same thing in postman var responseString = Encoding.Default.GetString(response); Debug.Log(responseString); } } catch (System.InvalidOperationException e) { if (e is WebException) { Debug.Log(e.Message); //Debug.Log (e.StackTrace); Debug.Log(e.GetBaseException()); } } }