Example #1
0
        public async Task WebSocketOptionsAreApplied()
        {
            using (StartLog(out var loggerFactory, $"{nameof(WebSocketOptionsAreApplied)}"))
            {
                // System.Net has a TransportType type which means we need to fully-qualify this rather than 'use' the namespace
                var cookieJar = new System.Net.CookieContainer();
                cookieJar.Add(new System.Net.Cookie("Foo", "Bar", "/", new Uri(_serverFixture.Url).Host));

                var hubConnection = new HubConnectionBuilder()
                                    .WithUrl(_serverFixture.Url + "/default")
                                    .WithTransport(TransportType.WebSockets)
                                    .WithLoggerFactory(loggerFactory)
                                    .WithWebSocketOptions(options => options.Cookies = cookieJar)
                                    .Build();
                try
                {
                    await hubConnection.StartAsync().OrTimeout();

                    var cookieValue = await hubConnection.InvokeAsync <string>(nameof(TestHub.GetCookieValue), new object[] { "Foo" }).OrTimeout();

                    Assert.Equal("Bar", cookieValue);
                }
                catch (Exception ex)
                {
                    loggerFactory.CreateLogger <HubConnectionTests>().LogError(ex, "{ExceptionType} from test", ex.GetType().FullName);
                    throw;
                }
                finally
                {
                    await hubConnection.DisposeAsync().OrTimeout();
                }
            }
        }
		private System.Net.CookieContainer ParseCookieSettings(string line)
		{
			System.Net.CookieContainer container = new System.Net.CookieContainer();

			// クッキー情報の前についているよくわからないヘッダー情報を取り除く
			// 対象:
			//  \\xと2桁の16進数値
			//  \\\\
			//  \がない場合の先頭1文字
			string matchPattern = "^(\\\\x[0-9a-fA-F]{2})|^(\\\\\\\\)|^(.)|[\"()]";
			System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(matchPattern, System.Text.RegularExpressions.RegexOptions.Compiled);

			string[] blocks = line.Split(new string[] { "\\0\\0\\0" }, StringSplitOptions.RemoveEmptyEntries);
			foreach (string block in blocks) {
				if (block.Contains("=") && block.Contains("domain")) {
					string header = reg.Replace(block, "");
					System.Net.Cookie cookie = ParseCookie(header);
					if (cookie != null) {
						try {
							container.Add(cookie);
						} catch(Exception ex) {
							CookieGetter.Exceptions.Enqueue(ex);
						}
					}
				}
			}

			return container;
		}
Example #3
0
        public static async Task <bool> TryRenewOsuCookies()
        {
            try // try renew
            {
                System.Net.CookieContainer _cookies = await Osu.LoginAndGetCookie(SettingManager.Get("officialOsuUsername"), SettingManager.Get("officialOsuPassword"));

                Properties.Settings.Default.officialOsuCookies = await Osu.SerializeCookies(_cookies);

                Osu.Cookies = _cookies;
                Properties.Settings.Default.Save(); // success
                return(true);
            }
            catch (Osu.InvalidPasswordException)
            {
                MessageBoxResult fallback = MessageBox.Show("It seems like your osu! login password has changed. Press yes to fallback the session to Bloodcat for now and you can go update your password, or press no to permanently use Bloodcat. You will have to retry the download again either way.", "NexDirect - Download Error", MessageBoxButton.YesNo, MessageBoxImage.Error);
                if (fallback == MessageBoxResult.Yes)
                {
                    // just fallback
                    SettingManager.Set("useOfficialOsu", false, true);
                    SettingManager.Set("fallbackActualOsu", true, true);
                    return(false);
                }
                else
                {
                    // disable perma
                    SettingManager.Set("useOfficialOsu", false);
                    SettingManager.Set("officialOsuCookies", null);
                    SettingManager.Set("officialOsuUsername", "");
                    SettingManager.Set("officialOsuPassword", "");
                    return(false);
                }
            }
        }
Example #4
0
        //验证订单
        public string CheckOrderInfoEx(System.Net.CookieContainer cookie)
        {
            var webrequest = new WebRequestHelper(Properties.Resources.otn_checkOrderInfo,
                                                  Properties.Resources.otn_initDc, "POST", _postdata, cookie);

            return(webrequest.SendDataToServer());
        }
        /// <summary>
        /// 添加 群组里的群组成员 好友
        /// </summary>
        /// <param name="info">添加 的信息</param>
        /// <param name="myCookiesContainer">Cookie</param>
        /// <param name="wxorwx2">新老微信标识 老微信 1 新微信 2</param>
        /// <returns></returns>
        public JObject AddGroupUser(AddGroupUser info, System.Net.CookieContainer myCookiesContainer, int wxorwx2)
        {
            string url = "https://wx2.qq.com/cgi-bin/mmwebwx-bin/webwxverifyuser?r=" + info.R + "&lang=zh_CN&pass_ticket="
                         + info.pass_ticket;

            if (wxorwx2 == 1)//老微信
            {
                url = "https://wx.qq.com/cgi-bin/mmwebwx-bin/webwxverifyuser?r=" + info.R + "&lang=zh_CN&pass_ticket=" + info.pass_ticket;
            }
            JObject job      = null;
            string  postdate = String.Empty;
            string  add1     = "{\"BaseRequest\":{\"Uin\":" + info.Uin + ",\"Sid\":\"" + info.Sid + "\",\"Skey\":\"" + info.Skey + "\",";
            string  add2     = "\"DeviceID\":\"" + info.DeviceID + "\"},\"Opcode\":2,\"VerifyUserListSize\":1,\"VerifyUserList\":";
            string  add3     = "[{\"Value\":\"" + info.Value + "\",\"VerifyUserTicket\":\"\"}],";
            string  add4     = "\"VerifyContent\":\"" + info.VerifyContent + "\",\"SceneListCount\":1,\"SceneList\":[33],\"skey\":\"" + info.Skey + "\"}";

            postdate = add1 + add2 + add3 + add4;
            if (wxorwx2 == 1)
            {
                job = WXService.SendPostRequest_Old(url, postdate, myCookiesContainer);
            }
            else
            {
                job = WXService.SendPostRequest(url, postdate, myCookiesContainer);
            }
            return(job);
        }
Example #6
0
 public byte[] GetClavePublica(byte[] ClavePublicaCliente, System.Net.CookieContainer cookie)
 {
     //this.SeguridadCP.AplicarSeguridadCP();
     byte[] bytRetorno = obj.GetClavePublica(ClavePublicaCliente, cookie);
     //this.SeguridadCP.UndoAplicarSeguridadCP();
     return(bytRetorno);
 }
Example #7
0
        public static string ConvertUrl(string _pdata)
        {
            /*
             * Cookie常用的几种处理方式:
             * new XJHTTP().UpdateCookie("旧Cookie", "请求后的Cookie");//合并Cookie,将cookie2与cookie1合并更新 返回字符串类型Cookie
             * new XJHTTP().StringToCookie("网站Domain", "字符串Cookie内容");//将文字Cookie转换为CookieContainer 对象
             * new XJHTTP().CookieTostring("CookieContainer 对象");//将 CookieContainer 对象转换为字符串类型
             * new XJHTTP().GetAllCookie("CookieContainer 对象");//得到CookieContainer中的所有Cookie对象集合,返回List<Cookie>
             * new XJHTTP().GetCookieByWininet("网站Url");//从Wininet 中获取字符串Cookie 可获取IE与Webbrowser控件中的Cookie
             * new XJHTTP().GetAllCookieByHttpItems("请求设置对象");//从请求设置对象中获取Cookie集合,返回List<Cookie>
             * new XJHTTP().ClearCookie("需要处理的字符串Cookie");//清理string类型Cookie.剔除无用项返回结果为null时遇见错误.
             * new XJHTTP().SetIeCookie("设置Cookie的URL", "需要设置的Cookie");//可设置IE/Webbrowser控件Cookie
             * new XJHTTP().CleanAll();//清除IE/Webbrowser所有内容 (注意,调用本方法需要管理员权限运行) CleanHistory();清空历史记录  CleanCookie(); 清空Cookie CleanTempFiles(); 清空临时文件
             */
            string url   = "dwz.cn/create.php";                               //请求地址
            string res   = string.Empty;                                      //请求结果,请求类型不是图片时有效
            string pdata = "url=" + _pdata;                                   //提交数据(必须项)

            System.Net.CookieContainer cc = new System.Net.CookieContainer(); //自动处理Cookie对象
            HttpHelpers helper            = new HttpHelpers();                //发起请求对象
            HttpItems   items             = new HttpItems();                  //请求设置对象
            HttpResults hr = new HttpResults();                               //请求结果

            items.URL       = url;                                            //设置请求地址
            items.Container = cc;                                             //自动处理Cookie时,每次提交时对cc赋值即可
            items.Postdata  = pdata;                                          //提交的数据
            items.Method    = "Post";                                         //设置请求类型为Post方式(默认为Get方式)
            hr  = helper.GetHtml(items);                                      //发起请求并得到结果
            res = hr.Html;                                                    //得到请求结果
            return(res);
        }
Example #8
0
        /// <summary>
        /// 从数网获取订单
        /// </summary>
        /// <param name="merchantID">商户编号</param>
        /// <param name="key">商户密码</param>
        /// <param name="url">接口地址</param>
        /// <param name="count">订单数量</param>
        /// <returns></returns>
        public List <Order> getOrderFromSW(ref int getOrderTime)
        {
            getOrderTime = time;

            List <Order> orderSet = new List <Order>();

            try
            {
                string sign     = Md5Helper.MD5Encrypt(merchantID + key);
                string postData = string.Format("MerchantID={0}&Count={1}&Sign={2}", merchantID, count, sign);


                System.Net.CookieContainer cookie = new System.Net.CookieContainer();

                string result = PostAndGet.HttpGetString(getOrderurl, postData, ref cookie);

                WriteLog.Write("方法:getOrderFromSW 获取订单信息:" + result, LogPathFile.Other);

                if (result.Contains("获取成功"))
                {
                    assignmentOrder(orderSet, result);
                }
            }
            catch (Exception ex)
            {
                WriteLog.Write("方法:getOrderFromSW异常,信息:" + ex.Message + ex.StackTrace, LogPathFile.Exception);
            }

            return(orderSet);
        }
Example #9
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="longurl">长链接</param>
        public static string GetShort(string longurl)
        {
            /*
             * Cookie常用的几种处理方式:
             * new XJHTTP().UpdateCookie("旧Cookie", "请求后的Cookie");//合并Cookie,将cookie2与cookie1合并更新 返回字符串类型Cookie
             * new XJHTTP().StringToCookie("网站Domain", "字符串Cookie内容");//将文字Cookie转换为CookieContainer 对象
             * new XJHTTP().CookieTostring("CookieContainer 对象");//将 CookieContainer 对象转换为字符串类型
             * new XJHTTP().GetAllCookie("CookieContainer 对象");//得到CookieContainer中的所有Cookie对象集合,返回List<Cookie>
             * new XJHTTP().GetCookieByWininet("网站Url");//从Wininet 中获取字符串Cookie 可获取IE与Webbrowser控件中的Cookie
             * new XJHTTP().GetAllCookieByHttpItems("请求设置对象");//从请求设置对象中获取Cookie集合,返回List<Cookie>
             * new XJHTTP().ClearCookie("需要处理的字符串Cookie");//清理string类型Cookie.剔除无用项返回结果为null时遇见错误.
             * new XJHTTP().SetIeCookie("设置Cookie的URL", "需要设置的Cookie");//可设置IE/Webbrowser控件Cookie
             * new XJHTTP().CleanAll();//清除IE/Webbrowser所有内容 (注意,调用本方法需要管理员权限运行) CleanHistory();清空历史记录  CleanCookie(); 清空Cookie CleanTempFiles(); 清空临时文件
             */
            string url = "http://api.t.sina.com.cn/short_url/shorten.json?source=4257120060&url_long=" + Encode.UrlEncode(longurl); //请求地址
            string res = string.Empty;                                                                                              //请求结果,请求类型不是图片时有效

            System.Net.CookieContainer cc = new System.Net.CookieContainer();                                                       //自动处理Cookie对象
            HttpHelpers helper            = new HttpHelpers();                                                                      //发起请求对象
            HttpItems   items             = new HttpItems();                                                                        //请求设置对象
            HttpResults hr = new HttpResults();                                                                                     //请求结果

            items.URL       = url;                                                                                                  //设置请求地址
            items.Container = cc;                                                                                                   //自动处理Cookie时,每次提交时对cc赋值即可
            hr  = helper.GetHtml(items);                                                                                            //发起请求并得到结果
            res = hr.Html;                                                                                                          //得到请求结果
            return(res);
        }
        /**
         * Scan is done asynchronously and each scan request is tracked by data id of which result can be retrieved by API Fetch Scan Result.
         *
         * @see <a href="http://software.opswat.com/metascan/Documentation/Metascan_v4/documentation/user_guide_metascan_developer_guide_scan_file.html" target="_blank">REST API doc</a>
         *
         * @param inputStream Stream of data (file) to scan. Required
         * @param fileScanOptions Optional file scan options. Can be NULL.
         * @return unique data id for this file scan
         */
        public string ScanFile(Stream inputStream, FileScanOptions fileScanOptions, out string coreId, long contentLength = 0)
        {
            //if (inputStream == null)
            //{
            //    throw new MetadefenderClientException("Stream cannot be null");
            //}

            if ((fileScanOptions != null && fileScanOptions.GetUserAgent() == null) && user_agent != null)
            {
                fileScanOptions.SetUserAgent(user_agent);
            }

            if (fileScanOptions == null && user_agent != null)
            {
                fileScanOptions = new FileScanOptions().SetUserAgent(user_agent);
            }

            Dictionary <string, string> headers = (fileScanOptions == null) ? null : fileScanOptions.GetOptions();

            cookieContainer = new System.Net.CookieContainer();

            HttpConnector.HttpResponse response =
                httpConnector.SendRequest(apiEndPointUrl + "/file", "POST", inputStream, headers, contentLength, cookieContainer);

            coreId = apiEndPointUrl;
            if (response.responseCode == 200)
            {
                try
                {
                    Responses.ScanRequest scanRequest = JsonConvert.DeserializeObject <Responses.ScanRequest>(response.response);
                    if (scanRequest != null)
                    {
                        if (cookieContainer.Count > 0)
                        {
                            foreach (System.Net.Cookie cookie in response.cookieContainer.GetCookies(new Uri(apiEndPointUrl)))
                            {
                                coreId = cookie.Value;
                            }
                        }

                        return(scanRequest.data_id);
                    }
                    else
                    {
                        ThrowRequestError(response);
                        return(null);
                    }
                }
                catch (JsonSerializationException)
                {
                    ThrowRequestError(response);
                    return(null);
                }
            }
            else
            {
                ThrowRequestError(response);
                return(null);
            }
        }
Example #11
0
        public static async Task Main(string[] args)
        {
            var cookie = new System.Net.CookieContainer();

            using (var handler = new HttpClientHandler()
            {
                CookieContainer = cookie
            })
                using (var client = new HttpClient(handler))
                {
                    client.DefaultRequestHeaders.UserAgent.ParseAdd("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36");
                    client.BaseAddress = new Uri($"{args[1]}/index.php");

                    cookie.Add(new Uri(args[1]), new System.Net.Cookie("id", args[2]));

                    foreach (var data in GetData())
                    {
                        foreach (var key in data.Keys)
                        {
                            Console.WriteLine($"{DateTime.Now}: {data.Dir} - '{key}'. Start.");
                            await LoadVideo(client, key, data.Dir);

                            Console.WriteLine($"{DateTime.Now}: {data.Dir} - '{key}'. End.");
                            await Task.Delay(10000);
                        }
                    }
                }
        }
        public UserProfileService(ClientContext context, string siteUrl = "") : this()
        {
            if (string.IsNullOrEmpty(siteUrl))
            {
                if (!context.Site.IsPropertyAvailable(sctx => sctx.Url))
                {
                    context.Site.EnsureProperties(sctx => sctx.Url);
                    siteUrl = context.Site.Url;
                }
            }

            var trailingSiteUrl = siteUrl.EnsureTrailingSlashLowered();

            OWService = new OfficeDevPnP.Core.UPAWebService.UserProfileService
            {
                Url                   = $"{trailingSiteUrl}_vti_bin/userprofileservice.asmx",
                Credentials           = context.Credentials,
                UseDefaultCredentials = false
            };


            if (context.Credentials is SharePointOnlineCredentials)
            {
                var spourl     = new Uri(siteUrl);
                var newcreds   = (SharePointOnlineCredentials)context.Credentials;
                var spocookies = newcreds.GetAuthenticationCookie(spourl);

                var cookieContainer = new System.Net.CookieContainer();
                cookieContainer.SetCookies(spourl, spocookies);
                OWService.CookieContainer = cookieContainer;
            }
        }
