public RaygunRequestMessage(HttpContext context)
        {
            HostName = context.Request.Url.Host;
              Url = context.Request.Url.AbsolutePath;
              HttpMethod = context.Request.RequestType;
              IPAddress = context.Request.UserHostAddress;
              Data = ToDictionary(context.Request.ServerVariables);
              QueryString = ToDictionary(context.Request.QueryString);
              Headers = ToDictionary(context.Request.Headers);
              Form = ToDictionary(context.Request.Form, true);

              try
              {
            var contentType = context.Request.Headers["Content-Type"];
            if (contentType != "text/html" && contentType != "application/x-www-form-urlencoded" && context.Request.RequestType != "GET")
            {
              int length = 4096;
              string temp = new StreamReader(context.Request.InputStream).ReadToEnd();
              if (length > temp.Length)
              {
            length = temp.Length;
              }

              RawData = temp.Substring(0, length);
            }
              }
              catch (HttpException)
              {
              }
        }
Exemplo n.º 2
0
        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;
        }
        /// <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>();
        }
        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="******"&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;
            }
            
        }
Exemplo n.º 5
0
        public void Main(string[] args)
        {
            foreach (var kvp in _pathToResource)
            {
                var success = true;
                var fileContent = new StreamReader(new FileStream(kvp.Key, FileMode.Open)).ReadToEnd();
                var resourceContent = new StreamReader(_assembly.GetManifestResourceStream(kvp.Value)).ReadToEnd();
                if (fileContent.Length > resourceContent.Length)
                {
                    success = false;
                    Console.WriteLine($"{ kvp.Key } is { fileContent.Length - resourceContent.Length } chars longer than { kvp.Value }.");
                    Console.WriteLine($"\tFile ends with     '...{ fileContent.Substring(fileContent.Length - 20) }'.");
                    Console.WriteLine($"\tResource ends with '...{ resourceContent.Substring(resourceContent.Length - 20) }'.");
                }
                else if (fileContent.Length < resourceContent.Length)
                {
                    success = false;
                    Console.WriteLine($"{ kvp.Key } is { resourceContent.Length - fileContent.Length } chars shorter than { kvp.Value }.");
                    Console.WriteLine($"\tFile ends with     '...{ fileContent.Substring(fileContent.Length - 20) }'.");
                    Console.WriteLine($"\tResource ends with '...{ resourceContent.Substring(resourceContent.Length - 20) }'.");
                }
                else
                {
                    for (var i = 0; i < fileContent.Length; i++)
                    {
                        if (fileContent[i] != resourceContent[i])
                        {
                            success = false;

                            var length = (i + 20 > fileContent.Length) ? fileContent.Length - i : 20;
                            Console.WriteLine($"Mismatch at index '{ i }' in { kvp.Key }.");
                            Console.WriteLine($"\tFile contains     '...{ fileContent.Substring(i, length) }'.");
                            Console.WriteLine($"\tResource contains '...{ resourceContent.Substring(i, length) }'.");
                            break;
                        }
                    }
                }

                if (success)
                {
                    Console.WriteLine($"Success for { kvp.Key }.");
                }
            }
        }
Exemplo n.º 6
0
        public void write(string data)
        {

            Request.InputStream.Seek(0, SeekOrigin.Begin);
            string jsonData = new StreamReader(Request.InputStream).ReadToEnd();
            String subject = jsonData.Split('<')[0];
            int subjectId = Int32.Parse(subject);
            String xaml = jsonData.Substring(subject.Length);
      
            _db.WS_Subjects.Find(subjectId).Xaml_Data = xaml;
           _db.SaveChanges();
        }
