public string InternalRFBGetCaptchaCNPJ() { try { var wc = new CookieAwareWebClient(); wc.Headers["user-agent"] = UserAgent; var arrBytes = wc.DownloadData(AddressBase + AddressCaptchaCNPJ); var x = new HtmlDocument(); x.LoadHtml(Encoding.UTF8.GetString(arrBytes)); var image = x.GetElementbyId("imgcaptcha").GetAttributeValue("src", ""); var viewstate = (string) null; // x.GetElementbyId("viewstate").GetAttributeValue("value", ""); image = AddressBase + "/pessoajuridica/cnpj/cnpjreva/" + image.Replace("&", "&"); var bytes = wc.DownloadData(image); var filename = Guid.NewGuid() + ".jpg"; var path = Server.MapPath("~\\temp\\" + filename); if (!Directory.Exists(Path.GetDirectoryName(path))) Directory.CreateDirectory(Path.GetDirectoryName(path)); System.IO.File.WriteAllBytes(path, bytes); Session["GetCNPJViewState"] = viewstate; Session["GetCNPJCookies"] = wc.CookieContainer; return VirtualPathUtility.ToAbsolute("~/temp/" + filename); } catch (Exception) { return null; } }
public bool LogIn(string username, string password) { cawc = new CookieAwareWebClient(); cawc.DownloadData("https://www.anckonsult.eu"); string response = Encoding.UTF8.GetString(cawc.UploadValues("https://www.anckonsult.eu/?class=user&do=login&method=json", new NameValueCollection() { { "uid", username }, { "password", password } })); cawc.DownloadData("https://www.anckonsult.eu"); Console.WriteLine("ANC:" + response); return(response.Contains("{\"ok\":1")); }
public static string GetCaptcha() { CookieContainer _cookies = new CookieContainer(); var htmlResult = string.Empty; using (var wc = new CookieAwareWebClient(_cookies)) { wc.Headers[HttpRequestHeader.UserAgent] = "Mozilla/4.0 (compatible; Synapse)"; wc.Headers[HttpRequestHeader.KeepAlive] = "300"; htmlResult = wc.DownloadString(urlBaseReceitaFederal + paginaPrincipal); } if (htmlResult.Length > 0) { var wc2 = new CookieAwareWebClient(_cookies); wc2.Headers[HttpRequestHeader.UserAgent] = "Mozilla/4.0 (compatible; Synapse)"; wc2.Headers[HttpRequestHeader.KeepAlive] = "300"; byte[] data = wc2.DownloadData(urlBaseReceitaFederal + paginaCaptcha); HttpContext.Current.Session["cookies"] = _cookies; return("data:image/jpeg;base64," + Convert.ToBase64String(data, 0, data.Length)); } return(string.Empty); }
// Thread Code - Session 유지를 위해 실행될 코드 private void KeepSession() { // 무한 반복 while (true) { // CNSA net에서 저장된 Session 받아오기 string nowSession = Encoding.UTF8.GetString(Web.DownloadData(cnsaUrl + "/login/dupLoginCheck?loginId=" + cnsaId)); // Session이 저장된 세션과 다르고 저장된 세션이 비어있지 않을 경우 -> 저장된 Session 교체 if (!session.Equals(nowSession) && !nowSession.Trim().Equals("")) { // 저장된 Session 교체 session = nowSession; // CookieAwareWebClient의 Session 초기화 -> CookieContainer 초기화 Web.CookieContainer = new CookieContainer(); // Session 저장 Web.AddCookie(new Uri(urlIntraNet), new Cookie("JSESSIONID", session)); Web.AddCookie(new Uri(urlExtraNet), new Cookie("JSESSIONID", session)); } // 로그인을 통한 Session 갱신 Web.UploadValues(cnsaUrl + "/login/userLogin", new NameValueCollection() { { "loginId", cnsaId }, { "loginPw", cnsaPw } }); // 10초에 한 번 씩 실행 Thread.Sleep(10000); } }
public string Captcha(string value) { CookieContainer _cookies = new CookieContainer(); var htmlResult = string.Empty; using (var wc = new CookieAwareWebClient(_cookies)) { wc.Headers[HttpRequestHeader.UserAgent] = "Mozilla/4.0 (compatible; Synapse)"; wc.Headers[HttpRequestHeader.KeepAlive] = "300"; htmlResult = wc.DownloadString(urlBaseReceitaFederal + paginaPrincipal); } if (htmlResult.Length > 0) { var wc2 = new CookieAwareWebClient(_cookies); wc2.Headers[HttpRequestHeader.UserAgent] = "Mozilla/4.0 (compatible; Synapse)"; wc2.Headers[HttpRequestHeader.KeepAlive] = "300"; byte[] data = wc2.DownloadData(urlBaseReceitaFederal + paginaCaptcha); CacheHelper.Add("CookieReceitaFederal_" + value, _cookies); return("data:image/jpeg;base64," + System.Convert.ToBase64String(data, 0, data.Length)); } return(string.Empty); }
static public string DoPost(string urlGetAutenticacao, string UrlPost, NameValueCollection parametros) { using (var client = new CookieAwareWebClient()) { var response = client.UploadValues(urlGetAutenticacao, parametros); var result = client.DownloadData(UrlPost); return(Encoding.UTF8.GetString(result)); } }
public void SetImage(string img_url) { CookieAwareWebClient wc = new CookieAwareWebClient(); wc.m_container = cc; Image i = Utils.GetImageFromBytes(Comm.DecompressBytes(wc.DownloadData(img_url))); Utils.FitImageNicely(ref this.picCAPTCHA, i); }
public string get(string referer, string url) { Uri u2 = new Uri(mainurl, url); nowUri = u2; // u2 = new Uri("http://www.baidu.com"); CookieAwareWebClient MyWebClient = new CookieAwareWebClient(); MyWebClient.Headers.Add("Accept", "text/html, application/xhtml+xml, */*"); MyWebClient.Headers.Add("Accept-Language", "zh-CN"); MyWebClient.Headers.Add("User-Agent", this.UserAgent); //MyWebClient.Headers.Add("Cookie", getCookieStr(u2)); // MyWebClient.Headers.Add("Cookie", "cookie2=1c26acc028f9a5604e3210550e8d5cea;t=1;uc1=2;uc3=3;a1=D;unt=f;a2=s;f1=1;sg=2;mt=3;e1=U;e2=w;skt=d;s=c;e3=s;_tb_token_=s;tg=0;_l_g_=s;_nk_=c;cookie17=0;a=1;a2=2;"); if (Authorization != null) { MyWebClient.Headers.Add("Authorization", Authorization); } //MyWebClient.Headers.Add("Cookie", "PHPSESSID=0cefe02fbabf45cf491cd30be8027039; phpcms_auth=VmcHM1YzVAsCPAI0A2EKNwdnVGUDNABjV2tQNlVuDjtXMgc4UWECMlA4BDAANQM%2FAWkBNwUxUzgEaQpsBG8PZFYzB2ZWZlRnAlACYwNhCjMHYVQzA2AAYFc8UGNVbA4yV2wHZlE%2FAjJQbQQzAGADbQFmAW4FYVMwBGcKaAQ9D2NWMwdmVmZUZAI8"); if (referer != null) { MyWebClient.Headers.Add("Referer", referer); } //ecmsloginnum=3; ecmslastlogintime=1356325904; ecmsloginnum=3; kgereloginuserid=62; kgereloginusername=%B4%A8%B4%A8; kgereloginrnd=vXnnwvhbqYsHnXBS24zT; kgereloginlevel=4; kgereeloginlic=empirecmslic; kgereloginadminstyleid=1; kgereloginecmsckpass=ac806cd0151b82fb4fe5cf1f53945469; kgerelogintime=1356400760; kgeretruelogintime=1356400760; kgereecmsdodbdata=deleted; ecmscheckkey=deleted;kgereloginuserid=62 //MyWebClient.Headers.Add("Cookie", "ecmsloginnum=3; ecmslastlogintime=1356325904; ecmsloginnum=3; kgereloginuserid=62; kgereloginusername=%B4%A8%B4%A8; kgereloginrnd=Kqj4qQcWbx4hpaBRBTFJ; kgereloginlevel=4; kgereeloginlic=empirecmslic; kgereloginadminstyleid=1; kgereloginecmsckpass=1140c99a496979aba6dc7d0c11cb30b7; kgerelogintime=1356400917; kgeretruelogintime=1356400917; kgereloginuserid=62"); MyWebClient.Credentials = CredentialCache.DefaultCredentials; try { Byte[] pageData = MyWebClient.DownloadData(u2.AbsoluteUri); this.ResponseUri = MyWebClient.ResponseUri; //setCookie(MyWebClient.ResponseHeaders["Set-Cookie"]); //addCookie(MyWebClient.cookies); setCookie(MyWebClient._cookieContainer.GetCookieHeader(mainurl)); if (MyWebClient.ResponseHeaders["location"] != null) { Uri u3 = new Uri(u2, MyWebClient.ResponseHeaders["location"].ToString()); return(get(u2.AbsoluteUri, u3.AbsoluteUri)); } else { return(codeLange.GetString(pageData)); } } catch { webCookie = null; return(""); } }
// Thread Code - 내부망 / 외부망을 결정하기 위해 실행될 코드 private void CheckIntraNet() { CookieAwareWebClient anotherWeb = new CookieAwareWebClient(); // 연결할 페이지 결정 (내부망/외부망) try { // CNSA net 내부망에서 Session을 받아옴 session = Encoding.UTF8.GetString(anotherWeb.DownloadData(urlIntraNet + "/login/dupLoginCheck?loginId=" + cnsaId)); cnsaUrl = urlIntraNet; } // WebException이 발생하면 내부망에 연결되어있지 않은 것으로 간주 catch (WebException) { cnsaUrl = urlExtraNet; } }
private static CookieAwareWebClient LogIn(string baseUrl, string email, string password) { var signinUrl = string.Format("{0}/signin", baseUrl); var loginUrl = string.Format("{0}/login_post", baseUrl); var client = new CookieAwareWebClient(); client.DownloadData(signinUrl); var response = JsonConvert.DeserializeObject<dynamic>(Encoding.UTF8.GetString(client.UploadValues(loginUrl, new NameValueCollection { { "email", email }, { "password", password } }))); if (response.success.ToObject<bool>()) return client; Console.WriteLine("Login failed:"); Console.WriteLine(response.value.ToObject<string>()); throw new OperationFailedGracefully(); }
public byte[] getVerificationCode(string url, string referer) { Uri u2 = new Uri(mainurl, url); CookieAwareWebClient MyWebClient = new CookieAwareWebClient(); MyWebClient.Headers.Add("Accept", "text/html, application/xhtml+xml, */*"); MyWebClient.Headers.Add("Accept-Language", "zh-CN"); MyWebClient.Headers.Add("User-Agent", this.UserAgent); if (referer != null) { MyWebClient.Headers.Add("Referer", referer); } //MyWebClient.Headers.Add("Cookie", getCookieStr(u2)); if (Authorization != null) { MyWebClient.Headers.Add("Authorization", Authorization); } MyWebClient.Credentials = CredentialCache.DefaultCredentials; try { Byte[] pageData = MyWebClient.DownloadData(u2.AbsoluteUri); //setCookie(MyWebClient.ResponseHeaders["Set-Cookie"]); setCookie(MyWebClient._cookieContainer.GetCookieHeader(u2)); //addCookie(MyWebClient.cookies); if (MyWebClient.ResponseHeaders["location"] != null) { Uri u3 = new Uri(u2, MyWebClient.ResponseHeaders["location"].ToString()); return(getVerificationCode2(u3.AbsoluteUri, u2.AbsoluteUri)); } else { return(pageData); } } catch { return(null); } }
private static Bitmap PegarCaptchaCNPJ() { if (_cookies == null) { _cookies = new CookieContainer(); var htmlResult = string.Empty; using (var wc = new CookieAwareWebClient(_cookies)) { wc.Headers[HttpRequestHeader.UserAgent] = "Mozilla/4.0 (compatible; Synapse)"; wc.Headers[HttpRequestHeader.KeepAlive] = "300"; htmlResult = wc.DownloadString(urlBaseReceitaFederal + paginaPrincipal); } if (htmlResult.Length == 0) { return(null); } } var wc2 = new CookieAwareWebClient(_cookies); wc2.Headers[HttpRequestHeader.UserAgent] = "Mozilla/4.0 (compatible; Synapse)"; wc2.Headers[HttpRequestHeader.KeepAlive] = "300"; byte[] data = wc2.DownloadData(urlBaseReceitaFederal + paginaCaptcha); _cookies.Add(new Uri(urlBaseReceitaFederal), new Cookie("flag", "1")); using (MemoryStream ms = new MemoryStream(data)) { var bmp = new Bitmap(ms); if (File.Exists(tempPath)) { File.Delete(tempPath + @"captcha.png"); } bmp.Save(tempPath + @"captcha.png", System.Drawing.Imaging.ImageFormat.Png); return(bmp); } }
public BitMap GetCaptcha() { string htmlResult; using (var wc = new CookieAwareWebClient()) { wc.SetCookieContainer(_cookies); wc.Headers[HttpRequestHeader.UserAgent] = "Mozilla/4.0 (compatible; Synapse)"; wc.Headers[HttpRequestHeader.KeepAlive] = "300"; htmlResult = wc.DownloadString(urlBaseReceitaFederal + paginaPrincipal); } if (htmlResult.Length > 0) { var wc2 = new CookieAwareWebClient(); wc2.SetCookieContainer(_cookies); wc2.Headers[HttpRequestHeader.UserAgent] = "Mozilla/4.0 (compatible; Synapse)"; wc.Headers[HttpRequestHeader.KeepAlive] = "300"; byte[] data = wc2.DownloadData(urlBaseReceitaFederal + paginaCaptcha); return(new BitMap(new MemoryStream(data))); } return(null); }
public string GetHTML(string url) { try { CookieAwareWebClient MyWebClient = new CookieAwareWebClient(cookie); MyWebClient.Headers.Add("Cookie", _cookies); MyWebClient.Credentials = CredentialCache.DefaultCredentials; //获取或设置用于向Internet资源的请求进行身份验证的网络凭据 Byte[] pageData = MyWebClient.DownloadData(url); //从指定网站下载数据 string pageHtml = Encoding.UTF8.GetString(pageData); //如果获取网站页面采用的是GB2312,则使用这句 return(pageHtml); } catch (WebException webEx) { Console.WriteLine(webEx.Message.ToString()); return(null); } }
// Session 유지를 위해 실행될 타이머 코드 void SessionUpdate(object state) { try { // CNSA net에서 저장된 Session 받아오기 string nowSession = Encoding.UTF8.GetString(Web.DownloadData(extraNetUrl + "/login/dupLoginCheck?loginId=" + cnsaId)); // Session이 저장된 세션과 다르고 저장된 세션이 비어있지 않을 경우 -> 저장된 Session 교체 if (!session.Equals(nowSession) && nowSession.Trim() != "") { // 저장된 Session 교체 session = nowSession; // Session이 변경되었을 경우 알림 new Handler(Looper.MainLooper).Post(new Java.Lang.Runnable(() => { Toast.MakeText(this, "Session이 변경되었습니다.", ToastLength.Long).Show(); })); } // Session 초기화 Web.CookieContainer = new CookieContainer(); // Session 저장 Web.AddCookie(new Uri(intraNetUrl), new Cookie("JSESSIONID", session)); Web.AddCookie(new Uri(extraNetUrl), new Cookie("JSESSIONID", session)); // 로그인을 통한 Session 갱신 Web.UploadValues(extraNetUrl + "/login/userLogin", new System.Collections.Specialized.NameValueCollection() { { "loginId", cnsaId }, { "loginPw", cnsaPw } }); } catch (WebException webE) { // WebException 발생 시 실행 [CNSAnet 연결 실패 포함] // Toast new Handler(Looper.MainLooper).Post(new Java.Lang.Runnable(() => { Toast.MakeText(this, "Session이 변경되었습니다.", ToastLength.Long).Show(); })); } }
protected override void DoBackgroundWork() { CookieAwareWebClient wc = new CookieAwareWebClient(); wc.Proxy = null; if (!string.IsNullOrEmpty(cameraSpec.username) || !string.IsNullOrEmpty(cameraSpec.password)) { wc.Credentials = new NetworkCredential(cameraSpec.username, cameraSpec.password); //string authInfo = cameraSpec.username + ":" + cameraSpec.password; //authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo)); //wc.Headers["Authorization"] = "Basic " + authInfo; } while (!Exit) { try { System.Diagnostics.Stopwatch timer = new System.Diagnostics.Stopwatch(); timer.Start(); byte[] newFrame = wc.DownloadData(cameraSpec.imageryUrl); //SimpleProxy.GetData(cameraSpec.imageryUrl, cameraSpec.username, cameraSpec.password, true); if (!ArraysLooselyMatch(newFrame, lastFrame)) { this.lastFrame = newFrame; EventWaitHandle oldWaitHandle = newFrameWaitHandle; newFrameWaitHandle = new EventWaitHandle(false, EventResetMode.ManualReset); oldWaitHandle.Set(); } int diff = cameraSpec.delayBetweenImageGrabs - (int)timer.ElapsedMilliseconds; while (diff > 0 && !Exit) { int timeToWait = Math.Max(250, diff); Thread.Sleep(timeToWait); diff = cameraSpec.delayBetweenImageGrabs - (int)timer.ElapsedMilliseconds; } if (newFrame.Length == 0 && cameraSpec.delayBetweenImageGrabs < 1000) { // Prevent rapid attempts if image failed to load int ctr = 0; while (ctr++ < 10) { Thread.Sleep(100); } } timer.Stop(); } catch (ThreadAbortException) { newFrameWaitHandle.Set(); return; } catch (Exception ex) { Logger.Debug(ex); newFrameWaitHandle.Set(); if (!Exit) { Thread.Sleep(5000); } } } newFrameWaitHandle.Set(); }
public string InternalRFBGetCaptchaCPF() { try { var wc = new CookieAwareWebClient(); wc.Headers["user-agent"] = UserAgent; var arrBytes = wc.DownloadData(AddressBase + AddressCaptchaCPF); var x = new HtmlDocument(); x.LoadHtml(Encoding.UTF8.GetString(arrBytes)); var image = x.GetElementbyId("imgCaptcha").GetAttributeValue("src", ""); image = "http://www.receita.fazenda.gov.br/Aplicacoes/ATCTA/CPF/" + image.Replace("&", "&").Replace("./", ""); var bytes = wc.DownloadData(image); var filename = Guid.NewGuid() + ".jpg"; var path = Server.MapPath("~\\temp\\" + filename); if (!Directory.Exists(Path.GetDirectoryName(path))) Directory.CreateDirectory(Path.GetDirectoryName(path)); System.IO.File.WriteAllBytes(path, bytes); System.Web.HttpContext.Current.Session["GetCPFCookies"] = wc.CookieContainer; return VirtualPathUtility.ToAbsolute("~/temp/" + filename); } catch (Exception) { return null; } }
private static AuthInfo GetInstagramAuth(string oAuthUri, string clientId, string redirectUri, InstagramConfig config, string login, string password) { List<Auth.Scope> scopes = new List<Auth.Scope>(); scopes.Add(Auth.Scope.basic); var link = InstaSharp.Auth.AuthLink(oAuthUri, clientId, redirectUri, scopes); // User name in the specified node CookieAwareWebClient client = new CookieAwareWebClient(); // We went to the login page var result = client.DownloadData(link); var html = System.Text.Encoding.Default.GetString(result); // Take the token string csr = ""; string pattern = @"csrfmiddlewaretoken""\svalue=""(.+)"""; var r = new System.Text.RegularExpressions.Regex(pattern); var m = r.Match(html); csr = m.Groups[1].Value; // Login string loginLink = string.Format( "https://instagram.com/accounts/login/?next=/oauth/authorize/%3Fclient_id%3D{0}%26redirect_uri%3Dhttp%3A//www.pwr.wroc.pl%26response_type%3Dcode%26scope%3Dbasic", clientId); NameValueCollection parameters = new NameValueCollection(); parameters.Add("csrfmiddlewaretoken", csr); parameters.Add("username", login); parameters.Add("password", password); // You need to add the secret cookies received pre-login // Looking for something headers string agent = "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)"; client.Headers["Referer"] = loginLink; client.Headers["Host"] = "instagram.com"; client.Headers["Content-Type"] = "application/x-www-form-urlencoded"; client.Headers["User-Agent"] = agent; client.Headers["Accept-Language"] = "pl-PL"; client.Headers["Accept"] = "text/html, application/xhtml+xml, */*"; client.Headers["Cache-Control"] = "no-cache"; // request var result2 = client.UploadValues(loginLink, "POST", parameters); // Fasting data received code // New link is not on the api, and on instagram string newPostLink = string.Format( "https://instagram.com/oauth/authorize/?client_id={0}&redirect_uri=http://www.pwr.wroc.pl&response_type=code&scope=basic", clientId); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(newPostLink); request.AllowAutoRedirect = false; request.CookieContainer = client.CookieContainer; request.Referer = newPostLink; request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; request.UserAgent = agent; string postData = string.Format("csrfmiddlewaretoken={0}&allow=Authorize", csr); request.ContentLength = postData.Length; ASCIIEncoding encoding = new ASCIIEncoding(); byte[] loginDataBytes = encoding.GetBytes(postData); request.ContentLength = loginDataBytes.Length; Stream stream = request.GetRequestStream(); stream.Write(loginDataBytes, 0, loginDataBytes.Length); // send the request var response = request.GetResponse(); string location = response.Headers["Location"]; // Now take out the code and get the authentication pattern = @"www.pwr.wroc.pl\?code=(.+)"; r = new System.Text.RegularExpressions.Regex(pattern); m = r.Match(location); string code = m.Groups[1].Value; // Finally, we get an authentication token var auth = new InstaSharp.Auth(config); //.OAuth(InstaSharpConfig.config); // now we have to call back to instagram and include the code they gave us // along with our client secret var oauthResponse = auth.RequestToken(code); return oauthResponse; }
static void Main(string[] args) { try { if (System.Threading.Thread.CurrentThread.CurrentCulture.Name.StartsWith("zh")) { language = JsonConvert.DeserializeObject <Language>(Encoding.UTF8.GetString(Properties.Resources.zh_tw)); //假如是中文語系,就使用中文 } else { language = new Language(); //否則,英文 } } catch (Exception) { language = new Language(); /*這邊是當跳出錯誤時,使用英文。正常來說是不會有錯誤才對,但有次比賽拿來做測試的時候出了錯誤,也抓不到點,就先認定是語系的問題了*/ } Console.Title = language.AppTitle; if (OsuPathResolver.Instance.OsuIsRunning) { FormatWrite(language.DetectionOsuIsRunning, ConsoleColor.Red); } OpenFileDialog openFileDialog = new OpenFileDialog(); //選擇收藏夾檔案的對話方塊 openFileDialog.AddExtension = true; openFileDialog.CheckFileExists = true; openFileDialog.CheckPathExists = true; openFileDialog.DefaultExt = "json"; openFileDialog.Filter = language.OpenFileFilter; openFileDialog.Multiselect = false; if (openFileDialog.ShowDialog() == DialogResult.Cancel) { Exit(language.PleaseSelectCollection, true); } JsonData collectionData = null; try { collectionData = JsonConvert.DeserializeObject <JsonData>(File.ReadAllText(openFileDialog.FileName)); } //讀取收藏夾資料 catch (Exception) { } if (collectionData == null || collectionData.collection_data == null) { Exit(language.ReadCollectionFail, true); } string osuPath = OsuPathResolver.Instance.GetOsuDir((path) => { //第一次會先偵測osu的路徑,然後提示使用者是否正確 var dialogResult = MessageBox.Show( string.Format( language.ConfirmOsuPath, Environment.NewLine + path, Environment.NewLine), "", MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk); return(dialogResult == DialogResult.Yes); }, (text) => { FolderBrowserDialog dialog = new FolderBrowserDialog(); //假如是錯誤的,那就開個資料夾選擇對話框,讓使用者自行選擇osu的路徑 dialog.ShowNewFolderButton = false; dialog.Description = language.PleaseSelectOsuPath; dialog.RootFolder = Environment.SpecialFolder.MyComputer; if (dialog.ShowDialog() == DialogResult.OK && Directory.Exists(dialog.SelectedPath)) { return(dialog.SelectedPath); } return(""); }); if (osuPath == string.Empty || !Directory.Exists(osuPath)) { Exit(language.NeedValidOsuPath, true); } if (!osuPath.EndsWith("\\")) { osuPath += "\\"; } FormatWrite(string.Format(language.OsuPath, osuPath), ConsoleColor.Yellow); OsuFileIo.OsuSettings.Load(osuPath); OsuFileIo.OsuDatabase.Load(osuPath + "osu!.db"); //載入osu的資料庫來抓取songs的資料夾路徑 List <BeatmapData> needDownloadBeatmapList = new List <BeatmapData>(); var collectionManager = new CollectionsManager(OsuFileIo.OsuDatabase.LoadedMaps.Beatmaps); Collection collection; //初始化目前osu所有的Beatmap collectionManager.EditCollection(CollectionEditArgs.AddCollections(OsuFileIo.CollectionLoader.LoadCollection(osuPath + "collection.db"))); //載入原先的收藏夾 foreach (CollectionData item in collectionData.collection_data) { FormatWrite(string.Format(language.CollectionName, item.collection_name), ConsoleColor.Yellow); if (collectionManager.CollectionNameExists(item.collection_name)) { collection = collectionManager.GetCollectionByName(item.collection_name); //如果收藏夾已經存在,就讀取出來 } else { collection = new Collection(OsuFileIo.LoadedMaps) { Name = item.collection_name } }; //否則新建一個 foreach (BeatmapData item2 in item.beatmap_data) { if (!collection.AllBeatmaps().Any((x) => x.MapId == item2.beatmap_id)) //讀取收藏夾內的Beatmap,如果要匯入的收藏夾Beatmap ID不存在於收藏夾內,那就新增進去 { FormatWrite(string.Format(language.AddBeatmapToCollection, item2.beatmap_name), ConsoleColor.Green); collection.AddBeatmapByHash(item2.beatmap_md5); //新增Beatmap,使用Hash新增法 if (!OsuFileIo.OsuDatabase.LoadedMaps.Beatmaps.Any((x) => x.MapId == item2.beatmap_id)) //如果osu資料庫裡面沒有該Beatmap { needDownloadBeatmapList.Add(item2); //就新增到下載清單內 FormatWrite(language.NeedDownloadBeatmap, ConsoleColor.Cyan); } } } collectionManager.EditCollection(CollectionEditArgs.RemoveCollections(new Collections() { collection })); //先把收藏夾移除 collectionManager.EditCollection(CollectionEditArgs.AddCollections(new Collections() { collection })); //再把收藏夾新增,以達成重整的效果 } if (needDownloadBeatmapList.Count != 0) //如果下載清單數量不為0,就進入下載程序 { FormatWrite(language.DownloadBeatmapInfo, ConsoleColor.Green); CookieAwareWebClient cookieAwareWebClient = new CookieAwareWebClient(); //CollectionManager提供的class,可以讓WebClient使用cookie的功能 string username, password; do { Console.Write(language.OsuUsername); username = Console.ReadLine(); Console.Write(language.OsuPassword); password = ""; do { ConsoleKeyInfo key = Console.ReadKey(true); if (key.Key != ConsoleKey.Backspace && key.Key != ConsoleKey.Enter) { password += key.KeyChar; Console.Write("*"); } else { if (key.Key == ConsoleKey.Backspace && password.Length > 0) { password = password.Substring(0, (password.Length - 1)); Console.Write("\b \b"); } else if (key.Key == ConsoleKey.Enter) { Console.WriteLine(); break; } } } while (true); try { if (!cookieAwareWebClient.Login(loginAddress, string.Format(loginDataStr, username, password)).Contains("I don't have an account")) { break; } } //登入失敗的話,回傳的網頁資料會有I don't have an account catch (Exception ex) { Exit(string.Format(language.LoginErrorElseReason, ex.Message)); } FormatWrite(language.LoginError, ConsoleColor.Red); } while (true); bool downloadVideo = MessageBox.Show(language.DownloadBeatmapWithVideo, "", MessageBoxButtons.YesNo) == DialogResult.Yes; //提示下載時是否包含背景影片 needDownloadBeatmapList.ForEach((item) => { string savePath = OsuFileIo.OsuSettings.CustomBeatmapDirectoryLocation + item.beatmap_setid + " " + StripInvalidCharacters(item.beatmap_name) + ".osz"; //存放路徑: osu的songs資料夾 + BeatmapSet ID + BeatmapSet Name if (!File.Exists(savePath)) { FormatWrite(string.Format(language.DownloadBeatmapName, Path.GetFileName(savePath)), ConsoleColor.Green); try { File.WriteAllBytes(savePath, cookieAwareWebClient.DownloadData("https://osu.ppy.sh/d/" + item.beatmap_setid + (downloadVideo ? "n" : ""))); } catch (Exception ex) { Console.WriteLine(string.Format(language.DownloadFali, ex.Message)); } } else { FormatWrite(string.Format(language.DownloadDone, Path.GetFileName(savePath)), ConsoleColor.Yellow); } }); } string backupName = "collection.db-" + DateTime.Now.ToFileTime() + ".bak"; //備份舊的收藏夾檔案 File.Move(osuPath + "collection.db", osuPath + backupName); //然後覆蓋新的收藏夾檔案 Console.WriteLine(string.Format(language.BackupCollectionTo, osuPath + backupName)); Console.WriteLine(language.WritingNewCollection); OsuFileIo.CollectionLoader.SaveOsuCollection(collectionManager.LoadedCollections, osuPath + "collection.db"); if (OsuPathResolver.Instance.OsuIsRunning) { if (needDownloadBeatmapList.Count != 0) { Exit(language.WriteDone1); } else { Exit(language.WriteDone2); } } else { if (needDownloadBeatmapList.Count != 0) { Exit(language.WriteDone3); } else { Exit(language.WriteDone4); } } }
private void button1_Click(object sender, EventArgs e) { string autoIncrementIndexOfData = cntAutoInc.ToString(); string password = ""; if (GlobalClass.TestSecretCloud() == true) { password = GlobalClass.ReadSecretCloud(); //Sha256 } string InputString = ""; //******************* INITIATE PHPSESSION *************************** NameValueCollection formData = new NameValueCollection(); CookieAwareWebClient webClient = new CookieAwareWebClient(); webClient.Encoding = System.Text.Encoding.Default; formData.Clear(); formData["username"] = "******"; if (GlobalClass.TestPasswordCloud() == true) { formData["password"] = GlobalClass.ReadPasswordCloud(); //user pwd } byte[] responseBytes = webClient.UploadValues("http://your.url.here/lo.php", "POST", formData); string responseHTML = Encoding.UTF8.GetString(responseBytes); Uri uriStr; if (Uri.TryCreate("http://your.url.here", UriKind.RelativeOrAbsolute, out uriStr) == false) { System.Diagnostics.Debug.WriteLine("NO"); } foreach (Cookie cookie in webClient.CookieContainer.GetCookies(uriStr)) { System.Diagnostics.Debug.WriteLine(cookie.Name); System.Diagnostics.Debug.WriteLine(cookie.Value); } //******************* INITIATE PHPSESSION *************************** //******************* DOWNLOAD XML FILE LIST *************************** string fileList = webClient.DownloadString("http://your.url.here/filelist.php"); DataSet ds = new DataSet(); byte[] byteArray = Encoding.UTF8.GetBytes(fileList); ds.ReadXml(new MemoryStream(byteArray)); if (ds.Tables.Count > 0) { var result = ds.Tables[0]; } dataGridView1.DataSource = ds.Tables[0]; //******************* DOWNLOAD XML FILE LIST *************************** //******************* DOWNLOAD IV *************************** byte[] ivArr = webClient.DownloadData("http://your.url.here/listiv.php?id=" + autoIncrementIndexOfData); //******************* DOWNLOAD IV *************************** //******************* DOWNLOAD LENGTH *************************** byte[] length = webClient.DownloadData("http://your.url.here/getLen.php?id=" + autoIncrementIndexOfData); //filesize from files int fileSize = 0; foreach (byte l in length) { fileSize += (byte)(l - (byte)(0x30)); fileSize *= 10; } fileSize /= 10; System.Diagnostics.Debug.WriteLine("filesize: " + fileSize.ToString()); //******************* DOWNLOAD LENGTH *************************** //******************* DOWNL DATA *************************** InputString = webClient.DownloadString("http://your.url.here/dwnl.php?id=" + autoIncrementIndexOfData); //******************* DOWNL DATA *************************** //******************* DOWNLOAD AS FILE *************************** webClient.DownloadFile("http://your.url.here/download.php?id=" + autoIncrementIndexOfData.ToString(), "C:\\your\\dir\\here\\akm2Raw.jpg"); //******************* DOWNLOAD AS FILE *************************** ////******************* DOWNLOAD DOWNLOAD *************************** string InputStringDownload = webClient.DownloadString("http://your.url.here/download.php"); ////******************* DOWNLOAD DOWNLOAD *************************** //******************* DECRYPT *************************** // Create sha256 hash SHA256 mySHA256 = SHA256Managed.Create(); byte[] key = mySHA256.ComputeHash(Encoding.ASCII.GetBytes(password)); string decrypted = this.DecryptString(InputString, key, ivArr, fileSize); byte[] decryptedArr = Convert.FromBase64String(decrypted); //******************* DECRYPT *************************** //******************* CHECK SIGN *************************** Encoding encoding = Encoding.UTF8; DataTable dt = ds.Tables[0]; BinaryFormatter bf = new BinaryFormatter(); using (var ms = new MemoryStream()) { foreach (DataRow row in dt.Rows) { if (row["id"].ToString() == autoIncrementIndexOfData) { Debug.WriteLine(row["sign"].ToString()); bf.Serialize(ms, row["sign"]); } } byte[] signObj = ms.ToArray(); } using (HMACSHA256 hmac = new HMACSHA256(key)) { var hash = hmac.ComputeHash(StringToStream(decrypted)); // Create a new Stringbuilder to collect the bytes and create a string. StringBuilder sBuilder = new StringBuilder(); // Loop through each byte of the hashed data // and format each one as a hexadecimal string. for (int i = 0; i < hash.Length; i++) { sBuilder.Append(hash[i].ToString("x2")); } // Return the hexadecimal string. Debug.WriteLine(sBuilder.ToString()); } Debug.WriteLine("getUUID: " + getUUID()); //******************* CHECK SIGN *************************** File.WriteAllBytes("C:\\your\\dir\\here\\akm2.jpg", decryptedArr); // Requires System.IO }
static void Main(string[] args) { try { CookieAwareWebClient wc = new CookieAwareWebClient(); wc.AddDefaultHeaders(); byte[] buff = wc.DownloadData("https://www.facebook.com/the.habib.qureshi/allactivity"); //https://www.facebook.com/all_activity.php - 2012 DateTime dt = DateTime.Now; //DateTime dt = DateTime.ParseExact("6/10/2012", "M/d/yyyy", null); String sDate = dt.ToString("M/d/yyyy"); sDate = Uri.EscapeDataString(sDate); int main_count = 0; while(true) { main_count++; int i = 0; System.Console.WriteLine(dt.ToShortDateString()); while (DeleteActivityOnThisDate(wc, sDate, dt)) i++; System.Threading.Thread.Sleep(500); dt = dt.AddDays(-1); sDate = dt.ToString("M/d/yyyy"); sDate = Uri.EscapeDataString(sDate); if (main_count >= 5000) break; //10 years? } } catch (Exception ex) { ex.ToString(); } }
// Button Click Event private void CLK_Click(object sender, EventArgs e) { // CNSAnet Id, Pw 저장 cnsaId = FindViewById <EditText>(Resource.Id.inputId).Text; cnsaPw = FindViewById <EditText>(Resource.Id.inputPw).Text; if (IsStarted) // Service가 실행 중인 경우 // Service 종료 { StopService(CLKService); // Service 실행 상태 갱신 IsStarted = false; // Button Image 변경 FindViewById <Button>(Resource.Id.loginLogo).Background = GetDrawable(Resource.Drawable.CLKStop); } else if (cnsaId.Trim().Equals("")) // If ID column is empty // inputId 초기화 후 포커스 맞춤 { FindViewById <EditText>(Resource.Id.inputId).Text = ""; FindViewById <EditText>(Resource.Id.inputId).FocusableInTouchMode = true; FindViewById <EditText>(Resource.Id.inputId).RequestFocus(); // Toast Toast.MakeText(this, "Please enter your ID", ToastLength.Long).Show(); } else if (cnsaPw.Trim().Equals("")) // If PW column is empty // inputPw 초기화 후 포커스 맞춤 { FindViewById <EditText>(Resource.Id.inputPw).Text = ""; FindViewById <EditText>(Resource.Id.inputPw).FocusableInTouchMode = true; FindViewById <EditText>(Resource.Id.inputPw).RequestFocus(); // Toast Toast.MakeText(this, "Please enter your PW", ToastLength.Long).Show(); } else { try { // CNSAnet에서 Session을 받아옴 session = Encoding.UTF8.GetString(Web.DownloadData(extraNetUrl + "/login/dupLoginCheck?loginId=" + cnsaId)); } catch (WebException webE) { // WebException 발생 시 실행 [CNSAnet 연결 실패 포함] // Toast Toast.MakeText(this, "CNSAnet에 연결할 수 없습니다.", ToastLength.Long).Show(); return; } // Session이 존재할 경우 (로그인이 되어 있을 경우) if (session.Trim() != "") { // Session 초기화 Web.CookieContainer = new CookieContainer(); // Session 값을 저장 Web.AddCookie(new Uri(intraNetUrl), new Cookie("JSESSIONID", session)); Web.AddCookie(new Uri(extraNetUrl), new Cookie("JSESSIONID", session)); // 로그인 시도 string responseData = Encoding.UTF8.GetString(Web.UploadValues(extraNetUrl + "/login/userLogin", new System.Collections.Specialized.NameValueCollection() { { "loginId", cnsaId }, { "loginPw", cnsaPw } })); if (!responseData.Contains("/login/userLogin")) // requestData에 특정 문자열이 포함되어 있지 않은 경우 로그인 성공으로 간주 // Service가 실행 중이지 않은 경우 { if (!IsStarted) { // Create Service CLKService = new Intent(this, typeof(KeepSession)); // Set Service Action CLKService.SetAction("com.CLK.KeepService"); // Add Receiver receiver = new RestartService(); // Save Receiver RegisterReceiver(receiver, new IntentFilter(CLKService.Action)); // Service에 값 전달 CLKService.PutExtra("cnsaId", cnsaId); CLKService.PutExtra("cnsaPw", cnsaPw); if (studentCount) // 학생인 경우 { CLKService.PutExtra("intraNetUrl", strIntraNetUrl); CLKService.PutExtra("extraNetUrl", strExtraNetUrl); } else // 교사/교직원인 경우 { CLKService.PutExtra("intraNetUrl", tcrIntraNetUrl); CLKService.PutExtra("extraNetUrl", tcrExtraNetUrl); } CLKService.PutExtra("session", session); // Service 실행 StartService(CLKService); // Service 상태 저장 IsStarted = true; // Button Image 변경 FindViewById <Button>(Resource.Id.loginLogo).Background = GetDrawable(Resource.Drawable.CLKRun); } } else // 로그인 실패 // Toast { Toast.MakeText(this, "Login Failed", ToastLength.Long).Show(); } } else // session이 존재하지 않을 경우 (로그인이 되어 있지 않을 경우) // Toast { Toast.MakeText(this, "CNSAnet에 로그인이 되어있지 않습니다.", ToastLength.Long).Show(); } } }
public static string GetCaptcha() { CookieContainer _cookies = new CookieContainer(); var htmlResult = string.Empty; using (var wc = new CookieAwareWebClient(_cookies)) { wc.Headers[HttpRequestHeader.UserAgent] = "Mozilla/4.0 (compatible; Synapse)"; wc.Headers[HttpRequestHeader.KeepAlive] = "300"; htmlResult = wc.DownloadString(urlBaseReceitaFederal + paginaPrincipal); } if (htmlResult.Length > 0) { var wc2 = new CookieAwareWebClient(_cookies); wc2.Headers[HttpRequestHeader.UserAgent] = "Mozilla/4.0 (compatible; Synapse)"; wc2.Headers[HttpRequestHeader.KeepAlive] = "300"; byte[] data = wc2.DownloadData(urlBaseReceitaFederal + paginaCaptcha); HttpContext.Current.Session["cookies"] = _cookies; return "data:image/jpeg;base64," + Convert.ToBase64String(data, 0, data.Length); } return string.Empty; }
/// <summary> /// To be overwritten by the corresponding subclass. /// </summary> /// <param name="rq">The rq.</param> /// <param name="rp">The rp.</param> /// <remarks>Documented by Dev10, 2008-08-07</remarks> /// <remarks>Documented by Dev05, 2009-01-16</remarks> public override void OnResponse(ref HTTPRequestStruct rq, ref HTTPResponseStruct rp) { Stream responseStream; int cardId; string ContentTypeString; Side side; Guid extensionGuid; if (IsContent(rq.URL, out cardId, out side, out ContentTypeString)) { string content = (side == Side.Question) ? DequeueQuestion(cardId) : DequeueAnswer(cardId); responseStream = new MemoryStream(Encoding.Unicode.GetBytes(content)); rp.mediaStream = responseStream; rp.Headers["Content-Type"] = ContentTypeString + "; charset=UTF-16"; rp.Headers["Content-Length"] = responseStream.Length; } else if (IsExtension(rq.URL, out extensionGuid)) { if (extensionconnector.IsStreamAvailable(extensionGuid)) { responseStream = extensionconnector.GetExtensionStream(extensionGuid); } else if (parent.CurrentUser.ConnectionString.SyncType == SyncType.HalfSynchronizedWithDbAccess) { responseStream = direct_extensionconnector.GetExtensionStream(extensionGuid); } else if (parent.CurrentUser.ConnectionString.SyncType == SyncType.HalfSynchronizedWithoutDbAccess || parent.CurrentUser.ConnectionString.SyncType == SyncType.FullSynchronized) { lock (webClient) { try { responseStream = new CachingStream(webClient.DownloadData(new Uri(string.Format(parent.CurrentUser.ConnectionString.ExtensionURI, extensionGuid))), extensionGuid, extensionconnector); } catch (WebException exp) { if ((exp.Response as HttpWebResponse).StatusCode != HttpStatusCode.Forbidden) { throw exp; } string result = webClient.DownloadString(new Uri(string.Format(parent.CurrentUser.ConnectionString.ExtensionURI + "&user={1}&password={2}", -1, parent.CurrentUser.ConnectionString.ServerUser.UserName, parent.CurrentUser.ConnectionString.ServerUser.Password))); if (result != "TRUE") { throw new NoValidUserException(); } responseStream = new CachingStream(webClient.DownloadData(new Uri(string.Format(parent.CurrentUser.ConnectionString.ExtensionURI, extensionGuid))), extensionGuid, extensionconnector); } } } else { throw new ArgumentException(); } rp.mediaStream = responseStream; rp.Headers["Content-Type"] = "application/bin"; rp.Headers["Content-Length"] = responseStream.Length; } else { int mediaId = GetMediaID(rq.URL); if (connector.IsMediaAvailable(mediaId)) { responseStream = connector.GetMediaStream(mediaId, null); } else if (parent.CurrentUser.ConnectionString.SyncType == SyncType.HalfSynchronizedWithDbAccess) { responseStream = direct_connector.GetMediaStream(mediaId, connector); } else if (parent.CurrentUser.ConnectionString.SyncType == SyncType.HalfSynchronizedWithoutDbAccess || parent.CurrentUser.ConnectionString.SyncType == SyncType.FullSynchronized) { lock (webClient) { try { responseStream = new CachingStream(webClient.DownloadData(new Uri(string.Format(parent.CurrentUser.ConnectionString.LearningModuleFolder, mediaId))), mediaId, connector); } catch (WebException exp) { if ((exp.Response as HttpWebResponse).StatusCode != HttpStatusCode.Forbidden) { throw exp; } string result = webClient.DownloadString(new Uri(string.Format(parent.CurrentUser.ConnectionString.LearningModuleFolder + "&user={1}&password={2}", -1, parent.CurrentUser.ConnectionString.ServerUser.UserName, parent.CurrentUser.ConnectionString.ServerUser.Password))); if (result != "TRUE") { throw new NoValidUserException(); } responseStream = new CachingStream(webClient.DownloadData(new Uri(string.Format(parent.CurrentUser.ConnectionString.LearningModuleFolder, mediaId))), mediaId, connector); } } } else { throw new ArgumentException(); } rp.mediaStream = responseStream; ContentTypeString = connector.GetPropertyValue(mediaId, MediaProperty.MimeType); if (ContentTypeString == null) { Trace.WriteLine("MimeType delivered null, obviously the corresponding DB entry is missing..."); ContentTypeString = Helper.UnknownMimeType; } rp.Headers["Content-Type"] = ContentTypeString; rp.Headers["Content-Length"] = responseStream.Length; } }
/// <summary> /// Loads the latest Speed camera database from PocketGpsWorld /// </summary> /// <param name="username">PocketGpsWorld username</param> /// <param name="password">PocketGpsWorld password</param> /// <returns>the latest bundle of cameras</returns> /// <exception cref="WebException">Thrown if unable to login, browse to or download the file</exception> public static byte[] Load(string username, string password) { string loginAddress = "https://www.pocketgpsworld.com/modules.php?name=Your_Account"; var client = new CookieAwareWebClient { Encoding = Encoding.UTF8 }; // Post values var values = new NameValueCollection { { "username", username }, { "user_password", password }, { "op", "login" } }; ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; // Logging in string loggedInPage = Encoding.ASCII.GetString(client.UploadValues(loginAddress, values)); // Check for a positive logon error. if (loggedInPage.Contains("Login Incorrect!")) { throw new WebException("Unable to logon to PocketGpsWorld.com, check your username and password"); } // Check for not a subscriber message if (loggedInPage.Contains("not subscriber")) { throw new WebException("PocketGPSworld.com reports your not a current Subscriber, If this is incorrect, please report error 1020 to developer"); } // Check to see the download link exisits, failing this check is the first indicator // that someting has changed on the PocketGpsWorld website if (!loggedInPage.Contains("<a href=\"/modules.php?name=Cameras\" class=\"sidemenu\">Download Speed Cams</a>")) { throw new WebException("Unable to find download link at PocketGPSworld.com, Please report error 1000 to developer"); } string downloadAddress = "https://www.pocketgpsworld.com/modules.php?name=Cameras"; NameValueCollection postData = new NameValueCollection { { "op", "DownloadPackage" }, { "idPackage", "14" }, { "getPmob", "yes" }, { "getFrance", "no" }, { "getSwiss", "no" } }; // Download is preped as a temp file which the browser would normally be redirected to, need to extract the path and download that file. string html = Encoding.ASCII.GetString(client.UploadValues(downloadAddress, postData)); Regex metaRefreshRegex = new Regex("<meta http-equiv=refresh content=0;url=(.+)>\\n"); Match match = metaRefreshRegex.Match(html); if (match.Success) { return(client.DownloadData(match.Groups[1].Value)); } else { throw new WebException("Unable to find download link at PocketGPSworld.com, Please report error 1010 to developer"); } }
// Form - 시작 버튼 클릭 시 private void startButton_Clicked(object sender, EventArgs e) { if (inputId.Text.Trim().Equals("")) // 아이디 입력란이 비어있을 경우 // inputId 초기화 후 포커스 맞춤 { inputId.Text = ""; inputId.Focus(); // MessageBox 띄움 MessageBox.Show("아이디를 입력해 주세요.", "로그인 실패", MessageBoxButtons.OK, MessageBoxIcon.Warning); } else if (inputPw.Text.Trim().Equals("")) // 패스워드 입력란이 비어있을 경우 // inputPw 초기화 후 포커스 맞춤 { inputPw.Text = ""; inputPw.Focus(); // MessageBox 띄움 MessageBox.Show("패스워드를 입력해 주세요.", "로그인 실패", MessageBoxButtons.OK, MessageBoxIcon.Warning); } else { // 네트워크가 연결되어 있는지 확인 (인터넷 연결 여부는 관계없음) if (NetworkInterface.GetIsNetworkAvailable()) { // CookieAwareWebClient 생성 Web = new CookieAwareWebClient(); // CNSA net Id, Pw 저장 cnsaId = inputId.Text; cnsaPw = inputPw.Text; if (studentRadioButton.Checked) // 학생일 경우 { urlIntraNet = "http://10.1.100.32"; urlExtraNet = "https://student.cnsa.hs.kr"; } else // 선생님 || 교직원 일 경우 { urlIntraNet = "http://10.1.100.31"; urlExtraNet = "https://school.cnsa.hs.kr"; } // 사용할 큰사넷 주소 초기화 cnsaUrl = urlExtraNet; // 내부망 / 외부망 확인 스레드 생성 checkIntraNet = new Thread(CheckIntraNet); // 내부망 / 외부망 확인 시작 checkIntraNet.Start(); // CNSA net에서 Session을 받아옴 session = Encoding.UTF8.GetString(Web.DownloadData(cnsaUrl + "/login/dupLoginCheck?loginId=" + cnsaId)); // session이 존재할 경우 (로그인이 되어 있을 경우) if (!session.Trim().Equals("")) { // session 값을 저장 Web.AddCookie(new Uri(urlIntraNet), new Cookie("JSESSIONID", session)); Web.AddCookie(new Uri(urlExtraNet), new Cookie("JSESSIONID", session)); // 로그인 시도 string responseData = Encoding.UTF8.GetString(Web.UploadValues(cnsaUrl + "/login/userLogin", new NameValueCollection() { { "loginId", cnsaId }, { "loginPw", cnsaPw } })); // requestData에 특정 문자열이 포함되어 있을 경우 로그인 성공으로 간주 if (!responseData.Contains("/login/userLogin")) { // 현재 창 숨기기 this.Hide(); // Tray Icon 표시 notifyIcon.Visible = true; // Session 유지 스레드 생성 keepSession = new Thread(KeepSession); // Session 유지 시작 keepSession.Start(); // 알림 띄우기 notifyIcon.BalloonTipTitle = "Login Keeper"; notifyIcon.BalloonTipText = "CNSA Login Keeper를 시작합니다."; notifyIcon.BalloonTipIcon = ToolTipIcon.Info; notifyIcon.ShowBalloonTip(3000); // Session 유지 시작 -> openToolStripMenuItem.Text = "사용자 변경" 으로 설정 reloginToolStripMenuItem.Text = "사용자 변경"; } else // 로그인 실패 // MessageBox 띄움 { MessageBox.Show("로그인 정보가 일치하지 않습니다.", "로그인 실패", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } else // session이 존재하지 않을 경우 (로그인이 되어 있지 않을 경우) // MessageBox 띄움 { MessageBox.Show("유지할 데이터가 존재하지 않습니다.\n아이디와 패스워드 또는 현재 로그인 되어있는지를 확인해 주세요.", "알림", MessageBoxButtons.OK, MessageBoxIcon.Information); } } else { MessageBox.Show("네트워크 연결상태를 확인해 주세요.", "알림", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } }