当前位置: 首页>>代码示例>>C#>>正文


C# StreamReader.IndexOf方法代码示例

本文整理汇总了C#中System.IO.StreamReader.IndexOf方法的典型用法代码示例。如果您正苦于以下问题:C# StreamReader.IndexOf方法的具体用法?C# StreamReader.IndexOf怎么用?C# StreamReader.IndexOf使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.IO.StreamReader的用法示例。


在下文中一共展示了StreamReader.IndexOf方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: GetTranslatedText

        public string GetTranslatedText(string sourseText, string langSource, string langTrans)
        {
            Helper helper = new Helper();
            string returnValue = string.Empty;

            if (!helper.IsNullOrEmpty(sourseText))
            {
                HttpWebRequest request = null;
                HttpWebResponse response = null;
                StringBuilder builder = new StringBuilder("http://ajax.googleapis.com/ajax/services/language/translate?v=1.0");
                builder.Append("&q=" + HttpUtility.UrlEncode(sourseText.Trim()));
                builder.Append("&langpair=" + langSource + "|" + langTrans);
                builder.Append("&key=" + ConfigurationManager.AppSettings["GoogleAPIKey"]);
                request = (HttpWebRequest)WebRequest.Create(builder.ToString());
                request.Method = NHttpMethod.GET.ToString();
                response = (HttpWebResponse)request.GetResponse();

                if (response.StatusCode == HttpStatusCode.OK)
                {
                    string str = new StreamReader(response.GetResponseStream()).ReadToEnd();
                    string leadingText = "{\"translatedText\":\"";
                    int startIndex = str.IndexOf(leadingText) + leadingText.Length;
                    int index = str.IndexOf("\"},");

                    returnValue = str.Substring(startIndex, index - startIndex);
                }
                else
                    returnValue = "Google translation service no response.";
            }

            return returnValue;
        }
开发者ID:wjkong,项目名称:MicNets,代码行数:32,代码来源:AjaxWS.asmx.cs

示例2: GetDownloadUrls

        /// <summary>
        /// Gets a list of <see cref="VideoInfo"/>s for the specified URL.
        /// </summary>
        /// <param name="videoUrl">The URL of the YouTube video.</param>
        /// <returns>A list of <see cref="VideoInfo"/>s that can be used to download the video.</returns>
        /// <exception cref="ArgumentException">videoUrl is not a valid YouTube URL.</exception>
        /// <exception cref="WebException">An error occured while downloading the video infos.</exception>
        public static IEnumerable<VideoInfo> GetDownloadUrls(string videoUrl)
        {
            videoUrl = NormalizeYoutubeUrl(videoUrl);

            const string startConfig = "yt.playerConfig = ";

            string pageSource;

            var req = WebRequest.Create(videoUrl);

            using (var resp = req.GetResponse())
            {
                pageSource = new StreamReader(resp.GetResponseStream(), Encoding.UTF8).ReadToEnd();
            }

            string videoTitle = GetVideoTitle(pageSource);

            int playerConfigIndex = pageSource.IndexOf(startConfig, StringComparison.Ordinal);

            if (playerConfigIndex > -1)
            {
                string signature = pageSource.Substring(playerConfigIndex);
                int endOfJsonIndex = signature.TrimEnd(' ').IndexOf("yt.setConfig", StringComparison.Ordinal);
                signature = signature.Substring(startConfig.Length, endOfJsonIndex - 26);

                JObject playerConfig = JObject.Parse(signature);
                JObject playerArgs = JObject.Parse(playerConfig["args"].ToString());
                var availableFormats = (string)playerArgs["url_encoded_fmt_stream_map"];

                const string argument = "url=";
                const string endOfQueryString = "&quality";

                if (availableFormats != String.Empty)
                {
                    var urlList = new List<string>(Regex.Split(availableFormats, argument));

                    var downLoadInfos = new List<VideoInfo>();

                    // Format the URL
                    var urls = urlList
                        .Where(entry => !String.IsNullOrEmpty(entry.Trim()))
                        .Select(entry => entry.Substring(0, entry.IndexOf(endOfQueryString, StringComparison.Ordinal)))
                        .Select(entry => new Uri(Uri.UnescapeDataString(entry)));

                    foreach (Uri url in urls)
                    {
                        NameValueCollection queryString = HttpUtility.ParseQueryString(url.Query);

                        // for this version, only get the download URL
                        byte formatCode = Byte.Parse(queryString["itag"]);
                        // Currently based on youtube specifications (later we'll depend on the MIME type returned from the web request)
                        downLoadInfos.Add(new VideoInfo(url.ToString(), videoTitle, formatCode));
                    }

                    return downLoadInfos;
                }
            }

            return Enumerable.Empty<VideoInfo>();
        }
开发者ID:random-username,项目名称:YoutubeExtractor,代码行数:67,代码来源:DownloadUrlResolver.cs

示例3: login

        public bool login(string username, string password) {
            var initialRequest = CyberghostRequest("https://account.cyberghostvpn.com/en_us/login");
            var initialResponse = (HttpWebResponse)initialRequest.GetResponse();

            var csrfToken = new StreamReader(initialResponse.GetResponseStream()).ReadToEnd();
            csrfToken = csrfToken.Substring(csrfToken.IndexOf("var CSRF", StringComparison.Ordinal) + 12, 64);


            var loginRequest = CyberghostRequest("https://account.cyberghostvpn.com/en_us/proxy/users/me?flags=17&csrf=" + csrfToken);
            var postData = "username="+ username + "&authentication=" + password + "&captcha=";
            var data = Encoding.ASCII.GetBytes(postData);

            loginRequest.Method = "POST";
            loginRequest.ContentType = "application/x-www-form-urlencoded";
            loginRequest.ContentLength = data.Length;

            using (var stream = loginRequest.GetRequestStream()) {
                stream.Write(data, 0, data.Length);
            }
            try {
                var loginResponse = (HttpWebResponse)loginRequest.GetResponse();
                var responded = new StreamReader(loginResponse.GetResponseStream()).ReadToEnd();
                return responded.Contains("user_name");
            } catch (Exception) {
                return false;
            }
            
        }
开发者ID:josh-richardson,项目名称:cyberghosty,代码行数:28,代码来源:CyberGhostInstance.cs

示例4: AddPhotosComments

        /// <summary>
        /// Функция добавления комментариев к фотографиям
        /// </summary>
        /// <param name="uid">Идентификатор пользователя</param>
        /// <param name="ts">Текущее состояние photos_comments</param>
        /// <param name="message">Текст сообщения</param>
        /// <param name="parent">{id владльца фотографии}_{id фотографии}</param>
        /// <param name="sid">Идентификатор сессии</param>
        /// <param name="errorResponse"></param>
        /// <returns></returns>
        public HttpWebResponse AddPhotosComments(string uid, string message, string parent, string sid, out ErrorResponse errorResponse)
        {
            //// коррекция parent
            //string[] parentData = parent.Split('_');

            //if (parentData[0].Equals("0"))
            //{
            //    parent = uid + "_" + parentData[1];
            //}

            errorResponse = null;

            var uri = new Uri
                          {
                              Address = SystemConfiguration.ServerConnectionToApiCalls,
                              Method = "/data?act=add_photos_comments&"
                          };

            uri.Parameters.Add("id=" + uid);
            uri.Parameters.Add("message=" + message);
            uri.Parameters.Add("parent=" + parent);
            uri.Parameters.Add("sid=" + sid);

            HttpWebRequest request = HttpUtility.PrepareHttpWebRequest(uri.GetUri());
            //WebResponse response = null;
            try
            {
                using (WebResponse newHttpWebResponse = request.GetResponse())
                {
                    string responseStr = new StreamReader(HttpUtility.PrepareResponseStream(newHttpWebResponse)).ReadToEnd();

                    if (responseStr.IndexOf("\"ok\":0") != -1)
                        errorResponse = new ErrorResponse { error_code = "0" };
                    else if (responseStr.IndexOf("\"ok\":-1") != -1)
                        errorResponse = new ErrorResponse { error_code = "-1" };
                    else if (responseStr.IndexOf("\"ok\":-2") != -1)
                        errorResponse = new ErrorResponse { error_code = "-2" };
                    else if (responseStr.IndexOf("\"ok\":-3") != -1)
                        errorResponse = new ErrorResponse { error_code = "-3" };

                    if (errorResponse != null)
                        return null;
                    return (HttpWebResponse)newHttpWebResponse;
                }
            }
            catch (ObjectDisposedException ex)
            {
                DebugHelper.WriteLogEntry(ex, "AddPhotosComments ObjectDisposedException");
                return null;
            }
            finally
            {
                request.Abort();
                //response.Close();
            }
        }
开发者ID:xorkrus,项目名称:vk_wm,代码行数:66,代码来源:CommunicationLogic.cs

示例5: GetAcceptCallback

        /*
         * Gets a response from the /tribunal/accept request. This response will contain
         * the case id and the number of game in the case.
         * These two pieces of info are used by the CaseLoader class to request the JSON data.
         */
        private void GetAcceptCallback(IAsyncResult asynchronousResult)
        {
            HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
            HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
            String html = new StreamReader(response.GetResponseStream()).ReadToEnd();
            //System.Diagnostics.Debug.WriteLine("Number of Cookies after: " + MobileTribunal.Instance.cookies.Count);
            //System.Diagnostics.Debug.WriteLine("Response: " + (int)response.StatusCode);
            //System.Diagnostics.Debug.WriteLine("Length: " + html.Length + "\nTitle: " + html.Substring(html.IndexOf("<title>")));

            /* The case id will be found in the title of the page
             * it will look something like: <title>The Tribunal -  Reviewing Case CASEID</title>
             */
            String caseId;
            int numGames;
            int startIndex = html.IndexOf("Reviewing Case ") + "Reviewing Case ".Length;
            caseId = html.Substring(startIndex, html.IndexOf("</title>") - startIndex);
            System.Diagnostics.Debug.WriteLine("Case Id: " + caseId);

            /* The number of games is stored in a JSON structure.
             * it looks something like 'game_count': NUMGAMES,
             */
            startIndex = html.IndexOf("'game_count': ") + "'game_count': ".Length;
            bool gotNumGames = int.TryParse(html.Substring(startIndex, html.IndexOf(",", startIndex) - startIndex), out numGames);
            System.Diagnostics.Debug.WriteLine("Number of games: " + numGames);

            if (gotNumGames && !(String.IsNullOrEmpty(caseId) || numGames < 1))
            {

                MobileTribunal.GetInstance().caseLoader.loadNewCase(caseId, numGames, new AsyncCallback(CaseLoadedCallback));
            }
            else
            {
                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    MessageBox.Show("An error occurred while trying to load a case.");
                    NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
                });
                return;
            }
        }
开发者ID:Cole119,项目名称:MobileTribunal,代码行数:45,代码来源:LoadingPage.xaml.cs