Exemplo n.º 7
0
        /*
         * 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;
            }
        }
Exemplo n.º 8
0
 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"));
 }
Exemplo n.º 9
0
        public RaygunRequestMessage(HttpContext context)
        {
            HostName = context.Request.Url.Host;
              Url = context.Request.Url.AbsolutePath;
              HttpMethod = context.Request.RequestType;
              IPAddress = context.Request.UserHostAddress;
              Data = ToDictionary(context.Request.ServerVariables);
              QueryString = ToDictionary(context.Request.QueryString);
              Headers = ToDictionary(context.Request.Headers);
              Form = new NameValueCollection();

              foreach (string s in context.Request.Form)
              {
            if (String.IsNullOrEmpty(s)) continue;

            string name = s;
            string value = context.Request.Form[s];

            if (s.Length > 256)
            {
              name = s.Substring(0, 256);
            }

            if (value.Length > 256)
            {
              value = value.Substring(0, 256);
            }

            Form.Add(name, value);
              }

              try
              {
            var contentType = context.Request.Headers["Content-Type"];
            if (contentType != "text/html" && contentType != "application/x-www-form-urlencoded" && context.Request.RequestType != "GET")
            {
              int length = 4096;
              string temp = new StreamReader(context.Request.InputStream).ReadToEnd();
              if (length > temp.Length)
              {
            length = temp.Length;
              }

              RawData = temp.Substring(0, length);
            }
              }
              catch (HttpException)
              {
              }
        }
Exemplo n.º 10
0
    void RequestParse()
    {
        // (ToDo: find a proper URL encoding solution!)
        string input = currentInput;

        if (input.ToLower().StartsWith("diana,"))
        {
            input = input.Substring(6).TrimStart();
        }
        if (input.ToLower().StartsWith("please"))
        {
            input = input.Substring(6).TrimStart();
        }
        input = input.Replace(" ", "+");
        input = input.Replace("%", "%25");
        input = input.Replace("&", "%26");
        input = input.Replace("?", "%3F");
        string dataStr = "outputFormat=json&Process=Submit&input=" + input;

        byte[] data = System.Text.Encoding.UTF8.GetBytes(dataStr);

        // Also ToDo: find an async method, or move this into a thread
        WebRequest request = WebRequest.Create("http://nlp.stanford.edu:8080/corenlp/process");

        request.Method        = WebRequestMethods.Http.Post;
        request.ContentType   = "application/x-www-form-urlencoded";
        request.ContentLength = data.Length;
        using (var stream = request.GetRequestStream()) {
            stream.Write(data, 0, data.Length);
        }
        var response       = (HttpWebResponse)request.GetResponse();
        var responseString = new System.IO.StreamReader(response.GetResponseStream()).ReadToEnd();

        int    startPos = responseString.IndexOf("<pre>") + 5;
        int    endPos   = responseString.IndexOf("</pre>");
        string json     = responseString.Substring(startPos, endPos - startPos);

        json = json.Replace("&nbsp;", " ").Replace("&quot;", "\"").Replace("&amp;", "&");
        JSONNode root = JSON.Parse(json);

        var sentenceList = root["sentences"];

        if (sentenceList.Count > 0)
        {
            JSONNode tokens       = sentenceList[0]["tokens"];
            JSONNode dependencies = sentenceList[0]["basic-dependencies"];
            Word     tree         = JsonToTree(tokens as JSONArray, dependencies as JSONArray);
            newParse = tree;                    // (store the data for the main thread)
        }
    }
Exemplo n.º 11
0
 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;
 }
    public RaygunRequestMessage(HttpRequest request, RaygunRequestMessageOptions options)
    {
      options = options ?? new RaygunRequestMessageOptions();

      HostName = request.Url.Host;
      Url = request.Url.AbsolutePath;
      HttpMethod = request.RequestType;
      IPAddress = GetIpAddress(request);
      
      QueryString = ToDictionary(request.QueryString, null);

      Headers = ToDictionary(request.Headers, options.IsHeaderIgnored);
      Headers.Remove("Cookie");

      Form = ToDictionary(request.Form, options.IsFormFieldIgnored, true);
      Cookies = GetCookies(request.Cookies, options.IsCookieIgnored);

      // Remove ignored and duplicated variables
      Data = ToDictionary(request.ServerVariables, options.IsServerVariableIgnored);
      Data.Remove("ALL_HTTP");
      Data.Remove("HTTP_COOKIE");
      Data.Remove("ALL_RAW");

      try
      {
        var contentType = request.Headers["Content-Type"];
        if (contentType != "text/html" && contentType != "application/x-www-form-urlencoded" && request.RequestType != "GET")
        {
          int length = 4096;
          request.InputStream.Seek(0, SeekOrigin.Begin);
          string temp = new StreamReader(request.InputStream).ReadToEnd();
          if (length > temp.Length)
          {
            length = temp.Length;
          }

          RawData = temp.Substring(0, length);
        }
      }
      catch (HttpException)
      {
      }
    }
Exemplo n.º 13
0
        public async Task DebugConsoleOnReceivedTests(bool connect)
        {
            // Setup
            var env = new Mock<IEnvironment>();
            var tracer = new Mock<ITracer>();
            var settings = new Mock<IDeploymentSettingsManager>();
            var process = new Mock<IProcess>();
            var connectionId = Guid.NewGuid().ToString();
            var data = Guid.NewGuid().ToString();
            var mem = new MemoryStream();

            using (var controller = new PersistentCommandTest(env.Object, settings.Object, tracer.Object, process.Object))
            {
                // Setup
                process.SetupGet(p => p.StandardInput)
                       .Returns(new StreamWriter(mem));

                // Test
                if (connect)
                {
                    await controller.Connect(Mock.Of<IRequest>(), connectionId);
                }

                await controller.Receive(Mock.Of<IRequest>(), connectionId, data);

                // Assert
                Assert.Equal(1, PersistentCommandTest.ProcessCount);

                if (connect)
                {
                    Assert.True(mem.Position > 0, "must write data");

                    mem.Position = 0;
                    var result = new StreamReader(mem).ReadToEnd();
                    Assert.True(result.EndsWith("\r\n"));
                    Assert.Equal(data, result.Substring(0, result.Length - 2));
                }
                else
                {
                    Assert.True(mem.Position == 0, "must skip data");
                }
            }
        }
        /// <summary>
        /// Processes the standard output and populates the relevant test result data of the referenced collection
        /// </summary>
        /// <param name="collection">test result collection where the leak information data will be inserted at</param>
        public override void Parse(TestResultCollection collection)
        {
            // NOTE Disposing is handled by parent class
            string strConsoleOutput = new StreamReader(this.InputStream).ReadToEnd();

            //the below regex is intended to only to "detect" if any memory leaks are present. Note that any console output printed by the test generally appears before the memory leaks dump.
            Regex regexObj = new Regex(@"Detected\smemory\sleaks!\nDumping objects\s->\n(.*)Object dump complete.", RegexOptions.IgnoreCase | RegexOptions.Singleline | RegexOptions.Multiline);
            Match outputMatch = regexObj.Match(strConsoleOutput);

            //leak has been detected
            if (outputMatch.Success)
            {
                RegisterMemoryLeak(outputMatch.Groups[1].Value, collection);
            }

            // Extract non-memory leak output
            string output = strConsoleOutput.Substring(0, ((outputMatch.Success) ? outputMatch.Index : strConsoleOutput.Length));
            RegisterMessages(output, collection);
        }
Exemplo n.º 15
0
        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);
        }
Exemplo n.º 16
0
        public void Execute(IJobExecutionContext context)
        {
            try
            {
                var urls = context.Get("urls").ToString().Split(',');

                urls.ToList().ForEach(url =>
                {
                    var request = (HttpWebRequest)WebRequest.Create(url);
                    var s = new Stopwatch();
                    s.Start();
                    using (var response = (HttpWebResponse)request.GetResponse())
                    using (var stream = response.GetResponseStream())
                    {
                        string ret = string.Empty;
                        if (stream != null)
                        {
                            string readToEnd = new StreamReader(stream).ReadToEnd();
                            ret = string.Format("{0}...", readToEnd.Substring(0, 500));
                        }
                        s.Stop();

                        Publish(new PingerModel()
                        {
                            Time = DateTime.Now,
                            Url = url,
                            response = ret,
                            Status = response.StatusCode.ToString(),
                            StatusDescription = response.StatusDescription,
                            Duration = s.Elapsed,
                            ContentLength = response.ContentLength,
                            ContentType = response.ContentType
                        });
                    }
                });
            }
            catch (Exception ex)
            {
                throw new JobExecutionException(ex);
            }
        }
Exemplo n.º 17
0
        public RaygunRequestMessage(HttpRequest request, List<string> ignoredFormNames)
        {
            HostName = request.Url.Host;
              Url = request.Url.AbsolutePath;
              HttpMethod = request.RequestType;
              IPAddress = request.UserHostAddress;
              IEnumerable<string> empty = new List<string>();
              QueryString = ToDictionary(request.QueryString, empty);

              Headers = ToDictionary(request.Headers, ignoredFormNames ?? empty);
              Headers.Remove("Cookie");

              Form = ToDictionary(request.Form, ignoredFormNames ?? empty, true);
              Cookies = GetCookies(request.Cookies, ignoredFormNames ?? empty);

              // Remove ignored and duplicated variables
              Data = ToDictionary(request.ServerVariables, ignoredFormNames ?? empty);
              Data.Remove("ALL_HTTP");
              Data.Remove("HTTP_COOKIE");
              Data.Remove("ALL_RAW");

              try
              {
            var contentType = request.Headers["Content-Type"];
            if (contentType != "text/html" && contentType != "application/x-www-form-urlencoded" && request.RequestType != "GET")
            {
              int length = 4096;
              string temp = new StreamReader(request.InputStream).ReadToEnd();
              if (length > temp.Length)
              {
            length = temp.Length;
              }

              RawData = temp.Substring(0, length);
            }
              }
              catch (HttpException)
              {
              }
        }
Exemplo n.º 18
0
        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);
        }
Exemplo n.º 19
0
        private Stock GetStockQuote(string stockSymbol)
        {
            GoogleStock googleStock = new GoogleStock();
            List<GoogleStock> stockArray = new List<GoogleStock>();
            string url = "http://www.google.com/finance/info?infotype=infoquoteall&q=" + stockSymbol;
            WebRequest request = WebRequest.Create(url);
            WebResponse ws = request.GetResponse();
            DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(GoogleStock));
            try
            {
                String json = new StreamReader(ws.GetResponseStream()).ReadToEnd();
                String jsonWithPrefixSlashesRemoved = json.Substring(3);
                stockArray = JsonConvert.DeserializeObject<List<GoogleStock>>(jsonWithPrefixSlashesRemoved);

            } catch(Exception e)
            {
                string error = e.ToString();
                return null;
            }

            return ConvertGoogleStockToStock(stockArray[0]);
        }
Exemplo n.º 20
0
        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");
                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=&__EVENTARGUMENT=&__LASTFOCUS=&__VIEWSTATE=" + viewState + "&__VIEWSTATEENCRYPTED=&__EVENTVALIDATION=" + eventValidation + "&ctl00%24hfKitNum=" + userName + "&ctl00%24hfProceduresID=51&ctl00%24MainContent%24hfFilterText=&ctl00%24MainContent%24ddlFilterMatches=0&ctl00%24MainContent%24tbName=&ctl00%24MainContent%24tbSurnames=&ctl00%24MainContent%24gvMatchResults%24ctl10%24assignRelationshipDdl=15&ctl00%24MainContent%24gvMatchResults%24ctl10%24saveRelationshipBtn=Save";
                    w.Write(payload);
                    w.Flush();
                    w.Close();
                }
                resp = (HttpWebResponse)request.GetResponse();
                respHtml = new StreamReader(resp.GetResponseStream()).ReadToEnd();


            }
        }
Exemplo n.º 21
0
        private void SetDefaultColorOfTextInXmlStream(Stream s)
        {
            /*
            XmlDocument xml = new XmlDocument();
            long beginLength = s.Length;
            xml.Load(s);
            s.Seek(0, SeekOrigin.Begin); // Because Load moved the caret to the end of the stream, and later we need it.
            XmlNode node = xml.FirstChild;
            while (node.Name != "Section" || node.NextSibling != null)
                node = node.NextSibling;

            node.Attributes["Foreground"].Value = this._rtb.Foreground.ToString(); // set the xml default color to the foreground color of the RichTextBox

            XmlTextWriter xmlWriter = new XmlTextWriter(s, Encoding.Default);
            xmlWriter.Formatting = Formatting.None;
            if (beginLength > s.Length)
                throw new InvalidOperationException();
            xml.Save(xmlWriter);
            long endPosition = xmlWriter.BaseStream.Position;
            if (s.Length > endPosition)
                s.SetLength(endPosition); // prevent garbage text on the end of the file to affect the xml reading methods

            s.Seek(0, SeekOrigin.Begin);
            String str = new StreamReader(s).ReadToEnd();
            s.Seek(0, SeekOrigin.Begin);
            /*/
            string foregroundAttributeString = "Foreground=\"";
            String str = new StreamReader(s).ReadToEnd();
            int startIndex = str.IndexOf("Section", 0);
            int endIndex = str.IndexOf('>', startIndex);
            int modStartIndex = str.IndexOf(foregroundAttributeString, startIndex, endIndex - startIndex + 1) + foregroundAttributeString.Length;
            int modEndIndex = str.IndexOf("\"", modStartIndex);
            StringBuilder sb = new StringBuilder();
            sb.Append(str.Substring(0, modStartIndex));
            sb.Append(this._rtb.Foreground.ToString());
            sb.Append(str.Substring(modEndIndex));
            s.Seek(0, SeekOrigin.Begin);
            new StreamWriter(s).Write(sb.ToString());

            //*/
        }