Example #13
0
        public override void SendNoWait()
        {
            var cookie = new System.Net.CookieContainer();

            cookie.Add(new Uri(Endpoint.IP), Message.Cookie);
            HttpClient.SendAsync(Message.Verb, Endpoint.IP, Message, HttpClient.CONTENTTYPE, cookie);
        }
Example #14
0
        public Boolean LoginOut()
        {
            string response = DownloadString("https://m.facebook.com/");

            HtmEle.LoadHtml(response);

            //If HtmEle.DocumentNode.SelectNodes("//table//tr") Is Nothing Then Return False
            if (HtmEle.DocumentNode.SelectNodes("//a") is null)
            {
                return(false);
            }

            foreach (HtmlNode element in HtmEle.DocumentNode.SelectNodes("//a"))
            {
                if (element.InnerText.Contains("登出"))
                {
                    string url = element.GetAttributeValue("href", "false");
                    if (url != "false")
                    {
                        url      = "https://m.facebook.com" + UrlTransfer(url);
                        response = DownloadString(url);
                    }
                    break;
                }
            }
            CookieContainer = new System.Net.CookieContainer();
            return(false);
        }
Example #15
0
        public async Task WebSocketOptionsAreApplied()
        {
            using (StartServer <Startup>(out var server))
            {
                // System.Net has a HttpTransportType type which means we need to fully-qualify this rather than 'use' the namespace
                var cookieJar = new System.Net.CookieContainer();
                cookieJar.Add(new System.Net.Cookie("Foo", "Bar", "/", new Uri(server.Url).Host));

                var hubConnection = new HubConnectionBuilder()
                                    .WithLoggerFactory(LoggerFactory)
                                    .WithUrl(server.Url + "/default", HttpTransportType.WebSockets, options =>
                {
                    options.WebSocketConfiguration = o => o.Cookies = cookieJar;
                })
                                    .Build();
                try
                {
                    await hubConnection.StartAsync().OrTimeout();

                    var cookieValue = await hubConnection.InvokeAsync <string>(nameof(TestHub.GetCookieValue), "Foo").OrTimeout();

                    Assert.Equal("Bar", cookieValue);
                }
                catch (Exception ex)
                {
                    LoggerFactory.CreateLogger <HubConnectionTests>().LogError(ex, "{ExceptionType} from test", ex.GetType().FullName);
                    throw;
                }
                finally
                {
                    await hubConnection.DisposeAsync().OrTimeout();
                }
            }
        }
 public string RecuperarNombreDominio(System.Net.CookieContainer cookie)
 {
     Fachada.Seguridad.IniciarSesion.wsInicioSesion objAux = new Fachada.Seguridad.IniciarSesion.wsInicioSesion();
     objAux.CookieContainer = cookie;
     objAux.Timeout         = System.Threading.Timeout.Infinite;
     return(objAux.RecuperarNombreDominio());
 }
Example #17
0
 private static void SetAuthenticationCookies(HttpClientHandler handler, ClientContext context)
 {
     context.Web.EnsureProperty(w => w.Url);
     if (context.Credentials is SharePointOnlineCredentials spCred)
     {
         handler.Credentials = context.Credentials;
         handler.CookieContainer.SetCookies(new Uri(context.Web.Url), spCred.GetAuthenticationCookie(new Uri(context.Web.Url)));
     }
     else if (context.Credentials == null)
     {
         var cookieString         = CookieReader.GetCookie(context.Web.Url).Replace("; ", ",").Replace(";", ",");
         var authCookiesContainer = new System.Net.CookieContainer();
         // Get FedAuth and rtFa cookies issued by ADFS when accessing claims aware applications.
         // - or get the EdgeAccessCookie issued by the Web Application Proxy (WAP) when accessing non-claims aware applications (Kerberos).
         IEnumerable <string> authCookies = null;
         if (Regex.IsMatch(cookieString, "FedAuth", RegexOptions.IgnoreCase))
         {
             authCookies = cookieString.Split(',').Where(c => c.StartsWith("FedAuth", StringComparison.InvariantCultureIgnoreCase) || c.StartsWith("rtFa", StringComparison.InvariantCultureIgnoreCase));
         }
         else if (Regex.IsMatch(cookieString, "EdgeAccessCookie", RegexOptions.IgnoreCase))
         {
             authCookies = cookieString.Split(',').Where(c => c.StartsWith("EdgeAccessCookie", StringComparison.InvariantCultureIgnoreCase));
         }
         if (authCookies != null)
         {
             authCookiesContainer.SetCookies(new Uri(context.Web.Url), string.Join(",", authCookies));
         }
         handler.CookieContainer = authCookiesContainer;
     }
 }
Example #18
0
        private bool HardDeleteNextUserBatch(string alias, string username, string password, int batchSize, bool testMode, bool useFastDelete, out string result)
        {
            result = null;
            bool   retVal = false;
            string url    = DnnRequest.GetUrl(alias, "Dnn_BulkUserDelete", "BulkUserDelete", "HardDeleteNextUsers", false);

            System.Net.HttpStatusCode  statusCode; string errorMsg;
            System.Net.CookieContainer cookies = new System.Net.CookieContainer();
            //really should use a string format here to build the JSON but quick and dirty does the job
            string requestBody = "{ 'actionName' : 'hardDelete', 'actionNumber' : " + batchSize.ToString() + ", 'testRun': '" + testMode.ToString() + "', 'useFastDelete': '" + useFastDelete.ToString() + "'}";

            //post the request to delete the batch of users
            result = DnnRequest.PostRequest(url, username, password, requestBody, ContentType.JSON, out statusCode, out errorMsg, ref cookies);
            result = ReturnResult(url, statusCode, errorMsg, result);
            if (statusCode == System.Net.HttpStatusCode.OK)
            {
                //get the call return value form the return JSON
                if (string.IsNullOrEmpty(result) == false)
                {
                    var jsonResult = Newtonsoft.Json.Linq.JObject.Parse(result);
                    retVal = bool.Parse(jsonResult["Success"].ToString());
                }
            }
            return(retVal);
        }
Example #19
0
        private HttpClient NewHttpClient(System.Net.CookieContainer cookies = null)
        {
            HttpClientHandler handler = new HttpClientHandler()
            {
                UseDefaultCredentials  = true,
                AutomaticDecompression = System.Net.DecompressionMethods.Deflate | System.Net.DecompressionMethods.GZip
            };

            if (cookies != null)
            {
                handler.UseCookies      = true;
                handler.CookieContainer = cookies;
            }

            var client = new HttpClient(handler)
            {
                BaseAddress = new Uri(Url)
            };

            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            if (!String.IsNullOrEmpty(Token))
            {
                client.DefaultRequestHeaders.Add("Authorization-Token", Token);
            }

            return(client);
        }
Example #20
0
        /// <summary>
        /// Gets the URI cookie container.
        /// </summary>
        /// <param name="uri">The URI.</param>
        /// <returns></returns>
        public static System.Net.CookieContainer GetUriCookieContainer(Uri uri)
        {
            System.Net.CookieContainer cookies = null;
            // Determine the size of the cookie
            int           datasize   = 8192 * 16;
            StringBuilder cookieData = new StringBuilder(datasize);

            if (!InternetGetCookieEx(uri.ToString(), null, cookieData, ref datasize, InternetCookieHttponly, IntPtr.Zero))
            {
                if (datasize < 0)
                {
                    return(null);
                }
                // Allocate stringbuilder large enough to hold the cookie
                cookieData = new StringBuilder(datasize);
                if (!InternetGetCookieEx(
                        uri.ToString(),
                        null, cookieData,
                        ref datasize,
                        InternetCookieHttponly,
                        IntPtr.Zero))
                {
                    return(null);
                }
            }
            if (cookieData.Length > 0)
            {
                cookies = new System.Net.CookieContainer();
                cookies.SetCookies(uri, cookieData.ToString().Replace(';', ','));
            }
            return(cookies);
        }