示例6: BackgroundWorkerDoWork

 private void BackgroundWorkerDoWork(object sender, DoWorkEventArgs e)
 {
     var url = string.Format("http://www.youtube.com/watch?v={0}", e.Argument);
     _errorMessage = string.Empty;
     var request = (HttpWebRequest)WebRequest.Create(url);
     var response = (HttpWebResponse)request.GetResponse();
     var responseStream = response.GetResponseStream();
     if (responseStream == null)
     {
         _errorMessage = "Error while reading response from YouTube.";
         return;
     }
     var source = new StreamReader(responseStream, Encoding.UTF8).ReadToEnd();
     
     var found = source.IndexOf("x-flv");
     while (!source.Substring(found, 4).Equals("http"))
         found--;
     source = source.Remove(0, found);
     source = HttpUtility.UrlDecode(source);
     source = HttpUtility.UrlDecode(source); //Twice
     _errorMessage = source.Substring(0,source.IndexOf("&quality"));
 }
开发者ID:fbmly007,项目名称:3dsexplorer,代码行数:22,代码来源:YouTube.cs

示例7: GetKeyFromRemoteServer

 public static int GetKeyFromRemoteServer(string regURL)
 {
     string s = new StreamReader(WebRequest.Create(regURL).GetResponse().GetResponseStream(), true).ReadToEnd().ToLower();
     int index = s.IndexOf("answer:");
     if (index != -1)
     {
         s = s.Substring(index + 7, 1);
         int result = 0;
         if (int.TryParse(s, out result))
         {
             return result;
         }
     }
     return -1;
 }
开发者ID:tmsdy,项目名称:RegRainbowEcommerce,代码行数:15,代码来源:Util.cs

示例8: MetaTag

        public void MetaTag()
        {

            var encoder = Encoding.GetEncoding("windows-1255");

            var html = htmlStart + htmlStartMeta + htmlStart3 +hebrewChar + htmlEnd;
            var htmlNoRecode = htmlStart + htmlStart3 + hebrewChar + htmlEnd;


            // create a windows-1255 encoded stream
            
            var dom = CQ.Create(GetMemoryStream(htmlNoRecode, encoder));

            // grab the character from CsQuery's output, and ensure that this all worked out.
            
            var csqueryHebrewChar = dom["#test"].Text();

            // Test directly from the stream

            string htmlHebrew = new StreamReader(GetMemoryStream(htmlNoRecode,encoder),encoder).ReadToEnd();

            var sourceHebrewChar = htmlHebrew.Substring(htmlHebrew.IndexOf("test>") + 5, 1);

            // CsQuery should fail to parse it

            Assert.AreNotEqual(sourceHebrewChar, csqueryHebrewChar);


            // the actual character from codepage 1255
            Assert.AreEqual("₪", sourceHebrewChar);

            // Now try it same as the original test - but with the meta tag identifying character set.

            var htmlWindows1255 = GetMemoryStream(html, encoder);

            // Now run again with the charset meta tag, but no encoding specified.
            dom = CQ.Create(htmlWindows1255);

            csqueryHebrewChar = dom["#test"].Text();

            Assert.AreEqual(sourceHebrewChar,csqueryHebrewChar);
        }
开发者ID:emrahoner,项目名称:CsQuery,代码行数:42,代码来源:CharacterSetEncoding.cs

示例9: MetaTag

        public void MetaTag()
        {

            var encoder = Encoding.GetEncoding("windows-1255");

            var html = htmlStart + htmlStartMeta + htmlStart3 +hebrewChar + htmlEnd;
            var htmlNoRecode = htmlStart + htmlStart3 + hebrewChar + htmlEnd;

            var dom = CQ.Create(GetMemoryStream(htmlNoRecode, encoder));

            // grab the character from CsQuery's output, and ensure that this all worked out.
            
            var outputHebrewChar = dom["#test"].Text();

            // Test directly from the stream

            string htmlHebrew = new StreamReader(GetMemoryStream(htmlNoRecode,encoder),encoder).ReadToEnd();

            var sourceHebrewChar = htmlHebrew.Substring(htmlHebrew.IndexOf("test>") + 5, 1);

            // CsQuery should fail to parse it
             
            Assert.AreNotEqual(hebrewChar, outputHebrewChar);

            // the unicode version should not match the 1255 versions
            Assert.AreNotEqual(hebrewChar, sourceHebrewChar);

            // the actual character from codepage 1255
            Assert.AreEqual("₪", sourceHebrewChar);

            // Now try it same as the original test - but with the meta tag identifying character set.

            var htmlWindows1255 = GetMemoryStream(html, encoder);

            // pass it the wrong encoding deliberately
            dom = CQ.Create(htmlWindows1255, Encoding.GetEncoding("ISO-8859-1"));
            outputHebrewChar = dom["#test"].Text();

            Assert.AreEqual(sourceHebrewChar,outputHebrewChar);
        }
开发者ID:yilativ,项目名称:CsQuery,代码行数:40,代码来源:CharacterSetEncoding.cs