Exemplo n.º 22
0
        private void ReceiveMessage()
        {
            bool NoCopeMsg;

            List<Socket> list = new List<Socket>(clients);
            if (list.Count > 0) Socket.Select(list, null, null, 200);//проверяем те, с которых ещё можно читать
            foreach (Socket socket in list)
            {
                NoCopeMsg = true;
                string key_msg;
                string msg = new StreamReader(new NetworkStream(socket)).ReadLine();
                key_msg = KeyControl.KeyLook(msg);
                foreach (string str in message)
                {
                    if (String.Compare(str, key_msg, true) == 0)
                    {
                        NoCopeMsg = false;
                        break;
                    }
                }
                if (NoCopeMsg)
                {
                    List<Socket> list2 = new List<Socket>(clients);//напишет всем своим клиентам
                    if (list2.Count > 0) Socket.Select(null, list2, null, 200);//только те, что на запись
                    foreach (Socket socket1 in list2)
                    {
                        try
                        {
                            if (socket1 != socket)
                            {
                                StreamWriter msgs = new StreamWriter(new NetworkStream(socket1));
                                msgs.WriteLine(msg);
                                msgs.Flush();
                            }
                        }
                        catch (Exception)
                        {
                            Console.WriteLine("Один из пользователей покинул чат");
                            clients.Remove(socket1);
                        }
                    }
                    //напишем и себе
                    Console.WriteLine(msg.Substring(key_msg.Length + 1));
                    message.Add(key_msg);
                }
            }
        }