Example #21
0
 public static string GetUrltoHtml(string Url, string type = "UTF-8")
 {
     try
     {
         System.Net.HttpWebRequest r = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(Url);
         r.AllowAutoRedirect = true;
         r.KeepAlive         = false;
         r.ServicePoint.Expect100Continue = false;
         r.ServicePoint.UseNagleAlgorithm = false;
         r.ServicePoint.ConnectionLimit   = 65500;
         r.AllowWriteStreamBuffering      = false;
         r.Proxy = null;
         System.Net.CookieContainer c = new System.Net.CookieContainer();
         r.CookieContainer = c;
         System.Net.HttpWebResponse res = r.GetResponse() as System.Net.HttpWebResponse;
         System.IO.StreamReader     s   = new System.IO.StreamReader(res.GetResponseStream(), System.Text.Encoding.GetEncoding(type));
         string retsult = s.ReadToEnd();
         res.Close();
         r.Abort();
         return(retsult);
     }
     catch (System.Exception ex)
     {
         //errorMsg = ex.Message;
         return(ex.Message);
     }
 }
Example #22
0
        private void FrmInterfaceTest_Load(object sender, EventArgs e)
        {
            cookie = new System.Net.CookieContainer();

            cBmethod.Items.Add(new App.ValTxt("POST", "POST"));
            cBmethod.Items.Add(new App.ValTxt("GET", "GET"));
            cBmethod.SelectedIndex = 0;

            cBencode.Items.Add(new App.ValTxt("utf-8", "utf-8"));
            cBencode.Items.Add(new App.ValTxt("gb2312", "gb2312(简体中文)"));
            cBencode.Items.Add(new App.ValTxt("big5", "big5(繁体中文)"));
            cBencode.SelectedIndex = 0;

            cBcontype.Items.Add(new App.ValTxt("application/json;charset=utf-8", "application/json;charset=utf-8"));
            cBcontype.Items.Add(new App.ValTxt("application/x-www-form-urlencoded;charset=utf-8", "application/x-www-form-urlencoded;charset=utf-8"));
            cBcontype.Items.Add(new App.ValTxt("text/xml", "text/xml"));
            cBcontype.SelectedIndex = 0;

            cBuncode.Items.Add(new App.ValTxt("0", "不解码"));
            cBuncode.Items.Add(new App.ValTxt("1", "escape解码"));
            cBuncode.Items.Add(new App.ValTxt("2", "Url解码(UrlDecode)"));
            cBuncode.Items.Add(new App.ValTxt("3", "encodeURIComponent 解码"));
            cBuncode.SelectedIndex = 1;

            cBformat.Items.Add(new App.ValTxt("0", "不格式化"));
            cBformat.Items.Add(new App.ValTxt("1", "JSON格式化"));
            cBformat.SelectedIndex = 1;
        }
Example #23
0
        public string ObtenerAlmacen(string usuario, string password)
        {
            string resultado = "";

            try
            {
                using (AlmacenCentralPiaguiServiceReference.wsAlmacenCentral servicioWeb = new AlmacenCentralPiaguiServiceReference.wsAlmacenCentral())
                {
                    System.Net.CookieContainer cookie = new System.Net.CookieContainer();
                    servicioWeb.CookieContainer = cookie;

                    //Conectamos con el servicio web
                    if (servicioWeb.Login(usuario, password) == true)
                    {
                        //Obtenemos el almacén
                        XmlNode xml = servicioWeb.getInventario("");
                        xml       = xml.ChildNodes[0].ChildNodes[0];
                        resultado = xml["Almacen"].InnerText;
                    }
                    else
                    {
                        resultado = "";
                    }
                }
            }
            catch (Exception ex)
            {
                resultado = "";
            }
            return(resultado);
        }
Example #24
0
        void PopulateSessionCookie()
        {
            //Already session cookie is populated.
            if (this.SessionCookieContainer != null)
            {
                return;
            }

            //Map of Session - CookieContainer is populated in RootActvity.
            Activity rootActivity = (Activity)GetRootActivity();
            Dictionary <String, System.Net.CookieContainer> sessionCookieContainers;

            System.Net.CookieContainer cookieContainer;

            sessionCookieContainers = (Dictionary <String, System.Net.CookieContainer>)rootActivity.GetValue(SessionCookieMapProperty);

            if (sessionCookieContainers == null)
            {
                sessionCookieContainers = new Dictionary <String, System.Net.CookieContainer>();
                rootActivity.SetValue(SessionCookieMapProperty, sessionCookieContainers);
                cookieContainer = new System.Net.CookieContainer();
                sessionCookieContainers.Add(SessionId, cookieContainer);
            }
            else
            {
                if (!sessionCookieContainers.TryGetValue(SessionId, out cookieContainer))
                {
                    cookieContainer = new System.Net.CookieContainer();
                    sessionCookieContainers.Add(SessionId, cookieContainer);
                }
            }
            this.SessionCookieContainer = cookieContainer;
        }
Example #25
0
 public ServerConnection(string url)
 {
     using(Log.Scope("ServerConnection constructor"))
     {
         Log.Debug("connecting to {0}", url);
         try
         {
             if(_instance != null)
             {
                 _instance.Dispose();
                 _instance = null;
             }
         }
         catch { }
         if(url == null)
             throw new ArgumentNullException("url");
         _url = url;
         this.Server = new LPSClientShared.LPSServer.Server(url);
         this.Server.CookieContainer = CookieContainer;
         this.cached_datasets = new Dictionary<string, DataSet>();
         _instance = this;
         resource_manager = new ResourceManager(this);
         configuration_store = new ConfigurationStore();
     }
 }
Example #26
0
        public static HtmlNode Get(string url, System.Net.CookieContainer cookies)
        {
            var html = Http.Get(url, cookies);
            var doc  = Html.Parse(html);

            return(doc);
        }
 public byte[] GetClavePublica(byte[] ClavePublicaCliente, System.Net.CookieContainer cookie)
 {
     Fachada.Seguridad.IniciarSesion.wsInicioSesion objAux = new Fachada.Seguridad.IniciarSesion.wsInicioSesion();
     objAux.CookieContainer = cookie;
     objAux.Timeout         = System.Threading.Timeout.Infinite;
     return(objAux.GetClavePublica(ClavePublicaCliente));
 }
Example #28
0
        private static string GetToken(int Project_ID)
        {
            System.Collections.Specialized.NameValueCollection pD1 = new System.Collections.Specialized.NameValueCollection();
            pD1.Add("ref", "bug_report_page.php");
            pD1.Add("project_id", Project_ID.ToString().Trim());
            pD1.Add("make_default", string.Empty);
            WebClientEx httpToken = new WebClientEx();

            cJar = new System.Net.CookieContainer();
            httpToken.KeepAlive   = false;
            httpToken.CookieJar   = cJar;
            httpToken.SendHeaders = new System.Net.WebHeaderCollection();
            httpToken.SendHeaders.Add(System.Net.HttpRequestHeader.Referer, "http://bugs.realityripple.com/login_select_proj_page.php?bug_report_page.php");
            string sTok = httpToken.UploadValues("http://bugs.realityripple.com/set_project.php", "POST", pD1);

            if (sTok.StartsWith("Error: "))
            {
                return(null);
            }
            if (sTok.Contains("bug_report_token"))
            {
                sTok = sTok.Substring(sTok.IndexOf("bug_report_token") + 25);
                sTok = sTok.Substring(0, sTok.IndexOf("\"/"));
                return(sTok);
            }
            else
            {
                return(null);
            }
        }
 public PassRzdRuClient(IOptions <Config> configAccessor, ILogger <PassRzdRuClient> logger)
 {
     _config          = configAccessor.Value;
     _log             = logger;
     _cookieContainer = new System.Net.CookieContainer();
     _sessionUri      = new System.Uri("https://pass.rzd.ru");
 }