示例10: Register

        public override bool Register(string Username, string Passwrd)
        {


            HttpWebRequest getHeaders = HttpWebRequest.Create("https://pocketrocketscasino.eu/play/#account") as HttpWebRequest;
            if (Prox != null)
                getHeaders.Proxy = Prox;
            var cookies = new CookieContainer();
            getHeaders.CookieContainer = cookies;
            HttpWebResponse Response = null;
            string rqtoken = "";
            try
            {

                Response = (HttpWebResponse)getHeaders.GetResponse();
                string s1 = new StreamReader(Response.GetResponseStream()).ReadToEnd();
                string tmp = s1.Substring(s1.IndexOf("__RequestVerificationToken") + "__RequestVerificationToken\" type=\"hidden\" value=\"".Length);
                rqtoken = tmp.Substring(0, tmp.IndexOf("\""));
            }
            catch (WebException e)
            {
                return false;
            }
            CookieContainer tmpContainer = getHeaders.CookieContainer;
            

            foreach (Cookie c in Response.Cookies)
            {
                /*if (c.Name == "__RequestVerificationToken")
                    rqtoken = c.Value;*/
                Cookies.Add(c);
            }
            con.CookieContainer = Cookies;
            try
            {
                string s1 = "";
                getHeaders = HttpWebRequest.Create("https://pocketrocketscasino.eu/account/GetUserAccount") as HttpWebRequest;
                if (Prox != null)
                    getHeaders.Proxy = Prox;
                getHeaders.CookieContainer = Cookies;
                Response = (HttpWebResponse)getHeaders.GetResponse();
                string stmp = new StreamReader(Response.GetResponseStream()).ReadToEnd();
                string sstmp = stmp.Substring(stmp.IndexOf("__RequestVerificationToken") + "__RequestVerificationToken\" type=\"hidden\" value=\"".Length);
                //s = rqtoken = sstmp.Substring(0, sstmp.IndexOf("\""));
                

                dicehub = con.CreateHubProxy("diceHub");
                con.Start().Wait();
                getHeaders = HttpWebRequest.Create("https://pocketrocketscasino.eu/account/SaveUserNameAndPassword") as HttpWebRequest;
                if (Prox != null)
                    getHeaders.Proxy = Prox;
                getHeaders.CookieContainer = tmpContainer;
                foreach (Cookie c in Response.Cookies)
                {

                    getHeaders.CookieContainer.Add(c);
                }
                getHeaders.CookieContainer.Add(new Cookie("PRC_Affiliate", "357", "/", "pocketrocketscasino.eu"));
                System.Threading.Thread.Sleep(5000);
                getHeaders.Method = "POST";
                string post = string.Format("userName={0}&password={1}&confirmPassword={1}&__RequestVerificationToken={2}", Username, Passwrd, rqtoken);
                getHeaders.ContentType = "application/x-www-form-urlencoded";
                getHeaders.ContentLength = post.Length;
                using (var writer = new StreamWriter(getHeaders.GetRequestStream()))
                {
                    string writestring = post as string;
                    writer.Write(writestring);
                }
                try
                {

                    Response = (HttpWebResponse)getHeaders.GetResponse();
                    s1 = new StreamReader(Response.GetResponseStream()).ReadToEnd();
                    /*string tmp = s1.Substring(s1.IndexOf("__RequestVerificationToken") + "__RequestVerificationToken\" type=\"hidden\" value=\"".Length);
                    rqtoken = tmp.Substring(0, tmp.IndexOf("\""));*/
                }
                catch (WebException e)
                {
                    Response = (HttpWebResponse)e.Response;
                    s1 = new StreamReader(Response.GetResponseStream()).ReadToEnd();
                    return false;
                }

                dicehub.On<string, string, string, string, string, string>("receiveChatMessage", GotChatMessage);
                
                getHeaders = HttpWebRequest.Create("https://pocketrocketscasino.eu/account/GetUserAccount") as HttpWebRequest;
                if (Prox != null)
                    getHeaders.Proxy = Prox;
                getHeaders.CookieContainer = Cookies;
                Response = (HttpWebResponse)getHeaders.GetResponse();
                s1 = new StreamReader(Response.GetResponseStream()).ReadToEnd();
                PRCUser tmp = json.JsonDeserialize<PRCUser>(s1);
                balance = (double)tmp.AvailableBalance;
                profit = (double)tmp.Profit;
                wagered =(double) tmp.Wagered;
                bets = (int)tmp.NumBets;
                wins = (int)tmp.Wins;
                losses = (int)tmp.Losses;
                UserID = tmp.Id;
                Parent.updateBalance((decimal)(balance));
//.........这里部分代码省略.........
开发者ID:wmgjang,项目名称:DiceBot,代码行数:101,代码来源:PRC.cs

示例11: submit_Click

        void submit_Click(object sender, EventArgs e)
        {
            if (!this.fieldLastName.Equals("No Mapping") && !this.fieldCompany.Equals("No Mapping")
                && this.FieldControls.Where(c => c.MetaField.FieldName.Equals(this.fieldLastName)).Any()
                && this.FieldControls.Where(c => c.MetaField.FieldName.Equals(this.fieldCompany)).Any())
            {
                //Retrieve configuration and build request for token
                SalesForceConfig config = Config.Get<SalesForceConfig>();
                StringBuilder request = new StringBuilder();
                request.Append("https://login.salesforce.com/services/oauth2/token?response_type=code&grant_type=password");
                request.Append("&client_id="); request.Append(config.ClientId); //Consumer Key for the Connected App
                request.Append("&client_secret="); request.Append(config.ClientSecret); //Consumer Secret for the Connected App
                request.Append("&username="); request.Append(config.Username);
                request.Append("&password="); request.Append(config.Password);request.Append(config.SecurityToken); //the security token is sent in an email to each user

                //Request token
                HttpWebRequest requestToken = (HttpWebRequest)WebRequest.Create(request.ToString());
                requestToken.Method = "POST";
                HttpWebResponse token = (HttpWebResponse)requestToken.GetResponse();
                string accessToken = new StreamReader(token.GetResponseStream()).ReadToEnd();
                string tokenStart = accessToken.Substring(accessToken.IndexOf("access_token") + 15);
                accessToken = tokenStart.Substring(0, tokenStart.IndexOf("\""));

                //Get form fields' values
                string lastName = ((FieldControl)this.FieldControls.Where(c => c.MetaField.FieldName.Equals(this.fieldLastName)).First()).Value.ToString();
                string company = ((FieldControl)this.FieldControls.Where(c => c.MetaField.FieldName.Equals(this.fieldCompany)).First()).Value.ToString();

                if (sfVersion.Equals(""))
                {
                    setSalesForceVersion();

                }
                //Create lead in SalesForce
                HttpWebRequest createLead = (HttpWebRequest)WebRequest.Create(config.Server + "/services/data/v" + sfVersion + "/sobjects/Lead/");
                createLead.Headers.Add("Authorization: Bearer " + accessToken);
                createLead.ContentType = "application/json";
                ASCIIEncoding encoding = new ASCIIEncoding();
                string stringData = "{\"LastName\":\"" + lastName + "\",\"Company\":\"" + company + "\"}";
                byte[] data = encoding.GetBytes(stringData);
                createLead.Method = "POST";
                createLead.ContentLength = data.Length;
                Stream newStream = createLead.GetRequestStream();
                newStream.Write(data, 0, data.Length);
                newStream.Flush();
                newStream.Close();
                createLead.GetResponse();
            }
        }
开发者ID:bilyana-ivanova,项目名称:SalesForceForm,代码行数:48,代码来源:FormsControlCustom.cs

示例12: SetDistant

        private void SetDistant(string userName)
        {
            HttpWebRequest request = CreateRequest("https://my.familytreedna.com/family-finder-matches.aspx");
            HttpWebResponse resp = (HttpWebResponse)request.GetResponse();
            string respHtml = new StreamReader(resp.GetResponseStream()).ReadToEnd();
            string viewState = ExtractViewState(respHtml);

            //Go to In Common Quickly
            request = CreateRequest("https://my.familytreedna.com/family-finder-matches.aspx");
            request.Method = "POST";
            //request.Headers.Add("X-MicrosoftAjax", "Delta=true");
            request.ContentType = "application/x-www-form-urlencoded";
            request.KeepAlive = true;
            request.Referer = "https://my.familytreedna.com/family-finder-matches.aspx";
            //request.Accept = "gzip,deflate,sdch";

            //__EventValidation
            string eventValidationFlag = "id=\"__EVENTVALIDATION\" value=\"";
            int i = respHtml.IndexOf(eventValidationFlag) + eventValidationFlag.Length;
            int j = respHtml.IndexOf("\"", i);
            string eventValidation = respHtml.Substring(i, j - i);
            eventValidation = System.Web.HttpUtility.UrlEncode(eventValidation);

            Cookie c = new Cookie("__utma", "168171965.1690722681.1337792889.1337792889.1337792889.1", "//", ".familytreedna.com");
            c.HttpOnly = true;
            request.CookieContainer.Add(c);
            c = new Cookie("__utmb", "168171965.1.10.1337792889", "//", ".familytreedna.com");
            c.HttpOnly = true;
            request.CookieContainer.Add(c);
            c = new Cookie("__utmc", "168171965", "//", ".familytreedna.com");
            c.HttpOnly = true;
            request.CookieContainer.Add(c);
            c = new Cookie("__utmz", "168171965.1337792889.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none)", "//", ".familytreedna.com");
            c.HttpOnly = true;
            request.CookieContainer.Add(c);
            c = new Cookie("genealogyMsg", "False", "//", ".familytreedna.com");
            c.HttpOnly = true;
            request.CookieContainer.Add(c);
            c = new Cookie("intYourResults", "False", "//", ".familytreedna.com");
            c.HttpOnly = true;
            request.CookieContainer.Add(c);
            c = new Cookie("relNotesMsg", "31", "//", ".familytreedna.com");
            c.HttpOnly = true;
            request.CookieContainer.Add(c);

            using (StreamWriter w = new StreamWriter(request.GetRequestStream()))
            {
                //                string payload = "__EVENTTARGET=ctl00%24MainContent%24gvMatchResults%24ctl01%24timer2&__EVENTARGUMENT=&__LASTFOCUS=&__VIEWSTATE=" + viewState + "&__VIEWSTATEENCRYPTED=&__EVENTVALIDATION=" + eventValidation + "&ctl00%24hfKitNum=" + userName + "&ctl00%24hfProceduresID=51&ctl00%24MainContent%24hfFilterText=&ctl00%24MainContent%24ddlFilterMatches=7&ctl00%24MainContent%24tbName=&ctl00%24MainContent%24tbSurnames=";
                string payload = "__EVENTTARGET=ctl00%24MainContent%24ddlFilterMatches&__EVENTARGUMENT=&__LASTFOCUS=&__VIEWSTATE=" + viewState + "&__VIEWSTATEENCRYPTED=&__EVENTVALIDATION=" + eventValidation + "&ctl00%24hfKitNum=" + userName + "&ctl00%24hfProceduresID=51&ctl00%24MainContent%24hfFilterText=&ctl00%24MainContent%24ddlFilterMatches=5&ctl00%24MainContent%24tbName=&ctl00%24MainContent%24tbSurnames=";
                w.Write(payload);
                w.Flush();
                w.Close();
            }
            resp = (HttpWebResponse)request.GetResponse();
            respHtml = (new StreamReader(resp.GetResponseStream())).ReadToEnd();

            viewState = ExtractViewState(respHtml);


            foreach (string relativeName in lstMatch)
            {
                //Get Data
                request = CreateRequest("https://my.familytreedna.com/family-finder-matches.aspx");
                request.Method = "POST";
                //request.Headers.Add("X-MicrosoftAjax", "Delta=true");
                request.ContentType = "application/x-www-form-urlencoded";

                //__EventValidation
                eventValidationFlag = "id=\"__EVENTVALIDATION\" value=\"";
                i = respHtml.IndexOf(eventValidationFlag) + eventValidationFlag.Length;
                j = respHtml.IndexOf("\"", i);
                eventValidation = respHtml.Substring(i, j - i);
                eventValidation = System.Web.HttpUtility.UrlEncode(eventValidation);

                c = new Cookie("genealogyMsg", "False", "//", ".familytreedna.com");
                c.HttpOnly = true;
                request.CookieContainer.Add(c);
                c = new Cookie("intYourResults", "False", "//", ".familytreedna.com");
                c.HttpOnly = true;
                request.CookieContainer.Add(c);
                c = new Cookie("relNotesMsg", "31", "//", ".familytreedna.com");
                c.HttpOnly = true;
                request.CookieContainer.Add(c);

                using (StreamWriter w = new StreamWriter(request.GetRequestStream()))
                {
                    string payload = "__EVENTTARGET=ctl00%24MainContent%24ddlRelativeName&__EVENTARGUMENT=&__LASTFOCUS=&__VIEWSTATE=" + viewState + "&__VIEWSTATEENCRYPTED=&__EVENTVALIDATION=" + eventValidation + "&ctl00%24hfKitNum=" + userName + "&ctl00%24hfProceduresID=51&ctl00%24MainContent%24hfFilterText=&ctl00%24MainContent%24ddlFilterMatches=5&ctl00%24MainContent%24ddlRelativeName=" + relativeName + "&ctl00%24MainContent%24tbName=&ctl00%24MainContent%24tbSurnames=&ctl00%24MainContent%24gvMatchResults%24ctl10%24assignRelationshipBtn=Assign";
                    w.Write(payload);
                    w.Flush();
                    w.Close();
                }
                resp = (HttpWebResponse)request.GetResponse();
                StreamReader sr = new StreamReader(resp.GetResponseStream());
                respHtml = sr.ReadToEnd();
                viewState = ExtractViewState(respHtml);

                //Save Data
                request = CreateRequest("https://my.familytreedna.com/family-finder-matches.aspx");
                request.Method = "POST";
                //request.Headers.Add("X-MicrosoftAjax", "Delta=true");
//.........这里部分代码省略.........
开发者ID:Bert6623,项目名称:Gedcom.Net,代码行数:101,代码来源:FamilyTreeDNA.cs

示例13: WriteICWFile

        private void WriteICWFile(string userName)
        {
            HttpWebRequest request = CreateRequest("https://my.familytreedna.com/family-finder-matches.aspx");
            HttpWebResponse resp = (HttpWebResponse)request.GetResponse();
            string respHtml = new StreamReader(resp.GetResponseStream()).ReadToEnd();
            string viewState = ExtractViewState(respHtml);

            StreamWriter swICW = new StreamWriter(WorkDir + userName + "_ICW.csv");

            try
            {
                //Go to In Common Quickly
                request = CreateRequest("https://my.familytreedna.com/family-finder-matches.aspx");
                request.Method = "POST";
                //request.Headers.Add("X-MicrosoftAjax", "Delta=true");
                request.ContentType = "application/x-www-form-urlencoded";
                request.KeepAlive = true;
                request.Referer = "https://my.familytreedna.com/family-finder-matches.aspx";
                //request.Accept = "gzip,deflate,sdch";

                //__EventValidation
                string eventValidationFlag = "id=\"__EVENTVALIDATION\" value=\"";
                int i = respHtml.IndexOf(eventValidationFlag) + eventValidationFlag.Length;
                int j = respHtml.IndexOf("\"", i);
                string eventValidation = respHtml.Substring(i, j - i);
                eventValidation = System.Web.HttpUtility.UrlEncode(eventValidation);

                Cookie c = new Cookie("__utma", "168171965.1690722681.1337792889.1337792889.1337792889.1", "//", ".familytreedna.com");
                c.HttpOnly = true;
                request.CookieContainer.Add(c);
                c = new Cookie("__utmb", "168171965.1.10.1337792889", "//", ".familytreedna.com");
                c.HttpOnly = true;
                request.CookieContainer.Add(c);
                c = new Cookie("__utmc", "168171965", "//", ".familytreedna.com");
                c.HttpOnly = true;
                request.CookieContainer.Add(c);
                c = new Cookie("__utmz", "168171965.1337792889.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none)", "//", ".familytreedna.com");
                c.HttpOnly = true;
                request.CookieContainer.Add(c);
                c = new Cookie("genealogyMsg", "False", "//", ".familytreedna.com");
                c.HttpOnly = true;
                request.CookieContainer.Add(c);
                c = new Cookie("intYourResults", "False", "//", ".familytreedna.com");
                c.HttpOnly = true;
                request.CookieContainer.Add(c);
                c = new Cookie("relNotesMsg", "31", "//", ".familytreedna.com");
                c.HttpOnly = true;
                request.CookieContainer.Add(c);

                using (StreamWriter w = new StreamWriter(request.GetRequestStream()))
                {
                    //                string payload = "__EVENTTARGET=ctl00%24MainContent%24gvMatchResults%24ctl01%24timer2&__EVENTARGUMENT=&__LASTFOCUS=&__VIEWSTATE=" + viewState + "&__VIEWSTATEENCRYPTED=&__EVENTVALIDATION=" + eventValidation + "&ctl00%24hfKitNum=" + userName + "&ctl00%24hfProceduresID=51&ctl00%24MainContent%24hfFilterText=&ctl00%24MainContent%24ddlFilterMatches=7&ctl00%24MainContent%24tbName=&ctl00%24MainContent%24tbSurnames=";
                    string payload = "__EVENTTARGET=ctl00%24MainContent%24ddlFilterMatches&__EVENTARGUMENT=&__LASTFOCUS=&__VIEWSTATE=" + viewState + "&__VIEWSTATEENCRYPTED=&__EVENTVALIDATION=" + eventValidation + "&ctl00%24hfKitNum=" + userName + "&ctl00%24hfProceduresID=51&ctl00%24MainContent%24hfFilterText=&ctl00%24MainContent%24ddlFilterMatches=5&ctl00%24MainContent%24tbName=&ctl00%24MainContent%24tbSurnames=";
                    w.Write(payload);
                    w.Flush();
                    w.Close();
                }
                resp = (HttpWebResponse)request.GetResponse();
                respHtml = (new StreamReader(resp.GetResponseStream())).ReadToEnd();

                viewState = ExtractViewState(respHtml);


                foreach (string relativeName in lstMatch)
                {
                    if (!hshMatch.Contains(relativeName))
                    {
                        Console.WriteLine("Skipping HASH ICW for " + relativeName);
                        continue;
                    }
                    string hashName = hshMatch[relativeName].ToString();

                    if (!icwMatch.Contains(hashName.Replace(" ", "")))
                    {
                        Console.WriteLine("Skipping ICW for " + hashName);
                        continue;
                    }

                    Console.WriteLine("Running ICW for " + hashName);
                    request = CreateRequest("https://my.familytreedna.com/family-finder-matches.aspx");
                    request.Method = "POST";
                    //request.Headers.Add("X-MicrosoftAjax", "Delta=true");
                    request.ContentType = "application/x-www-form-urlencoded";

                    //__EventValidation
                    eventValidationFlag = "id=\"__EVENTVALIDATION\" value=\"";
                    i = respHtml.IndexOf(eventValidationFlag) + eventValidationFlag.Length;
                    j = respHtml.IndexOf("\"", i);
                    eventValidation = respHtml.Substring(i, j - i);
                    eventValidation = System.Web.HttpUtility.UrlEncode(eventValidation);

                    c = new Cookie("genealogyMsg", "False", "//", ".familytreedna.com");
                    c.HttpOnly = true;
                    request.CookieContainer.Add(c);
                    c = new Cookie("intYourResults", "False", "//", ".familytreedna.com");
                    c.HttpOnly = true;
                    request.CookieContainer.Add(c);
                    c = new Cookie("relNotesMsg", "31", "//", ".familytreedna.com");
                    c.HttpOnly = true;
                    request.CookieContainer.Add(c);
//.........这里部分代码省略.........
开发者ID:Bert6623,项目名称:Gedcom.Net,代码行数:101,代码来源:FamilyTreeDNA.cs

示例14: runwork

        // Thread to scan
        private void runwork()
        {
            // Log in again
            if (!login())
            {
                SetStatus(statusWindow, "Will try to log on again in 10 seconds");
                hourTimer.Change(10000, 1000 * 60 * 60 * 4);
                scanner.Abort();
            }

            try
            {
                // List to save movies to db file
                List<string> downloadedTrailers = new List<string>();
                ObjectToSerialize trailerDBobject = new ObjectToSerialize();
                trailerDBobject.DownloadedTrailers = downloadedTrailers;

                // Scan for trailers
                SetStatus(statusWindow, "Scanning for new Trailers");
                string URL = "http://www.trailerfreaks.com/";
                HttpWebRequest webreq = (HttpWebRequest)WebRequest.Create(new System.Uri(URL));
                HttpWebResponse webres = (HttpWebResponse)webreq.GetResponse();
                Stream resStream = webres.GetResponseStream();
                string response = new StreamReader(resStream).ReadToEnd();
                // Find trailer
                string trailerStart = "a href =\"trai"; string toFind; string trailerName; string trailerDescription;
                string trailerDate; string trailerActors; string trailerNameClean; string trailerDetailsURL;
                int startindex, endindex;
                //int numToGet = 10000;
                //if (!numTrailersToGet.Equals("All"))
                //    numToGet = int.Parse(numTrailersToGet);
                //int count = 0;
                //while ((startindex = response.IndexOf(trailerStart)) > -1 && count < numToGet)
                while ((startindex = response.IndexOf(trailerStart)) > -1)
                {
                    bool skip = false;

                    if (startindex > -1)
                    {
                        response = response.Substring(startindex);
                    }
                    else
                    {
                        SetStatus(statusWindow, "Error Finding Trailer Page Links");
                        SetStatus(statusWindow, "Scanning aborted.");
                        enableControls(true);
                        scanner.Abort();
                    }
                    toFind = "title=\"";
                    startindex = response.IndexOf(toFind);
                    if (startindex > -1)
                    {
                        startindex += toFind.Length; // Move to starting position of new Trailer
                    }
                    else
                    {
                        SetStatus(statusWindow, "Error parsing for Trailer Name");
                        continue;
                    }
                    endindex = response.IndexOf("\"", startindex);
                    trailerName = response.Substring(startindex, endindex - startindex).Trim();
                    // Remove Year
                    trailerName = trailerName.Remove(trailerName.LastIndexOf(" "));
                    trailerNameClean = replaceSpecials(trailerName);
                    trailerNameClean = trailerNameClean.Remove(trailerNameClean.LastIndexOf(" "));
                    SetStatus(statusWindow, "Found Trailer: " + trailerName);
                    response = response.Substring(endindex);

                    // Check if it exists already in flat file
                    string trailerDB = Application.StartupPath + "\\trailerDB.txt";
                    if (!File.Exists(trailerDB))
                    {
                        if (verbose)
                            SetStatus(statusWindow, "New DB Created and will add Trailer after successfull download");
                    }
                    else
                    {
                        Serializer serializer = new Serializer();
                        trailerDBobject = serializer.DeSerializeObject(Application.StartupPath + "\\trailerDB.txt");
                        downloadedTrailers = trailerDBobject.DownloadedTrailers;
                        if (downloadedTrailers.Contains(trailerName + GetText(formatBox)))
                        {
                            SetStatus(statusWindow, "Already Downloaded, Skipping Trailer");
                            skip = true;
                        }
                        else
                        {
                            if (verbose)
                                SetStatus(statusWindow, "Not in DB will add Trailer after successfull download");
                        }
                    }

                    if (!skip)
                    {
                        // Get description
                        toFind = "<a href=\"";
                        startindex = response.IndexOf(toFind);
                        if (startindex > -1)
                        {
//.........这里部分代码省略.........
开发者ID:tmar89,项目名称:tmar89snapstreamdev,代码行数:101,代码来源:GUI.cs

示例15: Register

        public override bool Register(string username, string password)
        {
            this.username = username;
            HttpWebRequest getHeaders = (HttpWebRequest)HttpWebRequest.Create("https://rollin.io/ref/8c4");
            if (Prox != null)
                getHeaders.Proxy = Prox;
            var cookies = new CookieContainer();
            getHeaders.CookieContainer = cookies;

            try
            {
                HttpWebResponse Response = (HttpWebResponse)getHeaders.GetResponse();
                string s1 = new StreamReader(Response.GetResponseStream()).ReadToEnd();
                foreach (Cookie C in Response.Cookies)
                {
                    cookies.Add(C);
                }
                s1 = s1.Substring(s1.IndexOf("<input name=\"_token\" type=\"hidden\""));
                s1 = s1.Substring("<input name=\"_token\" type=\"hidden\" value=\"".Length);
                Token = s1.Substring(0, s1.IndexOf("\""));
            }
            catch
            {
                finishedlogin(false);
                return false;
            }
            HttpWebRequest betrequest = (HttpWebRequest)HttpWebRequest.Create("https://rollin.io/api/customer/settings/username");
            if (Prox != null)
                betrequest.Proxy = Prox;
            betrequest.CookieContainer = cookies;
            betrequest.Method = "POST";
            string post = string.Format("username={0}", username);
            betrequest.ContentLength = post.Length;
            betrequest.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
            betrequest.Headers.Add("X-CSRF-Token", Token);
            using (var writer = new StreamWriter(betrequest.GetRequestStream()))
            {

                writer.Write(post);
            }
            HttpWebResponse EmitResponse = (HttpWebResponse)betrequest.GetResponse();
            string sEmitResponse = new StreamReader(EmitResponse.GetResponseStream()).ReadToEnd();
            betrequest = (HttpWebRequest)HttpWebRequest.Create("https://rollin.io/api/customer/settings/password");
            if (Prox != null)
                betrequest.Proxy = Prox;
            betrequest.CookieContainer = cookies;
            betrequest.Method = "POST";
            post = string.Format("old=&new={0}&confirm={0}", password);
            betrequest.ContentLength = post.Length;
            betrequest.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
            betrequest.Headers.Add("X-CSRF-Token", Token);
            using (var writer = new StreamWriter(betrequest.GetRequestStream()))
            {
                writer.Write(post);
            }
            EmitResponse = (HttpWebResponse)betrequest.GetResponse();
            sEmitResponse = new StreamReader(EmitResponse.GetResponseStream()).ReadToEnd();

            HttpWebRequest betrequest2 = (HttpWebRequest)HttpWebRequest.Create("https://rollin.io/api/customer/info?username=" + username);
            if (Prox != null)
                betrequest2.Proxy = Prox;
            betrequest2.CookieContainer = cookies;
            betrequest2.Headers.Add("X-CSRF-Token", Token);
            HttpWebResponse EmitResponse2 = (HttpWebResponse)betrequest2.GetResponse();
            string sEmitResponse2 = new StreamReader(EmitResponse2.GetResponseStream()).ReadToEnd();
            RollinLoginStats tmpStats = json.JsonDeserialize<RollinLoginStats>(sEmitResponse2);

            //https://rollin.io/api/customer/sync
            betrequest2 = (HttpWebRequest)HttpWebRequest.Create("https://rollin.io/api/customer/sync");
            if (Prox != null)
                betrequest2.Proxy = Prox;
            betrequest2.CookieContainer = cookies;
            betrequest2.Headers.Add("X-CSRF-Token", Token);
            EmitResponse2 = (HttpWebResponse)betrequest2.GetResponse();
            sEmitResponse2 = new StreamReader(EmitResponse2.GetResponseStream()).ReadToEnd();
            RollinBet tmpStats2 = json.JsonDeserialize<RollinBet>(sEmitResponse2);

            if (tmpStats.success && tmpStats2.success)
            {
                ClientHandlr = new HttpClientHandler { UseCookies = true };
                Client = new HttpClient(ClientHandlr) { BaseAddress = new Uri("https://rollin.io/api/") };
                ClientHandlr.CookieContainer = this.Cookies;
                Client.DefaultRequestHeaders.Add("X-CSRF-Token", Token);

                GetDeposit();
                balance = double.Parse(tmpStats2.customer.balance, System.Globalization.NumberFormatInfo.InvariantInfo) / 1000.0; //i assume
                bets = tmpStats.user.bets;
                profit = double.Parse(tmpStats.user.profit, System.Globalization.NumberFormatInfo.InvariantInfo) / 1000.0;

                Parent.updateBalance((decimal)(balance));
                Parent.updateBets(tmpStats.user.bets);
                Parent.updateLosses(tmpStats.user.losses);
                Parent.updateProfit(double.Parse(tmpStats.user.profit, System.Globalization.NumberFormatInfo.InvariantInfo) / 1000.0);
                Parent.updateWagered(double.Parse(tmpStats.user.wagered, System.Globalization.NumberFormatInfo.InvariantInfo) / 1000.0);
                Parent.updateWins(tmpStats.user.wins);

                finishedlogin(true);
                return true;
            }
            finishedlogin(false);
//.........这里部分代码省略.........
开发者ID:bdcravens,项目名称:DiceBot,代码行数:101,代码来源:rollin.cs


注:本文中的System.IO.StreamReader.IndexOf方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。