Exemplo n.º 23
0
        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));
                Parent.updateBets(tmp.NumBets);
                Parent.updateLosses(tmp.Losses);
                Parent.updateProfit(profit);
                Parent.updateWagered(wagered);
                Parent.updateWins(tmp.Wins);
                //Parent.updateDeposit(tmp.DepositAddress);
                getHeaders = HttpWebRequest.Create("https://pocketrocketscasino.eu/account/GetCurrentSeed") as HttpWebRequest;
                if (Prox != null)
                    getHeaders.Proxy = Prox;
                getHeaders.CookieContainer = Cookies;
                Response = (HttpWebResponse)getHeaders.GetResponse();
                s1 = new StreamReader(Response.GetResponseStream()).ReadToEnd();
                prcSeed getseed = json.JsonDeserialize<prcSeed>(s1);
                client = getseed.ClientSeed;
                serverhash = getseed.ServerHash;
                getHeaders = HttpWebRequest.Create("https://pocketrocketscasino.eu/account/getDepositAddress") as HttpWebRequest;
                if (Prox != null)
                    getHeaders.Proxy = Prox;
                getHeaders.CookieContainer = Cookies;
                Response = (HttpWebResponse)getHeaders.GetResponse();
                s1 = new StreamReader(Response.GetResponseStream()).ReadToEnd();
                PRCDepost dep = json.JsonDeserialize<PRCDepost>(s1);
                Parent.updateDeposit(dep.Address);
                finishedlogin(true);
                return true;
            }
            catch
            {
                finishedlogin(false);
                return false;
            }
        }