Example #30
0
        /// <summary>
        /// HD streaming from laola1.tv
        /// http://streamaccess.unas.tv/hdflash/1/hdlaola1_70429.xml?streamid=70429&partnerid=1&quality=hdlive&t=.smil
        /// This streaming type is used for many major sport events (e.g. soccer games, ice hockey, etc.)
        /// </summary>
        /// <param name="video">Video object</param>
        /// <param name="playkey1">Playkey1 for this video</param>
        /// <param name="playkey2">Playkey2 for this video</param>
        /// <returns>Url for streaming</returns>
        private string GetHdStreamingUrl(VideoInfo video, String data)
        {
            //TODO: this isn't working yet. MediaPortal doesn't play the stream for some reason.
            //Downloading works though and the file can be played after that.

            Match c = regEx_GetLiveHdPlaykeys.Match(data);

            if (c.Success)
            {
                String streamAccess = c.Groups["streamaccess"].Value;
                String streamId     = c.Groups["streamid"].Value;
                String flashPlayer  = c.Groups["flashplayer"].Value + ".swf";
                //String flashVersion = c.Groups["flashversion"].Value;

                //String playData = GetWebData(String.Format("http://streamaccess.laola1.tv/hdflash/1/hdlaola1_{0}.xml?streamid={1}&partnerid=1&quality=hdlive&t=.smil", playkey1, playkey1));

                System.Net.CookieContainer container = new System.Net.CookieContainer();
                String playData = GetWebData(streamAccess, cookies: container);
                Match  baseUrls = regEx_GetLiveHdBaseUrls.Match(playData);
                Match  sources  = regEx_GetLiveHdSources.Match(playData);

                //TODO: don't rely on the fact, the the quality is sorted (first item = worst quality, third = best)
                if (videoQuality == VideoQuality.Medium)
                {
                    sources = sources.NextMatch();
                }
                else if (videoQuality == VideoQuality.High)
                {
                    sources = sources.NextMatch().NextMatch();
                }


                String httpUrl = baseUrls.Groups["httpbase"].Value + sources.Groups["src"].Value;// +"&v=2.6.6&fp=WIN%2011,1,102,62&r=" + GetHdLiveRandomString(5) + "&g=" + GetHdLiveRandomString(12);
                httpUrl = httpUrl.Replace("amp;", "");
                httpUrl = httpUrl.Replace("e=&", "e=" + streamId + "&");
                httpUrl = httpUrl.Replace("p=&", "p=1&");

                /*String rtmpUrl = String.Format("rtmp://{0}:1935/{1}?_fcs_vhost={2}/{3}?auth={4}&p=1&e={5}&u=&t=livevideo&l=&a=&aifp={6}", ip, servertype, url, stream, auth, playkey1, aifp);
                 * //Log.Info("RTMP Url: " + rtmpUrl);
                 * String playpath = ReverseProxy.Instance.GetProxyUri(RTMP_LIB.RTMPRequestHandler.Instance,
                 *      string.Format("http://127.0.0.1/stream.flv?rtmpurl={0}&swfVfy={1}&live={2}",
                 *      System.Web.HttpUtility.UrlEncode(rtmpUrl),
                 *      System.Web.HttpUtility.UrlEncode("true"),
                 *      System.Web.HttpUtility.UrlEncode("true")
                 *      ));
                 * String playpath = string.Format("{0}&swfVfy={1}&live={2}",
                 *      rtmpUrl,
                 *      System.Web.HttpUtility.UrlEncode("true"),
                 *      System.Web.HttpUtility.UrlEncode("true")
                 *      );*/

                //String playpath = ReverseProxy.Instance.GetProxyUri(this, httpUrl);
                MPUrlSourceFilter.HttpUrl url = new MPUrlSourceFilter.HttpUrl(httpUrl);
                //url.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3";
                url.Cookies.Add(container.GetCookies(new Uri(streamAccess)));
                return(url.ToString());
            }
            return(null);
        }
 public IBetSubEngine(string host, string dynamicURL, string setCookie, System.Net.CookieContainer cookies)
 {
     this._host = host;
     this._setCookie = setCookie;
     this._dynamicURL = dynamicURL;
     this._cookies = cookies;
     this.InitializeObjects();
 }
Example #32
0
        //获取联系人信息
        public void GetPassengersAll(Action <string> callback, System.Net.CookieContainer cookie)
        {
            WebRequestHelper webHelper = new WebRequestHelper(Properties.Resources.confirmPassengerAction_getpassengerJson, Properties.Resources.confirmPassengerAction_init, "POST", "", cookie);

            webHelper.SendDataToServer((str) => {
                callback(str);
            });
        }
Example #33
0
        public WebClientEx(System.Net.CookieContainer container)
        {
            this.container = container;

            this.Headers.Add("Accept-Language", "de-CH,de;q=0.9");
            this.Headers.Add("pragma", "no-cache");
            this.Headers.Add("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36");
        }
 public MainWindow()
 {
     InitializeComponent();
     
     var cookie = new System.Net.CookieContainer();
     SunokoLibrary.Nicovideo.Net.PrimitiveLibrary.Login("userid", "pass", cookie);
     var cInfo = new ContentInfo("sm9", cookie);
     var comme = cInfo.MovieInfo.GetCommentContainer(-10);
 }
Example #35
0
		protected virtual System.Net.CookieContainer GetCookies(string path, string query)
		{
			if (path == null || !System.IO.File.Exists(path)) {
				throw new CookieGetterException("クッキーパスが正しく設定されていません。");
			}

			System.Net.CookieContainer container = new System.Net.CookieContainer();

			string temp = null;

			try {
				temp = System.IO.Path.GetTempFileName();
				System.IO.File.Copy(path, temp, true);

				using (SQLiteConnection sqlConnection = new SQLiteConnection(string.Format(CONNECTIONSTRING_FORMAT, temp))) {
					sqlConnection.Open();

					SQLiteCommand command = sqlConnection.CreateCommand();
					command.Connection = sqlConnection;
					command.CommandText = query;
					SQLiteDataReader sdr = command.ExecuteReader();

					while (sdr.Read()) {
						List<object> items = new List<object>();

						for (int i = 0; i < sdr.FieldCount; i++) {
							items.Add(sdr[i]);
						}

						System.Net.Cookie cookie = DataToCookie(items.ToArray());
						try {
							Utility.AddCookieToContainer(container, cookie);
						} catch (Exception ex){
							CookieGetter.Exceptions.Enqueue(ex);
							Console.WriteLine(string.Format("Invalid Format! domain:{0},key:{1},value:{2}", cookie.Domain, cookie.Name, cookie.Value));
						}

					}

					sqlConnection.Close();
				}

			} catch (Exception ex) {
				throw new CookieGetterException("クッキーを取得中、Sqliteアクセスでエラーが発生しました。", ex);
			} finally {
				if (temp != null) {
					System.IO.File.Delete(temp);
				}
			}

			return container;
		}
 public UserManager()
 {
     CookieContainer = new System.Net.CookieContainer();
     string urlSetting = ConfigurationManager.AppSettings["UserManager"];
     if (urlSetting != null)
     {
         Url = urlSetting;
     }
     else
     {
         Trace.TraceWarning("No URL was found in application configuration file");
     }
 }
Example #37
0
 public TrainDeatils(System.Net.CookieContainer cookieContainer,string title, string from, string to, string train_no, string from_station_telecode, string to_station_telecode, string depart_date)
 {
     InitializeComponent();
     lblQuickTrainInfo.Text = title;
     _cookie = cookieContainer;
     _from = from;
     _to = to;
     _trainNo = train_no;
     _fromStationTelcode = from_station_telecode;
     _toStationTelcode = to_station_telecode;
     _departDate=depart_date;
     BindQuickTrainInfo();
 }
		/// <summary>
		/// ログインした人のアカウント情報を取得します
		/// </summary>
		/// <param name="cookieGetter"></param>
		/// <returns>ログインが完了していない場合はNullを返します</returns>
		public static AccountInfomation GetMyAccountInfomation(CookieGetterSharp.ICookieGetter cookieGetter)
		{
			if (cookieGetter.Status.IsAvailable) {
				try {
					System.Net.CookieContainer container = new System.Net.CookieContainer();
					container.Add(cookieGetter.GetCookieCollection(new Uri("http://live.nicovideo.jp/")));
					return GetMyAccountInfomation(container);
				} catch { 
				}
			}

			return null;
		}
Example #39
0
		/// <summary>
		/// メールアドレスとパスワードを使用して直接ログインする
		/// </summary>
		/// <param name="mail"></param>
		/// <param name="pass"></param>
		/// <returns>失敗した場合はnullが返される</returns>
		public static AccountInfomation Login(string mail, string pass)
		{
			System.Net.CookieContainer cookies = new System.Net.CookieContainer();
			string postData = String.Format("mail={0}&password={1}", mail, pass);

			Utility.PostData(ApiSettings.Default.LoginUrl, postData, cookies, 1000, "");

			AccountInfomation accountInfomation = NicoApiSharp.AccountInfomation.GetMyAccountInfomation(cookies);
			if (accountInfomation != null) {
				DefaultCookies = cookies;
				return accountInfomation;
			}

			return null;
		}
Example #40
0
        public BbsGetter(Settings settings)
        {
            this.cacheDir = settings.CacheDir;
            this.cc = settings.Cc;
            this.communityId = settings.CommunityId;
            this.host = settings.Host;
            this.username = settings.User;
            this.password = settings.Pass;
            this.dbName = settings.DbName;

            if (!cacheDir.EndsWith(System.IO.Path.DirectorySeparatorChar + ""))
                cacheDir += System.IO.Path.DirectorySeparatorChar;
            this.cacheDir = cacheDir + communityId + Path.DirectorySeparatorChar;
            Directory.CreateDirectory(cacheDir);
            Directory.CreateDirectory(this.cacheDir);


        }
Example #41
0
		/// <summary>
		/// ログインする
		/// </summary>
		/// <param name="cookieGetter"></param>
		/// <returns></returns>
		public static AccountInfomation Login(ICookieGetter cookieGetter)
		{
			System.Net.Cookie cookie = cookieGetter.GetCookie(new Uri("http://www.nicovideo.jp/"), "user_session");
			if (cookie == null) {
				Logger.Default.LogMessage(string.Format("Login failed, cookie dosen't found"));
				return null;
			}

			System.Net.CookieContainer container = new System.Net.CookieContainer();
			container.Add(cookie);

			AccountInfomation accountInfomation = NicoApiSharp.AccountInfomation.GetMyAccountInfomation(container);
			if (accountInfomation != null) {
				DefaultCookies = container;
				return accountInfomation;
			}

			return null;
		}
Example #42
0
        private async void button1_Click(object sender, EventArgs e)
        {
            try
            {
                button1.Enabled = false;
                while (true)
                {
                    var browser = ryu_s.BrowserCookie.BrowserManagerMaker.CreateInstance(ryu_s.MyCommon.Browser.BrowserType.Chrome);
                    var cookies = browser.CookieGetter.GetCookieCollection("nicovideo.jp");
                    var cc = new System.Net.CookieContainer();
                    cc.Add(cookies);

                    var settings = new NiconamaBbsGetter.Settings();
                    settings.CacheDir = txt_CacheDir.Text;
                    settings.Cc = cc;
                    settings.CommunityId = txt_communityId.Text;
                    settings.Host = txt_Host.Text;
                    settings.User = txt_User.Text;
                    settings.Pass = txt_Pass.Text;
                    settings.DbName = txt_DbName.Text;

                    var nicoBbs = new NiconamaBbsGetter.BbsGetter(settings);
                    try
                    {
                        await nicoBbs.Do(new Progress<Report>(SetProgress));

                    }
                    catch (System.Net.WebException ex)
                    {
                        ryu_s.MyCommon.Logging.LogException(ryu_s.MyCommon.LogLevel.error, ex);
                        Console.WriteLine(ex.Message);
                    }
                    SetText("30秒待機");
                    await Task.Delay(30 * 1000);
                }
            }
            finally
            {
                button1.Enabled = true;
            }
        }
		public override System.Net.CookieContainer GetAllCookies()
		{
			if (base.CookiePath == null || !System.IO.File.Exists(base.CookiePath)) {
				throw new CookieGetterException("Safariのクッキーパスが正しく設定されていません。");
			}

			System.Net.CookieContainer container = new System.Net.CookieContainer();

			try {
				System.Xml.XmlReaderSettings settings = new System.Xml.XmlReaderSettings();

				// DTDを取得するためにウェブアクセスするのを抑制する
				// (通信遅延や、アクセスエラーを排除するため)
				settings.XmlResolver = null;
				settings.ProhibitDtd = false;
				settings.CheckCharacters = false;

				using (System.Xml.XmlReader xtr = System.Xml.XmlTextReader.Create(base.CookiePath, settings)) {
					while (xtr.Read()) {
						switch (xtr.NodeType) {
							case System.Xml.XmlNodeType.Element:
								if (xtr.Name.ToLower().Equals("dict")) {
									System.Net.Cookie cookie = getCookie(xtr);
									try {
										Utility.AddCookieToContainer(container, cookie);
									} catch (Exception ex){
										CookieGetter.Exceptions.Enqueue(ex);
										Console.WriteLine(string.Format("Invalid Format! domain:{0},key:{1},value:{2}", cookie.Domain, cookie.Name, cookie.Value));
									}
								}
								break;
						}
					}
				}

			} catch (Exception ex) {
				throw new CookieGetterException("Safariのクッキー取得中にエラーが発生しました。", ex);
			}

			return container;
		}
Example #44
0
        public override System.Net.CookieContainer GetAllCookies()
        {
            List<System.Net.Cookie> cookies = new List<System.Net.Cookie>();

            foreach (string file in GetAllFiles()) {
                cookies.AddRange(PickCookiesFromFile(file));
            }

            // Expiresが最新のもで上書きする
            cookies.Sort(CompareCookieExpiresAsc);
            System.Net.CookieContainer container = new System.Net.CookieContainer();
            foreach (System.Net.Cookie cookie in cookies) {
                try {
                    Utility.AddCookieToContainer(container, cookie);
                } catch (Exception ex) {
                    CookieGetter.Exceptions.Enqueue(ex);
                    System.Diagnostics.Debug.WriteLine(ex.Message);
                }
            }
            return container;
        }
Example #45
0
		/// <summary>
		/// 対象URL上の名前がKeyであるクッキーを取得する
		/// </summary>
		/// <param name="url"></param>
		/// <param name="key"></param>
		/// <returns></returns>
		public override System.Net.Cookie GetCookie(Uri url, string key)
		{

			List<string> files = SelectFiles(url, GetAllFiles());
			List<System.Net.Cookie> cookies = new List<System.Net.Cookie>();
			foreach (string filepath in files) {
				System.Net.CookieContainer container = new System.Net.CookieContainer();

				foreach (System.Net.Cookie cookie in PickCookiesFromFile(filepath)) {
					if (cookie.Name.Equals(key)) {
						cookies.Add(cookie);
					}
				}
			}

			if (cookies.Count != 0) {
				// Expiresが最新のものを返す
				cookies.Sort(CompareCookieExpiresDesc);
				return cookies[0];
			}

			return null;
		}
        public override string this[string name]
        {
            get
            {
                return this.innerCollection[name];
            }

            set
            {
                if (name == XmlConstants.HttpContentLength)
                {
                    return;
                }
                else if (name == XmlConstants.HttpAcceptCharset)
                {
                    Debug.Assert(value == XmlConstants.Utf8Encoding, "Asking for AcceptCharset different thatn UTF-8.");
                    return;
                }
                else if (name == XmlConstants.HttpCookie)
                {
                    if (this.request != null)
                    {
                        System.Net.CookieContainer cookieContainer = new System.Net.CookieContainer();
                        cookieContainer.SetCookies(this.request.RequestUri, value);
                        this.request.CookieContainer = cookieContainer;
                    }
                    else
                    {
                        this.innerCollection[name] = value;
                    }
                }
                else
                {
                    this.innerCollection[name] = value;
                }
            }
        }
 public HttpClient()
 {
     _cookieContainer = new System.Net.CookieContainer();
 }
        private System.Net.CookieContainer ParseCookieSettings(string line)
        {
            System.Net.CookieContainer container = new System.Net.CookieContainer();

            // �N�b�L�[�����̑O�ɂ‚��Ă����悭�킩���Ȃ��w�b�_�[���������菜��
            // �ΏہF
            // �@\\x�ƂQ���̂P�U�i���l
            // �@\\\\
            // �@\���Ȃ��ꍇ�̐擪�P����
            string matchPattern = "^(\\\\x[0-9a-fA-F]{2})|^(\\\\\\\\)|^(.)|[\"()]";
            System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(matchPattern, System.Text.RegularExpressions.RegexOptions.Compiled);

            string[] blocks = line.Split(new string[] { "\\0\\0\\0" }, StringSplitOptions.RemoveEmptyEntries);
            foreach (string block in blocks) {
                if (block.Contains("=") && block.Contains("domain")) {
                    string header = reg.Replace(block, "");
                    System.Net.Cookie cookie = ParseCookie(header);
                    if (cookie != null) {
                        try {
                            container.Add(cookie);
                        } catch(Exception ex) {
                            CookieGetter.Exceptions.Enqueue(ex);
                        }
                    }
                }
            }

            return container;
        }
        void PopulateSessionCookie()
        {
            //Already session cookie is populated.
            if (this.SessionCookieContainer != null)
                return;

            //Map of Session - CookieContainer is populated in RootActvity.
            Activity rootActivity = (Activity)GetRootActivity();
            Dictionary<String, System.Net.CookieContainer> sessionCookieContainers;
            System.Net.CookieContainer cookieContainer;

            sessionCookieContainers = (Dictionary<String, System.Net.CookieContainer>)rootActivity.GetValue(SessionCookieMapProperty);

            if (sessionCookieContainers == null)
            {
                sessionCookieContainers = new Dictionary<String, System.Net.CookieContainer>();
                rootActivity.SetValue(SessionCookieMapProperty, sessionCookieContainers);
                cookieContainer = new System.Net.CookieContainer();
                sessionCookieContainers.Add(SessionId, cookieContainer);
            }
            else
            {
                if (!sessionCookieContainers.TryGetValue(SessionId, out cookieContainer))
                {
                    cookieContainer = new System.Net.CookieContainer();
                    sessionCookieContainers.Add(SessionId, cookieContainer);
                }
            }
            this.SessionCookieContainer = cookieContainer;
        }