Exemplo n.º 24
0
        public override void Login(string Username, string Password, string twofa)
        {
            HttpWebRequest getHeaders = HttpWebRequest.Create("https://pocketrocketscasino.eu/play/#dice") 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);
                s = rqtoken = tmp.Substring(0, tmp.IndexOf("\""));
            }
            catch (WebException e)
            {
                System.Windows.Forms.MessageBox.Show("Failed to log in. Please check your username and password.");
                finishedlogin(false);
            }
            
            getHeaders = HttpWebRequest.Create("https://pocketrocketscasino.eu/account/login") as HttpWebRequest;
            if (Prox != null)
                getHeaders.Proxy = Prox;
            getHeaders.CookieContainer = new CookieContainer();
            foreach (Cookie c in Response.Cookies)
            {
                
                getHeaders.CookieContainer.Add(c);
            }
            getHeaders.Method = "POST";
            string post = string.Format("userName={0}&password={1}&twoFactorCode={2}&__RequestVerificationToken={3}", Username, Password, twofa, 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();
                string s1 = new StreamReader(Response.GetResponseStream()).ReadToEnd();
                if (!s1.ToLower().Contains("success"))
                {
                    System.Windows.Forms.MessageBox.Show("Failed to log in. Please check your username and password.");
                    finishedlogin(false);
                }
                /*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;
                string s1 = new StreamReader(Response.GetResponseStream()).ReadToEnd();
                System.Windows.Forms.MessageBox.Show("Failed to log in. Please check your username and password.");
                finishedlogin(false);
            }
            
            foreach (Cookie c in Response.Cookies)
            {
                if (c.Name == "__RequestVerificationToken")
                    rqtoken = c.Value;
                Cookies.Add(c);
            }
            Cookies.Add((new Cookie("PRC_Affiliate", "357", "/", "pocketrocketscasino.eu")));
            con.CookieContainer = Cookies;
            try
            {
                getHeaders = HttpWebRequest.Create("https://pocketrocketscasino.eu/play/#dice") 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();

                dicehub.Invoke("joinChatRoom", 1);
                dicehub.On<string, string, string, int, int, bool>("chat", ReceivedChat);
                dicehub.On<string, string, string, int, bool>("receivePrivateMesssage", ReceivedChat);

                getHeaders = HttpWebRequest.Create("https://pocketrocketscasino.eu/account/GetUserAccount") as HttpWebRequest;
                if (Prox != null)
                    getHeaders.Proxy = Prox;
                getHeaders.CookieContainer = Cookies;
                Response = (HttpWebResponse)getHeaders.GetResponse();
                string 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));
                Parent.updateBets(tmp.NumBets);
                Parent.updateLosses(tmp.Losses);
                Parent.updateProfit(profit);
                Parent.updateWagered(wagered);
                Parent.updateWins(tmp.Wins);
                //Parent.updateDeposit(tmp.DepositAddress);
                getHeaders = HttpWebRequest.Create("https://pocketrocketscasino.eu/account/GetCurrentSeed") as HttpWebRequest;
                if (Prox != null)
                    getHeaders.Proxy = Prox;
                getHeaders.CookieContainer = Cookies;
                Response = (HttpWebResponse)getHeaders.GetResponse();
                s1 = new StreamReader(Response.GetResponseStream()).ReadToEnd();
                prcSeed getseed = json.JsonDeserialize<prcSeed>(s1);
                client = getseed.ClientSeed;
                serverhash = getseed.ServerHash;
                getHeaders = HttpWebRequest.Create("https://pocketrocketscasino.eu/account/getDepositAddress") as HttpWebRequest;
                if (Prox != null)
                    getHeaders.Proxy = Prox;
                getHeaders.CookieContainer = Cookies;
                Response = (HttpWebResponse)getHeaders.GetResponse();
                s1 = new StreamReader(Response.GetResponseStream()).ReadToEnd();
                PRCDepost dep = json.JsonDeserialize<PRCDepost>(s1);
                Parent.updateDeposit(dep.Address);
                finishedlogin(true);
            }
            catch
            {
                
            }
        }
        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="******"&password="******"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();
            }
        }
Exemplo n.º 26
0
        /// <summary>
        /// http://en.wikipedia.org/wiki/Wavefront_.obj_file
        /// </summary>
        /// <param name="filename"></param>
        /// <returns></returns>
        public static Mesh LoadObjFile(string filename)
        {
            var file = Filepaths.GetModelFileInfo(filename);
            if (!file.Exists)
                throw new ModelException(StandardExceptions.NewFileNotFound(file));
            string src;
            using (var s = new StreamReader(file.FullName))
            {
                src = s.ReadToEnd();
            }

            var lines = src.Split('\n').Where(s => !s.StartsWith("#")).ToList();

            var vertexs = new List<Vector3>();
            var vertexTextures = new List<Vector2>();
            var vertexNormals = new List<Vector3>();

            foreach (
                var xyzw in
                    lines.Where(s => s.StartsWith("v "))
                         .Select(s => s.Substring(s.IndexOf(' ') + 1).Split(' '))
                         .ToList())
            {
                string x = "", y = "", z = "", w = "";
                if (xyzw.Length >= 1)
                    x = xyzw[0];
                if (xyzw.Length >= 2)
                    y = xyzw[1];
                if (xyzw.Length >= 3)
                    z = xyzw[2];
                if (xyzw.Length == 4)
                    w = xyzw[3];
                // TODO: Vertex4 for position in the Vertex class
                vertexs.Add(new Vector3(float.Parse(x), float.Parse(y), float.Parse(z)));
            }

            // TODO: .mtl and that stuff
            foreach (
                var uvw in
                    lines.Where(s => s.StartsWith("vt "))
                         .Select(s => s.Substring(s.IndexOf(' ') + 1).Split(' '))
                         .ToList())
            {
                string u = "", v = "", w = "";
                if (uvw.Length >= 1)
                    u = uvw[0];
                if (uvw.Length >= 2)
                    v = uvw[1];
                if (uvw.Length == 3)
                    w = uvw[3];
                // TODO: Vertex3 for texture in the Vertex class
                vertexTextures.Add(new Vector2(float.Parse(u), float.Parse(v)));
            }

            foreach (
                var xyz in
                    lines.Where(s => s.StartsWith("vn "))
                         .Select(s => s.Substring(s.IndexOf(' ') + 1).Split(' '))
                         .ToList())
            {
                string x = "", y = "", z = "";
                if (xyz.Length >= 1)
                    x = xyz[0];
                if (xyz.Length >= 2)
                    y = xyz[1];
                if (xyz.Length >= 3)
                    z = xyz[2];
                vertexNormals.Add(new Vector3(float.Parse(x), float.Parse(y), float.Parse(z)).Normalized());
            }

            // TODO: lines starting with vp

            var vertices = new List<Vertex>();
            var indices = new List<int>();

            foreach (
                var face in
                    lines.Where(s => s.StartsWith("f "))
                         .Select(s => s.Substring(s.IndexOf(' ') + 1).Split(' '))
                         .ToList())
            {
                for (int i = 0; i < face.Length - 2; i++)
                {
                    for (int j = 0; j < 3; j++)
                    {
                        string[] vert = face[i + j].Split('/');
                        int v = 0, t = 0, n = 0;
                        v = int.Parse(vert[0]);
                        if (vert.Length >= 2 && vert[1] != string.Empty)
                            t = int.Parse(vert[1]);
                        if (vert.Length == 3)
                            n = int.Parse(vert[2]);

                        Vector3 position = vertexs[v - 1];
                        Vector2 texture = Vector2.Zero;
                        if (t != 0)
                            texture = vertexTextures[t - 1];
                        Vector3 normal = Vector3.Zero;
                        if (n != 0)
                            normal = vertexNormals[n - 1];

                        vertices.Add(new Vertex(position, normal, texture));
                        indices.Add(indices.Count);
                    }
                }
            }

            var mesh = new Mesh(
                BufferLibrary.CreateVertexBuffer(filename, vertices.ToArray()),
                BufferLibrary.CreateIndexBuffer(
                    filename, indices.Select(i => (uint) i).ToArray(), PrimitiveType.Triangles),
                indices.Count, PrimitiveType.Triangles);
            AddMesh(mesh, filename);
            return mesh;
        }
Exemplo n.º 27
0
        public void Login(string userName, string password)
        {
            StreamWriter swlog = new StreamWriter(WorkDir + "../" + userName + ".log", true);
            swlog.AutoFlush = true;

            HttpWebRequest request = CreateRequest("https://my.familytreedna.com/login.aspx");
            request.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(userName + ":" + password)));
            HttpWebResponse resp = (HttpWebResponse)request.GetResponse();
            string respHtml = new StreamReader(resp.GetResponseStream()).ReadToEnd();
            string viewState = ExtractViewState(respHtml);
           
            try { swlog.WriteLine("Login " + userName + "/" + password); }
            catch { }

            request = CreateRequest("https://my.familytreedna.com/login.aspx");
            request.Method = "POST";
            request.Headers.Add("X-MicrosoftAjax", "Delta=true");
            request.ContentType = "application/x-www-form-urlencoded";
            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);
            
            //__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);

            using (StreamWriter w = new StreamWriter(request.GetRequestStream()))
            {
                string payload = "__EVENTTARGET=&__EVENTARGUMENT=&__EVENTVALIDATION=" + eventValidation + "&__VIEWSTATE=" + viewState + "&LoginView1%24Login1%24UserName="******"&" + "LoginView1%24Login1%24Password="******"&LoginView1%24Login1%24LoginButton=Log+In&LoginView1%24txtKit=&LoginView1%24txtEmail";
                w.Write(payload);
                w.Flush();
                w.Close();
            }
            resp = (HttpWebResponse)request.GetResponse();
            respHtml = new StreamReader(resp.GetResponseStream()).ReadToEnd();

            //Now get the real screen
            //System.Threading.Thread.Sleep(1500);
            request = CreateRequest("https://my.familytreedna.com/");
            resp = (HttpWebResponse)request.GetResponse();
            respHtml = new StreamReader(resp.GetResponseStream()).ReadToEnd();

            try { swlog.WriteLine("Family Finder"); }
            catch { }

            swMatch = new StreamWriter(WorkDir + userName + "_Family_Finder_Matches.csv");
            swMatch.WriteLine("Full Name,Match Date,Relationship Range,Suggested Relationship,Shared cM,Longest Block,Known Relationship,E-mail,Ancestral Surnames (Bolded names match your surnames),notes");
            WriteMatchFile(userName);
            swMatch.Flush();
            swMatch.Close();

            //System.Threading.Thread.Sleep(1500);
            request = CreateRequest("https://my.familytreedna.com/family-finder-chromosome-browser_v2.aspx");
            resp = (HttpWebResponse)request.GetResponse();
            respHtml = new StreamReader(resp.GetResponseStream()).ReadToEnd();

            bool repeat = true;
            int rownum = 0;
            int totalcount = 0;
            int page = 1;
            string name = String.Empty;
            string resultid2 = String.Empty;
            //fswSurname = new StreamWriter(userName + "_SurnameList.csv");
            //swSurname.WriteLine("Full Name,Match Date,Relationship Range,Suggested Relationship,Shared cM,Longest Block,Known Relationship,E-mail,Ancestral Surnames (Bolded names match your surnames),notes");
            StreamWriter swchrom = new StreamWriter(WorkDir + userName + "_ChromsomeBrowser.csv");
            while (repeat)
            {
                request = CreateRequest("https://my.familytreedna.com/ftdnawebservice/FamilyFinderOmni700.asmx/getMatchdata");
                request.Method = "POST";
                request.ContentType = "application/json; charset=utf-8";
                string postData = "{'ekit': 'SX67iaoAkkw%3d','page': '" + page.ToString() + "','filter': '0','hide3rdparty': 'false', name: ''}";
                using (Stream s = request.GetRequestStream())
                {
                    using (StreamWriter sw = new StreamWriter(s))
                        sw.Write(postData);
                }

                //get response-stream, and use a streamReader to read the content
                using (Stream s = request.GetResponse().GetResponseStream())
                {
                    using (StreamReader sr = new StreamReader(s))
                    {
                        string jsonData = sr.ReadToEnd();
                        jsonData.Replace("{\"d\":[", "").Replace("]}", "");
                        try
                        {
                            foreach (string rec in jsonData.Split('{'))
                            {
                                foreach (string field in rec.Split(','))
                                {
                                    if (field.StartsWith("\"name\":"))
                                    {
                                        name = field.Substring(8, field.Length - 8);
                                    }
                                    if (field.StartsWith("\"resultid2\":"))
                                    {
                                        resultid2 = field.Substring(12, field.Length - 12);
                                        if (!lstMatch.Contains(resultid2))
                                            lstMatch.Add(resultid2);

                                    }
                                    if (field.StartsWith("\"totalcount\":"))
                                    {
                                        totalcount = int.Parse(field.Substring(13, field.Length - 13));
                                        //Console.WriteLine(field.Substring(13, field.Length - 13));
                                    }
                                    if (field.StartsWith("\"rownum\":"))
                                    {
                                        rownum = int.Parse(field.Substring(9, field.Length - 9));
                                        //Console.WriteLine(field.Substring(7, field.Length - 7));
                                        if (rownum == totalcount)
                                            repeat = false;
                                    }
                                }

                                if (resultid2.Trim().Length > 0)
                                    WriteChromosome(swchrom, name, resultid2);
                                swchrom.Flush();
                                resultid2 = String.Empty;
                            }
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(ex.Message + ": " + ex.StackTrace);
                        }

                        page++;
                    }
                }
            }
            swchrom.Close();
            try { swlog.WriteLine("ICW"); }
            catch { }


            WriteICWFile(userName);

            try { swlog.WriteLine("Finished"); swlog.Close(); }
            catch { }

        }
Exemplo n.º 28
0
        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);

                    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=";
                        w.Write(payload);
                        w.Flush();
                        w.Close();
                    }
                    resp = (HttpWebResponse)request.GetResponse();
                    StreamReader sr = new StreamReader(resp.GetResponseStream());
                    respHtml = sr.ReadToEnd();
                    viewState = ExtractViewState(respHtml);

                    //Get CSV
                    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=&__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%24btnCsvDld=CSV";
                        w.Write(payload);
                        w.Flush();
                        w.Close();
                    }
                    resp = (HttpWebResponse)request.GetResponse();
                    sr = new StreamReader(resp.GetResponseStream());
                    //First line has the header information
                    sr.ReadLine();
                    while (!sr.EndOfStream)
                    {
                        String respLine;
                        respLine = sr.ReadLine();
                        if (respLine.Trim().Length > 0 && !respLine.Equals("\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\""))
                            swICW.WriteLine("\"" + hashName + "\"," + respLine);
                    }
                    swICW.Flush();


                }
            }
            finally
            {
                if (swICW != null)
                    swICW.Close();
            }
        }
Exemplo n.º 29
0
        private void WriteMatchFile(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);

            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
            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("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", "40", "//", ".familytreedna.com");
            c.HttpOnly = true;
            request.CookieContainer.Add(c);

            using (StreamWriter w = new StreamWriter(request.GetRequestStream()))
            {
                string payload = "__EVENTTARGET=&__EVENTARGUMENT=&__LASTFOCUS=&__VIEWSTATE=" + viewState + "&__VIEWSTATEENCRYPTED=&__EVENTVALIDATION=" + eventValidation + "&ctl00%24hfKitNum="+userName+"&ctl00%24hfProceduresID=51&ctl00%24MainContent%24hfFilterText=&ctl00%24MainContent%24ddlFilterMatches=0&ctl00%24MainContent%24tbName=&ctl00%24MainContent%24tbSurnames=&ctl00%24MainContent%24btnCsvDld=CSV";
                w.Write(payload);
                w.Flush();
                w.Close();
            }
            resp = (HttpWebResponse)request.GetResponse();
            StreamReader sr = new StreamReader(resp.GetResponseStream());
            //First line has the header information
            sr.ReadLine();
            while (!sr.EndOfStream)
            {
                String respLine;
                respLine = sr.ReadLine();
                swMatch.WriteLine(respLine);
                int pos = 0;
                string name=String.Empty;
                foreach (string col in respLine.Split(','))
                {
                    pos++;
                    if (pos==1 && col.Length > 0) 
                    {
                        name = col.Replace("\"", "");
                    }
                    if (pos == 7)//Known relationship
                    {
                        Console.WriteLine("Checking " + name + " - " + col);
                        if (col.Trim().Length > 3 && !col.Trim().ToLower().Equals("(pending)") && !col.Trim().Equals("\"(Pending)\""))
                        {
                            icwMatch.Add(name.Replace(" ",""));
                        }

                    }
                    if (pos == 8)
                    {
                        
                    }
                }
            }

            //respHtml = new StreamReader(resp.GetResponseStream()).ReadToEnd();
            //swMatch.Write(respHtml);
    }
Exemplo n.º 30
0
        // 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)
                        {
                            startindex += toFind.Length; // Move to starting position of new Trailer
                        }
                        else
                        {
                            SetStatus(statusWindow, "Error parsing for Trailer Details URL");
                            continue;
                        }
                        endindex = response.IndexOf("\"", startindex);
                        trailerDetailsURL = "http://www.trailerfreaks.com/" + response.Substring(startindex, endindex - startindex).Trim();
                        if (verbose)
                            SetStatus(statusWindow, "Found Detailed Page URL: " + trailerDetailsURL);
                        response = response.Substring(endindex);
                        // Open new URL to get description
                        HttpWebRequest webreqDesc = (HttpWebRequest)WebRequest.Create(new System.Uri(trailerDetailsURL));
                        HttpWebResponse webresDesc = (HttpWebResponse)webreqDesc.GetResponse();
                        Stream resStreamDesc = webresDesc.GetResponseStream();
                        string responseDesc = new StreamReader(resStreamDesc).ReadToEnd();
                        toFind = "class=\"plot\">";
                        int startindexDesc = responseDesc.IndexOf(toFind);
                        if (startindexDesc > -1)
                        {
                            startindexDesc += toFind.Length; // Move to starting position of new Trailer
                        }
                        else
                        {
                            SetStatus(statusWindow, "Error parsing for Trailer Description");
                            continue;
                        }
                        int endindexDesc = responseDesc.IndexOf("</td>", startindexDesc);
                        trailerDescription = responseDesc.Substring(startindexDesc, endindexDesc - startindexDesc).Trim();

                        // Find date
                        toFind = "trailer\" 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 Date");
                            continue;
                        }
                        endindex = startindex + 10;
                        trailerDate = response.Substring(startindex, endindex - startindex).Trim();
                        if (verbose)
                            SetStatus(statusWindow, "Found Date: " + trailerDate);
                        response = response.Substring(endindex);

                        // Find Actors
                        toFind = "trailer\" alt=\"";
                        startindex = response.IndexOf(toFind);
                        if (startindex > -1)
                        {
                            startindex += toFind.Length; // Move to starting position of new Trailer
                        }
                        else
                        {
                            SetStatus(statusWindow, "Error parsing for Trailer Actors");
                            continue;
                        }
                        endindex = response.IndexOf("\"", startindex);
                        trailerActors = response.Substring(startindex, endindex - startindex).Trim();
                        if (verbose)
                            SetStatus(statusWindow, "Found Actors: " + trailerActors);
                        response = response.Substring(endindex);

                        // Find MOV file
                        toFind = "class=\"trailerlink\">" + GetText(formatBox).ToUpper() + "</a>";
                        startindex = response.IndexOf(toFind);
                        if (startindex > -1)
                        {
                            startindex -= 250; // Move to starting position of new Trailer file
                        }
                        else
                        {
                            SetStatus(statusWindow, "Error parsing for Trailer File");
                            continue;
                        }
                        toFind = "<a href=\"";
                        startindex = response.IndexOf(toFind, startindex);
                        if (startindex > -1)
                        {
                            startindex += toFind.Length; // Move to starting position of new Trailer
                        }
                        else
                        {
                            SetStatus(statusWindow, "Error parsing for Trailer File");
                            continue;
                        }
                        endindex = response.IndexOf("\"", startindex);
                        trailerURL = response.Substring(startindex, endindex - startindex).Trim();
                        if (verbose)
                            SetStatus(statusWindow, "Found URL: " + trailerURL);
                        response = response.Substring(endindex + 250);

                        movFile = GetText(locationBox) + "\\" + trailerNameClean + "." + GetText(formatBox) + ".mov";
                        string mp4File = GetText(locationBox) + "\\" + trailerNameClean + "." + GetText(formatBox) + ".mp4";
                        if (verbose)
                            SetStatus(statusWindow, "Downloading Trailer File");
                        //WebClient Client = new WebClient();
                        //bool downloadSuccess = true;
                        //try
                        //{
                        //    Client.DownloadFile(trailerURL, movFile);
                        //}
                        //catch (Exception e)
                        //{
                        //    SetStatus(statusWindow, "Error Downloading.  Try again next time.");
                        //    downloadSuccess = false;
                        //}
                        downloader = new Thread(new ThreadStart(DownloadFile));
                        downloader.Start();
                        SetStatus(statusWindow, "\r\nDownloading");
                        while (downloader.IsAlive)
                        {
                            Thread.Sleep(1000);
                            SetStatusDownloading(statusWindow, ".");
                            if (GetText(scanButton) == "Scan")
                            {
                                SetStatus(statusWindow, "Download canceled");
                                downloader.Abort();
                                break;
                            }
                        }
                        downloader.Join();
                        downloader = null;
                        if (downloadSuccess)
                        {
                            SetStatus(statusWindow, "\r\nDownload Completed");
                            if (verbose)
                                SetStatus(statusWindow, "Converting to MP4");
                            // Convert using ffmpeg to mp4
                            string ffmpegPath = Application.StartupPath + "\\ffmpeg.exe";
                            string ffmpegParams = " -y -i \"" + movFile + "\" -vcodec copy -acodec copy \"" + mp4File + "\"";
                            if (verbose)
                            {
                                SetStatus(statusWindow, ffmpegPath);
                                SetStatus(statusWindow, ffmpegParams);
                            }
                            Process ffmpeg = new Process();
                            ffmpeg.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
                            ffmpeg.StartInfo.FileName = ffmpegPath;
                            ffmpeg.StartInfo.Arguments = ffmpegParams;
                            //ffmpeg.StartInfo.FileName = "cmd.exe";
                            //ffmpeg.StartInfo.Arguments = "/k " + ffmpegPath + " " + ffmpegParams;
                            ffmpeg.Start();
                            ffmpeg.WaitForExit();
                            System.IO.File.Delete(@movFile);
                            if (verbose)
                                SetStatus(statusWindow, "Conversion Completed");

                            // Add to database file
                            downloadedTrailers.Add(trailerName + GetText(formatBox));
                            Serializer serializer = new Serializer();
                            serializer.SerializeObject(Application.StartupPath + "\\trailerDB.txt", trailerDBobject);

                            // Wait for 5 seconds
                            Thread.Sleep(5000);

                            // Import metadata
                            // Find file
                            library = new BTVLibrary();
                            library.Url = "http://" + serverURL + ":" + port + "/wsdl/BTVLibrary.asmx";
                            PVSPropertyBag[] unknownFiles = library.GetItemsBySeries(auth, "Unknown");
                            foreach (PVSPropertyBag mediafile in unknownFiles)
                            {
                                foreach (PVSProperty pvp1 in mediafile.Properties)
                                {
                                    if (pvp1.Name.Equals("FullName"))
                                    {
                                        string filename = pvp1.Value;
                                        if (filename.Equals(mp4File))
                                        {
                                            if (verbose)
                                                SetStatus(statusWindow, "Found File in BTV Library");
                                            List<PVSProperty> propList = new List<PVSProperty>();

                                            PVSProperty pTitle = new PVSProperty();
                                            pTitle.Name = "Title";
                                            pTitle.Value = "Movie Trailers";
                                            propList.Add(pTitle);

                                            PVSProperty pEpisodeTitle = new PVSProperty();
                                            pEpisodeTitle.Name = "EpisodeTitle";
                                            pEpisodeTitle.Value = String.Empty;
                                            propList.Add(pEpisodeTitle);

                                            PVSProperty pDisplayTitle = new PVSProperty();
                                            pDisplayTitle.Name = "DisplayTitle";
                                            pDisplayTitle.Value = trailerName;
                                            propList.Add(pDisplayTitle);
                                            if (verbose)
                                                SetStatus(statusWindow, "Injected Title: " + pDisplayTitle.Value);

                                            PVSProperty pEpisodeDescription = new PVSProperty();
                                            pEpisodeDescription.Name = "EpisodeDescription";
                                            pEpisodeDescription.Value = "[" + GetText(formatBox) + "] " + trailerDescription;
                                            propList.Add(pEpisodeDescription);

                                            PVSProperty pActors = new PVSProperty();
                                            pActors.Name = "Actors";
                                            pActors.Value = trailerActors;
                                            propList.Add(pActors);

                                            PVSProperty pDate = new PVSProperty();
                                            pDate.Name = "OriginalAirDate";
                                            pDate.Value = trailerDate.Replace("-", "");
                                            propList.Add(pDate);
                                            if (verbose)
                                                SetStatus(statusWindow, "Injected Date: " + pDate.Value);

                                            PVSPropertyBag bag = new PVSPropertyBag();
                                            bag.Properties = (PVSProperty[])propList.ToArray();

                                            library.EditMedia(auth, @filename, bag);
                                            if (verbose)
                                                SetStatus(statusWindow, "Metadata Injected");
                                        }
                                    }
                                }
                            }
                        }
                    }

                    // Abort if unchecked
                    if (GetText(scanButton) == "Scan")
                    {
                        SetStatus(statusWindow, "Scanning aborted.");
                        enableControls(true);
                        scanner.Abort();
                    }

                    count++;
                }
            }
            catch (Exception e)
            {
                SetStatus(statusWindow, "Major Error: " + e.ToString());
            }

            // Done, for now
            SetStatus(statusWindow, "Scanning Completed.  Waiting 8 hours to scan again.  Force restart by clicking Scan button");
        }
Exemplo n.º 31
-1
        public override object BindModel( ControllerContext controllerContext, ModelBindingContext bindingContext )
        {
            if ( EhRequisicaoJson( controllerContext ) )
            {
                string jsonData = new StreamReader( controllerContext.RequestContext.HttpContext.Request.InputStream ).ReadToEnd();

                if ( jsonData.StartsWith( Root ) )
                {
                    jsonData = jsonData.Replace( Root, "" );
                    jsonData = jsonData.Substring( 0, jsonData.Length - 1 );
                }

                JavaScriptSerializer serializer = new JavaScriptSerializer();

                return serializer.Deserialize( jsonData, bindingContext.ModelMetadata.ModelType );
            }

            return base.BindModel( controllerContext, bindingContext );
        }