Example #50
0
        /*
        * Método que carga la ventana
        */
        private void Form1_Load(object sender, EventArgs e)
        {
            pictureBox1.Load("http://titanic.ecci.ucr.ac.cr/~eb02430/TP2/hang/hang0.gif");  //método que carga la imagen inicial del ahorcado
            ws = new Hangman.titanic.B02430_Hangman();  //creación del servicio
            cookies = new System.Net.CookieContainer(); //creación del cookie
            ws.CookieContainer = cookies;   //asignación al servicio
            answer = ws.fetchWordArray("palabras.txt"); //escoge la palabra para el juego
            hidden = ws.hideCharacters(answer, answer.Length);  //esconde la palabra con _ _ _
            colocarResultado(hidden);   //coloca la palabra escondida en pantalla
            intentos = ws.getIntentos();
            label3.Text = intentos.ToString();  //coloca los intentos disponibles en pantalla

            /* Deshabilita botones y campos de texto */
            textBox1.Enabled = false;
            textBox2.Enabled = false;
            Top.Enabled = false;
            Probar.Enabled = false;
            label5.Visible = false;
            label6.Visible = false;
        }
Example #51
0
        /// <summary>
        /// Uploads the UI5 Project int <see cref="ProjectDir"/> to the SAP system specified by <see cref="Credentials"/>. If <see cref="Credentials.Username"/> is <c>null</c>, a single sign on authentification is performed.
        /// </summary>
        public void Upload()
        {
            if (string.IsNullOrWhiteSpace(ProjectDir)) throw new InvalidOperationException("ProjectDir not set.");
             if (!Directory.Exists(ProjectDir)) throw new InvalidOperationException("ProjectDir not set to a folder.");
             if (Credentials == null) throw new InvalidOperationException("Credentials not set.");
             if (string.IsNullOrWhiteSpace(Credentials.System)) throw new InvalidOperationException("Credentials.System not set.");
             if (string.IsNullOrWhiteSpace(AppName)) throw new InvalidOperationException("AppName not set.");

             if (TestMode) Log.Instance.Write("Test mode on!");

             try
             {
            var uri = new Uri(this.Credentials.System);
            uri = uri.AddQuery("sap-client", Credentials.Mandant.ToString());
            uri = uri.AddQuery("sapui5applicationname", AppName);
            uri = uri.AddQuery("sapui5applicationdescription", AppDescription);
            uri = uri.AddQuery("sapui5applicationpackage", Package);
            uri = uri.AddQuery("workbenchrequest", TransportRequest);
            uri = uri.AddQuery("externalcodepage", ExternalCodepage);
            uri = uri.AddQuery("deltamode", DeltaMode ? "true" : "false");
            uri = uri.AddQuery("testmode", TestMode ? "true" : "false");

            if (IgnoreCertificateErrors)
            {
               System.Net.ServicePointManager.ServerCertificateValidationCallback += ServerCertificateValidationIgnoreAll;
            }

            var cookieContainer = new System.Net.CookieContainer();
            //Try to Authenticate with a HEAD request and retrieve an authentification token cookie before uploading the whole application.
            var headRequest = System.Net.HttpWebRequest.Create(uri);
            headRequest.PreAuthenticate = false;
            headRequest.Timeout = 10000;
            headRequest.Method = System.Net.WebRequestMethods.Http.Head;
            ((System.Net.HttpWebRequest)headRequest).CookieContainer = cookieContainer;

            if (Credentials.Username != null)
            {
               headRequest.Credentials = new System.Net.NetworkCredential(Credentials.Username, Credentials.Password);
            }
            else //SSO
            {
               headRequest.ImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
               headRequest.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
            }
            headRequest.GetResponse().Close();

            //The actual POST request with the ziped project.
            var request = System.Net.HttpWebRequest.Create(uri);
            request.Timeout = Timeout * 1000;
            request.PreAuthenticate = true;
            request.UseDefaultCredentials = false;
            ((System.Net.HttpWebRequest)request).CookieContainer = cookieContainer; //Contains the authentification token if acquired
            if (Credentials.Username != null)                                       //if not: credentials to reauthenficiate.
            {
               request.Credentials = new System.Net.NetworkCredential(Credentials.Username, Credentials.Password);
            }
            else //SSO
            {
               request.ImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
               request.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
            }
            Log.Instance.Write("Uploading project...");
            request.Method = System.Net.WebRequestMethods.Http.Post;
            request.ContentType = "application/zip";
            using (var stream = request.GetRequestStream())
            {
               using (var zipHelper = new ZipHelper(stream))
               {
                  zipHelper.Zip(".Ui5RepositoryUploadParameters", Encoding.UTF8.GetBytes(cleanedConfigFileContent));
                  zipHelper.Zip(ProjectDir, new[] { ".Ui5Repository*", "WebContent" }, IgnoreMasks.ToArray());
               }
               stream.Close();
            }
            Log.Instance.Write("Installing App...");
            var response = (System.Net.HttpWebResponse)request.GetResponse();
            HandleResponse(response);
             }
             catch (System.Net.WebException ex)
             {
            if (ex.Response != null)
            {
               HandleResponse((System.Net.HttpWebResponse)ex.Response);
            }
            else
            {
               Log.Instance.Write(ex.ToString());
               Log.Instance.Write("Upload failed!");
               throw new UploadFailedException();
            }
             }
        }
        /// <summary>
        /// HD streaming from laola1.tv
        /// http://streamaccess.unas.tv/hdflash/1/hdlaola1_70429.xml?streamid=70429&partnerid=1&quality=hdlive&t=.smil
        /// This streaming type is used for many major sport events (e.g. soccer games, ice hockey, etc.) 
        /// </summary>
        /// <param name="video">Video object</param>
        /// <param name="playkey1">Playkey1 for this video</param>
        /// <param name="playkey2">Playkey2 for this video</param>
        /// <returns>Url for streaming</returns>
        private string GetHdStreamingUrl(VideoInfo video, String data)
        {
            //TODO: this isn't working yet. MediaPortal doesn't play the stream for some reason.
            //Downloading works though and the file can be played after that.

            Match c = regEx_GetLiveHdPlaykeys.Match(data);
            if (c.Success)
            {
                String streamAccess = c.Groups["streamaccess"].Value;
                String streamId = c.Groups["streamid"].Value;
                String flashPlayer = c.Groups["flashplayer"].Value + ".swf";
                //String flashVersion = c.Groups["flashversion"].Value;

                //String playData = GetWebData(String.Format("http://streamaccess.laola1.tv/hdflash/1/hdlaola1_{0}.xml?streamid={1}&partnerid=1&quality=hdlive&t=.smil", playkey1, playkey1));

                System.Net.CookieContainer container = new System.Net.CookieContainer();
                String playData = GetWebData(streamAccess, cookies: container);
                Match baseUrls = regEx_GetLiveHdBaseUrls.Match(playData);
                Match sources = regEx_GetLiveHdSources.Match(playData);

                //TODO: don't rely on the fact, the the quality is sorted (first item = worst quality, third = best)
                if (videoQuality == VideoQuality.Medium)
                {
                    sources = sources.NextMatch();
                }
                else if (videoQuality == VideoQuality.High)
                {
                    sources = sources.NextMatch().NextMatch();
                }


                String httpUrl = baseUrls.Groups["httpbase"].Value + sources.Groups["src"].Value;// +"&v=2.6.6&fp=WIN%2011,1,102,62&r=" + GetHdLiveRandomString(5) + "&g=" + GetHdLiveRandomString(12);
                httpUrl = httpUrl.Replace("amp;", "");
                httpUrl = httpUrl.Replace("e=&", "e=" + streamId + "&");
                httpUrl = httpUrl.Replace("p=&", "p=1&");

                /*String rtmpUrl = String.Format("rtmp://{0}:1935/{1}?_fcs_vhost={2}/{3}?auth={4}&p=1&e={5}&u=&t=livevideo&l=&a=&aifp={6}", ip, servertype, url, stream, auth, playkey1, aifp);
                //Log.Info("RTMP Url: " + rtmpUrl);
                String playpath = ReverseProxy.Instance.GetProxyUri(RTMP_LIB.RTMPRequestHandler.Instance,
                        string.Format("http://127.0.0.1/stream.flv?rtmpurl={0}&swfVfy={1}&live={2}",
                        System.Web.HttpUtility.UrlEncode(rtmpUrl),
                        System.Web.HttpUtility.UrlEncode("true"),
                        System.Web.HttpUtility.UrlEncode("true")
                        ));
                String playpath = string.Format("{0}&swfVfy={1}&live={2}",
                        rtmpUrl,
                        System.Web.HttpUtility.UrlEncode("true"),
                        System.Web.HttpUtility.UrlEncode("true")
                        );*/

                //String playpath = ReverseProxy.Instance.GetProxyUri(this, httpUrl);
                MPUrlSourceFilter.HttpUrl url = new MPUrlSourceFilter.HttpUrl(httpUrl);
                //url.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3";
                url.Cookies.Add(container.GetCookies(new Uri(streamAccess)));
                return url.ToString();
            }
            return null;
        }
Example #53
0
 static ServerConnection()
 {
     CookieContainer = new System.Net.CookieContainer();
 }
Example #54
0
        private static System.Net.CookieContainer FetLifeCookie()
        {
            string[] pairs = cookieString.Split(';');
            var cookieContainer = new System.Net.CookieContainer();
            Uri fl = new Uri("https://fetlife.com");

            foreach (var item in pairs)
            {
                string[] splitItem = item.Split(new char[] { '=' }, 2);
                System.Net.Cookie cookie = new System.Net.Cookie(splitItem[0].Trim(), splitItem[1].Trim(), "/", fl.Host);
                cookieContainer.Add(cookie);
            }
            return cookieContainer;
        }
 public UserManager(string url)
 {
     CookieContainer = new System.Net.CookieContainer();
     url = url;
 }
        protected override System.Net.CookieContainer GetCookies(string path, string query)
        {
            System.Net.CookieContainer container = new System.Net.CookieContainer();

            if(string.IsNullOrEmpty(path) || !System.IO.File.Exists(path)) {
                return container;
                throw new CookieGetterException("クッキーパスが正しく設定されていません。");
            }

            string temp = null;

            try {
                // 一時ファイルの取得ができない環境に対応
                temp = Utility.GetTempFilePath();
                System.IO.File.Copy(path, temp, true);

                // SQLite3.7.x
                string pathshm = path + "-shm";
                string pathwal = path + "-wal";
                if(File.Exists(pathshm)) {
                    System.IO.File.Copy(pathwal, temp + "-wal", true);
                    System.IO.File.Copy(pathshm, temp + "-shm", true);
                }

                System.Threading.Thread.Sleep(5);

                using(SQLiteConnection sqlConnection = new SQLiteConnection(string.Format(CONNECTIONSTRING_FORMAT, temp))) {
                    sqlConnection.Open();

                    try {
                        using(SQLiteCommand commandVersion = sqlConnection.CreateCommand()) {
                            commandVersion.Connection = sqlConnection;
                            commandVersion.CommandText = SELECT_QUERY_VERSION;
                            using(SQLiteDataReader sdrv = commandVersion.ExecuteReader()) {
                                if(!sdrv.Read()) {
                                    return base.GetCookies(path, query);
                                }

                                int version = int.Parse(sdrv[0].ToString());
                                if(version < VERSION) {
                                    return base.GetCookies(path, query);
                                }
                            }
                        }
                    }
                    catch {
                        return base.GetCookies(path, query);
                    }

                    // スマートにならないのかなー
                    query = query.Replace("expires_utc FROM cookies", "expires_utc, encrypted_value FROM cookies");

                    using(SQLiteCommand command = sqlConnection.CreateCommand()) {
                        command.Connection = sqlConnection;
                        command.CommandText = query;
                        using(SQLiteDataReader sdr = command.ExecuteReader()) {

                            while(sdr.Read()) {
                                List<object> items = new List<object>();

                                for(int i = 0; i < sdr.FieldCount; i++) {
                                    items.Add(sdr[i]);
                                }

                                System.Net.Cookie cookie = DataToCookie(items.ToArray());
                                try {
                                    Utility.AddCookieToContainer(container, cookie);
                                }
                                catch(Exception ex) {
                                    CookieGetter.Exceptions.Enqueue(ex);
                                    Console.WriteLine(string.Format("Invalid Format! domain:{0},key:{1},value:{2}", cookie.Domain, cookie.Name, cookie.Value));
                                }

                            }
                        }
                    }

                    sqlConnection.Close();
                }

            }
            catch(Exception ex) {
                throw new CookieGetterException("クッキーを取得中、Sqliteアクセスでエラーが発生しました。", ex);
            }
            finally {
                if(temp != null) {
                    System.IO.File.Delete(temp);
                }
            }

            return container;
        }
Example #57
0
        /// <summary>
        /// P6Login
        /// </summary>
        /// <param name="userName">User Name</param>
        /// <param name="password"></param>
        /// <returns></returns>
        public System.Net.CookieContainer P6Login(string userName, string password)
        {
            P6WS.AuthenticationService.AuthenticationService authService = new P6WS.AuthenticationService.AuthenticationService();
            authService.CookieContainer = new System.Net.CookieContainer();
            // Add an entry to appSettings.
            authService.Url = System.Configuration.ConfigurationManager.AppSettings[P6WS_SERVICES_AUTHENTICATION_SERVICE].ToString();
            P6WS.AuthenticationService.Login loginObj = new P6WS.AuthenticationService.Login();
            loginObj.UserName = userName;
            loginObj.Password = password;
            loginObj.DatabaseInstanceId = 1;
            loginObj.DatabaseInstanceIdSpecified = true;
            loginObj.VerboseFaults = true;
            loginObj.VerboseFaultsSpecified = true;
            P6WS.AuthenticationService.LoginResponse loginReturn = authService.Login(loginObj);

            System.Net.CookieContainer cookie = new System.Net.CookieContainer();

            if (loginReturn.Return)
                cookie = authService.CookieContainer;

            return cookie;
        }
Example #58
0
 /// <summary>
 /// Clear
 /// </summary>
 public void ClearCookies()
 {
     _cookies = new System.Net.CookieContainer(); // let GC do it
 }
Example #59
0
 private bool HardDeleteNextUserBatch(string alias, string username, string password, int batchSize, bool testMode, bool useFastDelete, out string result)
 {
     result = null;
     bool retVal = false;
     string url = DnnRequest.GetUrl(alias, "Dnn_BulkUserDelete", "BulkUserDelete", "HardDeleteNextUsers", false);
     System.Net.HttpStatusCode statusCode; string errorMsg;
     System.Net.CookieContainer cookies = new System.Net.CookieContainer();
     //really should use a string format here to build the JSON but quick and dirty does the job
     string requestBody = "{ 'actionName' : 'hardDelete', 'actionNumber' : " + batchSize.ToString() + ", 'testRun': '" + testMode.ToString() + "', 'useFastDelete': '" +  useFastDelete.ToString() + "'}";
     //post the request to delete the batch of users
     result = DnnRequest.PostRequest(url, username, password, requestBody, ContentType.JSON, out statusCode, out errorMsg, ref cookies);
     result = ReturnResult(url, statusCode, errorMsg, result);
     if (statusCode == System.Net.HttpStatusCode.OK)
     {
         //get the call return value form the return JSON
         if (string.IsNullOrEmpty(result) == false)
         {
             var jsonResult = Newtonsoft.Json.Linq.JObject.Parse(result);
             retVal = bool.Parse(jsonResult["Success"].ToString());
         }
     }
     return retVal;
 }
 public HttpClient(System.Net.CookieContainer cookies)
 {
     _cookieContainer = cookies;
 }