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

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

            errorResponse = null;

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

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

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

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

                    if (errorResponse != null)
                        return null;
                    return (HttpWebResponse)newHttpWebResponse;
                }
            }
            catch (ObjectDisposedException ex)
            {
                DebugHelper.WriteLogEntry(ex, "AddPhotosComments ObjectDisposedException");
                return null;
            }
            finally
            {
                request.Abort();
                //response.Close();
            }
        }
        /*
         * 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;
            }
        }
Exemple #7
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"));
 }
Exemple #8
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 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);
        }
        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);
        }
Exemple #11
0
 public static string GetRealIP()
 {
     string str3;
     string requestUriString = "http://checkrealip.com";
     try
     {
         str3 = new StreamReader(WebRequest.Create(requestUriString).GetResponse().GetResponseStream(), true).ReadToEnd();
     }
     catch (Exception exception1)
     {
         ProjectData.SetProjectError(exception1);
         Exception exception = exception1;
         ProjectData.ClearProjectError();
         return "";
     }
     str3 = str3.ToLower();
     int index = str3.IndexOf("address:");
     if (index == -1)
     {
         return "";
     }
     str3 = str3.Substring(index + 8);
     index = str3.IndexOf("\r\n");
     if (index == -1)
     {
         return "";
     }
     return str3.Substring(0, index);
 }
Exemple #12
0
 private static string DecodeData(Stream responseStream, HttpWebResponse response)
 {
     string name = null;
     string text2 = response.Headers["content-type"];
     if (text2 != null)
     {
         int index = text2.IndexOf("charset=");
         if (index != -1)
         {
             name = text2.Substring(index + 8);
         }
     }
     MemoryStream stream = new MemoryStream();
     byte[] buffer = new byte[0x400];
     for (int i = responseStream.Read(buffer, 0, buffer.Length); i > 0; i = responseStream.Read(buffer, 0, buffer.Length))
     {
         stream.Write(buffer, 0, i);
     }
     responseStream.Close();
     if (name == null)
     {
         MemoryStream stream3 = stream;
         stream3.Seek((long)0, SeekOrigin.Begin);
         string text3 = new StreamReader(stream3, Encoding.ASCII).ReadToEnd();
         if (text3 != null)
         {
             int startIndex = text3.IndexOf("charset=");
             int num4 = -1;
             if (startIndex != -1)
             {
                 num4 = text3.IndexOf("\"", startIndex);
                 if (num4 != -1)
                 {
                     int num5 = startIndex + 8;
                     name = text3.Substring(num5, (num4 - num5) + 1).TrimEnd(new char[] { '>', '"' });
                 }
             }
         }
     }
     Encoding aSCII = null;
     if (name == null)
     {
         aSCII = Encoding.GetEncoding("gb2312");
     }
     else
     {
         try
         {
             if (name == "GBK")
             {
                 name = "GB2312";
             }
             aSCII = Encoding.GetEncoding(name);
         }
         catch
         {
             aSCII = Encoding.GetEncoding("gb2312");
         }
     }
     stream.Seek((long)0, SeekOrigin.Begin);
     StreamReader reader2 = new StreamReader(stream, aSCII);
     return reader2.ReadToEnd();
 }
        public void GenerateClasses(string nameSpace)
        {
            var numSamples = NumRowsToSample;

            _generatedClasses =
                GetInputFiles()
                    .Select(f =>
                    {
                        // TODO: Be a better error handler
                        try
                        {
                            var fs = new FileStream(f, FileMode.Open);
                            var sr = new StreamReader(fs);
                            var jtr = new JsonTextReader(sr);

                            var examples =
                                Enumerable
                                    .Range(0, numSamples)
                                    .Select(_ =>
                                    {
                                        while (jtr.Read())
                                            if (jtr.TokenType == JsonToken.StartObject)
                                                return JObject.Load(jtr).ToString();
                                        return null;
                                    })
                                    .Where(json => json != null);

                            var examplesJson = String.Format("[{0}]", String.Join(",\r\n", examples));

                            jtr.Close();
                            sr.Close();
                            fs.Close();

                            var className = Path.GetFileNameWithoutExtension(f).SanitiseClassName();
                            var finalNamespace = nameSpace + "." + className + "Input";
                            var outputStream = new MemoryStream();
                            var outputWriter = new StreamWriter(outputStream);

                            var jsg = new JsonClassGenerator
                            {
                                Example = examplesJson,
                                Namespace = finalNamespace,
                                MainClass = className,
                                OutputStream = outputWriter,
                                NoHelperClass = true,
                                UseProperties = true,
                                GeneratePartialClasses = true
                            };

                            jsg.GenerateClasses();

                            outputWriter.Flush();
                            outputStream.Seek(0, SeekOrigin.Begin);

                            var classDef = new StreamReader(outputStream)
                                .ReadToEnd()
                                .Replace("IList<", "List<");

                            classDef =
                                classDef.Substring(classDef.IndexOf(String.Format("namespace {0}", nameSpace),
                                    StringComparison.Ordinal));

                            NamespacesToAdd.Add(finalNamespace);

                            return new JsonFileGeneratedClass(this)
                            {
                                Namespace = finalNamespace,
                                ClassName = className,
                                DataFilePath = f,
                                ClassDefinition = classDef,
                                Success = true
                            };
                        }
                        catch (Exception e)
                        {
                            return new JsonFileGeneratedClass(this)
                            {
                                DataFilePath = f,
                                Success = false,
                                Error = e
                            };
                        }
                    })
                    .ToList();
        }
Exemple #14
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;
            }
        }
        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();
            }
        }
Exemple #16
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();


            }
        }
Exemple #17
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();
            }
        }
Exemple #18
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");
        }
Exemple #19
0
        public override bool Register(string username, string password)
        {
            this.username = username;
            HttpWebRequest getHeaders = (HttpWebRequest)HttpWebRequest.Create("https://rollin.io/ref/8c4");
            if (Prox != null)
                getHeaders.Proxy = Prox;
            var cookies = new CookieContainer();
            getHeaders.CookieContainer = cookies;

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

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

            HttpWebRequest betrequest2 = (HttpWebRequest)HttpWebRequest.Create("https://rollin.io/api/customer/info?username="******"X-CSRF-Token", Token);
            HttpWebResponse EmitResponse2 = (HttpWebResponse)betrequest2.GetResponse();
            string sEmitResponse2 = new StreamReader(EmitResponse2.GetResponseStream()).ReadToEnd();
            RollinLoginStats tmpStats = json.JsonDeserialize<RollinLoginStats>(sEmitResponse2);

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

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

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

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

                finishedlogin(true);
                return true;
            }
            finishedlogin(false);
            return false;
        }
        // Get a single comic
        private ComicInfo UpdateSingleComic( ComicInfo ci )
        {
            for (int i = 0; i < daysToKeep; i++)
            {
                // Create a webclient
                System.Net.WebClient webClient = new System.Net.WebClient();

                // Create the image filename from the format in the XML file
                char[] delims = {'$'};
                // Parse the String format and form the path with the year
                String[] ImagePathTokens = ci.ImagePath.Split(delims,100);
                String ImagePath = "";
                foreach( String s in ImagePathTokens )
                {
                    int dt = DateTime.Now.Year;
                    // Year
                    if ( s.Equals("yyyy") )
                        ImagePath += dt.ToString();
                    else
                        ImagePath += s;
                }

                // Parse the String format and form the filename with the date
                // Dilbert Hack: Create a filename to store that is consistent with the rest
                String[] FilenameTokens = ci.ImageFilename.Split(delims,100);
                String URIImageFilename = "";
                String SavedImageFilename = "";
                foreach( String s in FilenameTokens )
                {
                    DateTime dt = DateTime.Now.AddDays(-i);
                        // Year
                    if ( s.Equals("YY") )
                    {
                        SavedImageFilename += dt.ToString("yy",DateTimeFormatInfo.InvariantInfo);
                    }
                        // Month
                    else if ( s.Equals("MM") )
                    {
                        SavedImageFilename += dt.ToString("MM",DateTimeFormatInfo.InvariantInfo);
                    }
                        // Day
                    else if ( s.Equals("DD") )
                    {
                        SavedImageFilename += dt.ToString("dd",DateTimeFormatInfo.InvariantInfo);
                    }
                    else
                    {
                        SavedImageFilename += s;
                    }
                }

                // Comics.com support
                if ( ci.Website == "Comics.com" )
                {
                    try
                    {
                        DateTime dt = DateTime.Now.AddDays(-i);
                        HttpWebRequest webreq;
                        HttpWebResponse	webres;
                        string trimmedPath =  ci.ImagePath.Remove(ci.ImagePath.IndexOf("images/"),7);
                        System.Uri uri = new System.Uri(trimmedPath+ci.FolderName+"-"+DateTime.Now.Year.ToString() + dt.ToString("MM",DateTimeFormatInfo.InvariantInfo) + dt.ToString("dd",DateTimeFormatInfo.InvariantInfo) + ".html");
                        webreq = (HttpWebRequest)WebRequest.Create(uri);
                        webres = (HttpWebResponse)webreq.GetResponse();
                        Stream resStream = webres.GetResponseStream();
                        string response = new StreamReader( resStream ).ReadToEnd();
                        response = response.Substring(response.IndexOf("archive/images/"+ci.FolderName));
                        string[] responseArray = response.Split('/');
                        char[] dms = new  Char[] {'"','&'};
                        URIImageFilename = responseArray[2].Split(dms)[0];
                        ci.ImageSuffix = URIImageFilename.Split('.')[1];
                    }
                    catch (Exception e)
                    {
                        SnapStream.Logging.WriteLog( e.StackTrace );
                    }
                }
                // End Comics.com support

                // Add the extension name to the save file name
                SavedImageFilename += "." + ci.ImageSuffix;

                // ucomics filename needs an extension
                if (ci.Website != "Comics.com")
                    URIImageFilename = SavedImageFilename;

                // Add the website path before the image filename
                String URIImagePath = ImagePath + URIImageFilename;

                // Download the image
                try
                {
                    // Prepare the local storage folder, if it needs to be created
                    string alphaNumericName = ToAlphaNumericString( ci.FolderName );
                    string comicDirectory = _homeDirectory + "\\" + alphaNumericName;
                    if( System.IO.Directory.Exists(comicDirectory) == false )
                    {
                        System.IO.Directory.CreateDirectory( comicDirectory );
                    }

                    // Now create the local image path to save the file
                    string imagePath = _homeDirectory + "\\" + alphaNumericName + "\\" + SavedImageFilename;

                    // If the file exists, don't download it again
                    if( System.IO.File.Exists(imagePath) == false )
                    {
                        string tempFilename = System.IO.Path.GetTempFileName();
                        webClient.DownloadFile( URIImagePath, tempFilename );
                        System.IO.File.Copy( tempFilename, imagePath, true );
                        System.IO.File.Delete( tempFilename );
                    }
                }
                catch (Exception e)
                {
                    SnapStream.Logging.WriteLog( e.StackTrace );
                }
            }
            // Now add
            ComicInfo ciAdd = new ComicInfo();
            return ciAdd = ci;
        }
        public void MetaTagOutsideBlock()
        {


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

            string filler = "<script type=\"text/javascript\" src=\"dummy\"></script>";
            var html = htmlStart;
            for (int i = 1; i < 5000 / filler.Length; i++)
            {
                html += filler;
            }

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


            var dom = CQ.Create(html);
            var output = dom.Render(OutputFormatters.HtmlEncodingMinimum);

            // FINALLY  -- grab the character from CsQuery's output, and ensure that this all worked out.

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

            //  write the string to an encoded stream  to get the correct encoding manually
            MemoryStream encoded = new MemoryStream();
            var writer = new StreamWriter(encoded, encoder);
            writer.Write(html);
            writer.Flush();

            encoded.Position = 0;
            string htmlHebrew = new StreamReader(encoded, encoder).ReadToEnd();
            var sourceHebrewChar = htmlHebrew.Substring(htmlHebrew.IndexOf("test>") + 5, 1);


            // THIS IS THE DIFFERENCE BETWEEN THIS AND THE OTHER TEST
            // the encoding should be ignored
            Assert.AreNotEqual(sourceHebrewChar, outputHebrewChar);

            // Try this again WITHOUT charset encoding.

            var clone = CQ.Create(htmlNoRecode);
            string newHtml = clone.Render(OutputFormatters.HtmlEncodingMinimum);
            var dom2 = CQ.Create(newHtml);

            outputHebrewChar = dom2["#test"].Text();
            Assert.AreNotEqual(sourceHebrewChar, outputHebrewChar);

            var reader = new StreamReader(encoded);
            string interim = reader.ReadToEnd();

            encoded = new MemoryStream();
            writer = new StreamWriter(encoded, Encoding.UTF8);
            writer.Write(interim);
            writer.Flush();


            // read it back one more time

            encoded.Position = 0;
            reader = new StreamReader(encoded);
            string final = reader.ReadToEnd();


            //            var encoded = encoder.GetBytes(html);



        }
Exemple #22
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);
    }
Exemple #23
0
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="obj"></param>
        private void login(object obj)
        {
            try
            {
                running = true;
                sleep();
                if (stop == true)
                {
                    return;
                }
                if (obj != null)
                {
                    Thread.CurrentThread.Name = obj.ToString();
                }
                if (logged == true)
                {
                    if (MessageBox.Show("您已经登录,您需要再次进入12306网站吗?需要您已经退出,就需要重新登录!", "德广火车票助手 温馨提示", MessageBoxButtons.YesNo, MessageBoxIcon.Information, MessageBoxDefaultButton.Button2) == DialogResult.Yes)
                    {
                        this.Invoke(LoggedDelegate);
                        //openie();
                    }
                    running = false;
                    return;
                }

                Trace.WriteLine("login()");
                count++;
                System.Net.ServicePointManager.CertificatePolicy = new MyPolicy();

                // this is what we are sending
                string post_data = "loginUser.user_name=tony12306cn&nameErrorFocus=&user.password=tony1234&passwordErrorFocus=&randCode=" + txtVerificationCode.Text + "&randErrorFocus=focus";

                // this is where we will send it
                string uri = "https://dynamic.12306.cn/otsweb/loginAction.do?method=login";

                // create a request
                //HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
                //request.CookieContainer = cookieContainer;
                //request.KeepAlive = false;
                //request.ProtocolVersion = HttpVersion.Version10;
                //request.Method = "POST";

                //// turn our request string into a byte stream
                //byte[] postBytes = Encoding.ASCII.GetBytes(post_data);

                //// this is important - make sure you specify type this way
                //request.ContentType = "application/x-www-form-urlencoded";
                //request.ContentLength = postBytes.Length;
                //Stream requestStream = request.GetRequestStream();

                //// now send it
                //requestStream.Write(postBytes, 0, postBytes.Length);
                //requestStream.Close();

                Dictionary<string, string> param = new Dictionary<string, string>();
                param.Add("loginUser.user_name", txtUserName.Text);
                param.Add("nameErrorFocus", string.Empty);
                param.Add("user.password", txtPassword.Text);
                param.Add("passwordErrorFocus", string.Empty);
                param.Add("randCode", txtVerificationCode.Text);
                param.Add("randErrorFocus", "focus");

                HttpWebResponse response = null;
                try
                {
                    response = HttpWebResponseUtility.CreatePostHttpResponse(uri, param,null, DefaultUserAgent, Encoding.ASCII, cookieCollection, uri);
                }
                catch (Exception ex)
                {
                    this.Invoke(this.showMsgDelegate, ex.Message);
                    //showInfo(ex.Message);
                }

                if (response != null)
                {
                    // grab te response and print it out to the console along with the status code
                    //HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                    Stream receiveStream = response.GetResponseStream();
                    if (response.ContentEncoding.ToLower().Contains("gzip"))
                    {
                        receiveStream = new GZipStream(receiveStream, CompressionMode.Decompress);
                    }
                    html = new StreamReader(receiveStream).ReadToEnd();
                    if (html.IndexOf("当前访问用户过多") > 0)
                    {
                        this.Invoke(this.showMsgDelegate, "当前访问用户过多");
                        login(null);
                    }
                    else if (html.IndexOf("请输入正确的验证码") > 0)
                    {
                        messageBoxShowInfo("请输入正确的验证码!");
                        this.Invoke(focusDelegate,new object[]{txtVerificationCode});
                        this.Invoke(setControlTextDelegate,new object[]{txtVerificationCode,string.Empty,true});
                        getVerificationCode(this);
                    }
                    else if (html.IndexOf("登录名不存在") > 0)
                    {
                        messageBoxShowInfo("登录名不存在!!");
                        this.Invoke(focusDelegate, new object[] { txtUserName });
                    }
                    else if (html.IndexOf("密码输入错误") > 0)
                    {
                        messageBoxShowInfo("密码输入错误,如果多次输入错误可能会被锁定帐户!");
                        this.Invoke(focusDelegate, new object[] { txtPassword });
                        this.Invoke(setControlTextDelegate, new object[] { txtPassword, string.Empty, true });
                    }
                    else if (html.IndexOf("已经被锁定") > 0)
                    {
                        messageBoxShowInfo("您的用户已经被锁定,请稍候再试!");
                    }
                    else if (html.IndexOf("系统维护中") > 0)
                    {
                        messageBoxShowInfo("系统维护中!");
                    }
                    else if (html.IndexOf("我的12306") > 0)
                    {
                        this.Invoke(activateDelegate);
                        endTime = DateTime.Now;
                        logged = true;
                        timeSpan = endTime.Subtract(beginTime);
                        timeSpanStr = getTimeSpanString(timeSpan);

                        MessageBox.Show("经过 " + timeSpanStr + ", " + count + " 次的尝试后,您已经登录成功!" + Environment.NewLine
                            + "点击确定打开12306网站,请忽略登录界面,直接点击\"车票预订\"就可以啦!" + Environment.NewLine
                            + Environment.NewLine
                            + "深圳市德广信息技术有限公司 祝您:" + Environment.NewLine
                            + "回家一路顺风!全家身体健康!幸福快乐!事事如意!", "德广火车票助手 恭喜您", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);

                        this.Invoke(shareToWeiboDelegate, new object[] { "我用#德广火车票助手#经过" + timeSpanStr +"尝试登录"+ count + "次后,成功登录上了12306.cn!你用了多长时间才登录成功的呢?" });

                        this.Invoke(LoggedDelegate);
                        //openie();
                        this.Invoke(this.showMsgDelegate, "登录成功!");
                    }
                    else
                    {
                        Trace.WriteLine(html);
                        login(null);
                    }

                    Trace.WriteLine(response.StatusCode);
                }
                else
                {
                    login(null);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "异常", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                this.Invoke(setControlTextDelegate, new object[] { btnLogin, "登录", true });
                running = false;
            }
        }
Exemple #24
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 { }

        }
Exemple #25
0
        /// <summary>
        /// gets the inital cookies for the connections.
        /// cookies includeL __cfduid, connect.sid, hash. These are required for mainting the same connection
        /// </summary>
        private bool getInitalHeaders()
        {
            string sResponse = "";
            request = (HttpWebRequest)HttpWebRequest.Create(host);
            if (Proxy != null)
                request.Proxy = Proxy;
            var cookies = new CookieContainer();
            request.CookieContainer = cookies;
            request.UserAgent = "JDCAPI - " + UserAgent;
            if (!string.IsNullOrEmpty(privatehash))
            {
                request.CookieContainer.Add(new Cookie("hash", privatehash, "/", (host.Contains("just")) ? ".just-dice.com" : ".doge-dice.com"));
            }
            //request.CookieContainer.Add(new Cookie("cf_clearance", "bc22bf9b9733912f976dc28c78796fc91e19b7fe-1393330223-86400", "/", ".just-dice.com"));
            HttpWebResponse Response = null;
            try
            {

                Response = (HttpWebResponse)request.GetResponse();

            }
            catch (WebException e)
            {
                if (logging)
                    writelog(e.Message);

                if (e.Response != null)
                {
                    Response = (HttpWebResponse)e.Response;
                    string s1 = new StreamReader(Response.GetResponseStream()).ReadToEnd();
                    string tmp = s1.Substring(s1.IndexOf("var t,r,a,f,"));
                    string varfirst = tmp.Substring("var t,r,a,f,".Length + 1, tmp.IndexOf("=") - "var t,r,a,f,".Length - 1);
                    string varsec = tmp.Substring(tmp.IndexOf("{\"") + 2, tmp.IndexOf("\"", tmp.IndexOf("{\"") + 3) - tmp.IndexOf("{\"") - 2);
                    string var = varfirst + "." + varsec;
                    string varline = "var " + tmp.Substring("var t,r,a,f,".Length + 1, tmp.IndexOf(";") - "var t,r,a,f,".Length);
                    string initbval = tmp.Substring(tmp.IndexOf(":+") + 1, tmp.IndexOf("))") + 3 - tmp.IndexOf(":+") - 1);
                    string vallist = tmp.Substring(tmp.IndexOf(var), tmp.IndexOf("a.value") - tmp.IndexOf(var));

                    string script = varline + vallist;
                    object Result = 0;
                    try
                    {
                        Result = ScriptEngine.Eval("jscript", script);
                    }
                    catch (Exception ex)
                    {

                    }
                    int aval = int.Parse(Result.ToString(), System.Globalization.CultureInfo.InvariantCulture);

                    string jschl_vc = s1.Substring(s1.IndexOf(" name=\"jschl_vc\" value=\""));
                    jschl_vc = jschl_vc.Substring(("name=\"jschl_vc\" value=\"").Length + 1);
                    int len = jschl_vc.IndexOf("\"/>\n");
                    jschl_vc = jschl_vc.Substring(0, len);
                    try
                    {
                        //string content = new WebClient().DownloadString("cdn-cgi/l/chk_jschl?jschl_vc=1bb30f6e73b41c8dd914ccbf64576147&jschl_answer=84");
                        CookieContainer cookies2 = request.CookieContainer;
                        string req = string.Format(host + "/cdn-cgi/l/chk_jschl?jschl_vc={0}&jschl_answer={1}", jschl_vc, aval + 13);
                        request = (HttpWebRequest)HttpWebRequest.Create(req);
                        if (Proxy != null)
                            request.Proxy = Proxy;
                        request.UserAgent = "JDCAPI - " + UserAgent;
                        request.CookieContainer = cookies2;
                        Response = (HttpWebResponse)request.GetResponse();

                    }
                    catch
                    {
                        return false;
                    }
                }
                else
                {
                    Connected = false;
                    return false;
                }
            }

            string s = new StreamReader(Response.GetResponseStream()).ReadToEnd();
            if (s.StartsWith("<!DOCTYPE html><html lang=\"en\"><head><script src=\"/javascripts/jquery-1.10.0.min.js\">"))
            {
                if (OnLoginError != null && sUsername == "" && sPassword == "")
                {
                    OnLoginError("This account requires a username and password");
                    Connected = false;
                    return false;
                }
            }
            foreach (Cookie cookievalue in Response.Cookies)
            {
                request.CookieContainer.Add(cookievalue);
                switch (cookievalue.Name)
                {
                    case "connect.sid": conid = cookievalue.Value; break;
                    case "__cfduid": id = cookievalue.Value; break;
                    case "hash":
                    case "hash ":
                    case " hash":
                    case " hash ": hash = cookievalue.Value; break;
                }

            }

            Response = (HttpWebResponse)request.GetResponse();
            s = new StreamReader(Response.GetResponseStream()).ReadToEnd();

            foreach (Cookie cookievalue in Response.Cookies)
            {
                request.CookieContainer.Add(cookievalue);
                switch (cookievalue.Name)
                {
                    case "connect.sid": conid = cookievalue.Value; break;
                    case "__cfduid": id = cookievalue.Value; break;
                    case "hash":
                    case "hash ":
                    case " hash":
                    case " hash ": hash = cookievalue.Value; break;
                }

            }

            bool founhash = false;
            for (int i = 0; i < request.CookieContainer.GetCookies(request.RequestUri).Count; i++)
            {
                if (request.CookieContainer.GetCookies(request.RequestUri)[i].Name == "hash")
                {
                    founhash = true;
                    break;
                }
            }

            for (int i = 0; i < Response.Headers.Count && !founhash; i++)
            {
                string hash = Response.Headers[i];
                if (hash.Contains("hash"))
                {
                    string[] tmpCookies = hash.Split(';');
                    foreach (string CurCookie in tmpCookies)
                    {
                        if (CurCookie.Contains("hash"))
                        {
                            string HashValue = CurCookie.Split('=')[1];
                            request.CookieContainer.Add(new Cookie("hash", HashValue,"/",".just-dice.com"));
                            privatehash = HashValue;
                            founhash = true;
                            break;
                        }
                    }
                }
            }
            return true;
        }
Exemple #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;
        }
Exemple #27
0
        static void Main(string[] args)
        {
            String contents = new StreamReader("GearConsole.cs").ReadToEnd();

            String template = String.Empty;
            String outputFilename = String.Empty;
            switch (Type)
            {
                case OutputType.GSFile:
                    template = new StreamReader("GS.Template.cs").ReadToEnd();
                    outputFilename = "GS.cs";
                    break;
                case OutputType.DummyGearConsole:
                    template = new StreamReader("GearConsoleDummy.Template.cs").ReadToEnd();
                    outputFilename = "GearConsole (Dummy).cs";
                    break;
            }

            int startIndex = contents.IndexOf("// WRAPPER FUNCTIONS BEGIN") +"// WRAPPER FUNCTIONS BEGIN".Length;
            int endIndex = contents.IndexOf("// WRAPPER FUNCTIONS END");
            contents = contents.Substring(startIndex , endIndex - startIndex);

            String result = String.Empty;

            MatchCollection matches = Regex.Matches(contents, "((?: */// .*\\n)+) *public (.*)");
            foreach (Match match in matches)
            {
                String comment = match.Groups[1].Captures[0].Value;
                String signature = match.Groups[2].Captures[0].Value.TrimEnd('\r', '\n');
                String paramStr = Regex.Matches(signature, ".*\\((.*)\\)")[0].Groups[1].ToString();
                String[] parameters = paramStr.Split(',');
                String indentation = new String(' ', 4);
                String methodName = signature.TrimStart(' ').Split('(')[0].Split(' ').Last();
                String passOfParameters = Regex.Replace(paramStr, "((?:ref )?)(?:[a-zA-Z0-9_]+ )([a-zA-Z0-9_]+,?)", "$1$2");
                String methodCall = "Console." + methodName + "(" + passOfParameters + ")";

                switch (Type)
                {
                    case OutputType.GSFile:
                        result += comment;
                        result += Indentation(2) + "[Conditional(\"USE_GEARSET\")]\n";
                        result += Indentation(2) + "public static " + signature + "\n";
                        result += Indentation(2) + "{\n";
                        result += Indentation(3) + "if (SameThread())\n";
                        result += Indentation(4) + methodCall + ";\n";
                        result += Indentation(3) + "else\n";
                        if (paramStr.Contains("ref "))
                            result += Indentation(4) + "// TODO: CACHE THE REF PARAMETERS\n";
                        if (paramStr.Contains("params "))
                            result += Indentation(4) + "// TODO: FIX THE \"PARAMS\" PARAMETER(S)\n";
                        result += Indentation(4) + "EnqueueAction(new Action(() => " + methodCall + "));\n";
                        result += Indentation(2) + "}\n\n";
                        break;
                    case OutputType.DummyGearConsole:
                        result += Indentation(2) + signature + " { }\n";
                        break;
                }

            }

            result = template.Replace("// FUNCTION WRAPPERS PLACEHOLDER", result);

            // Write the output.
            var outputFile = new StreamWriter(outputFilename);
            outputFile.Write(result);
            outputFile.Close();
            Console.WriteLine("Output written to " + outputFilename);
            Console.WriteLine("Remember to check for stuff marked with TODO");
            Console.ReadLine();
        }
Exemple #28
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
            {
                
            }
        }
        public void MetaTag()
        {
            

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

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


            // read it in again, but without encoding

            //encoded.Position = 0;

            var dom = CQ.Create(html);
            var output = dom.Render(OutputFormatters.HtmlEncodingMinimum);

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

            //  write the string to an encoded stream  to get the correct encoding manually
            MemoryStream encoded = new MemoryStream();
            var writer = new StreamWriter(encoded, encoder);
            writer.Write(html);
            writer.Flush();

            encoded.Position = 0;
            string htmlHebrew = new StreamReader(encoded, encoder).ReadToEnd();
            var sourceHebrewChar = htmlHebrew.Substring(htmlHebrew.IndexOf("test>") + 5, 1);

            Assert.AreEqual(sourceHebrewChar, outputHebrewChar);

            // Try this again WITHOUT charset encoding.

            var clone = CQ.Create(htmlNoRecode);
            string newHtml = clone.Render(OutputFormatters.HtmlEncodingMinimum);
            var dom2 = CQ.Create(newHtml);

            outputHebrewChar = dom2["#test"].Text();
            Assert.AreNotEqual(sourceHebrewChar, outputHebrewChar);

            var reader = new StreamReader(encoded);
            string interim = reader.ReadToEnd();

            encoded = new MemoryStream();
            writer = new StreamWriter(encoded, Encoding.UTF8);
            writer.Write(interim);
            writer.Flush();


            // read it back one more time

            encoded.Position = 0;
            reader = new StreamReader(encoded);
            string final = reader.ReadToEnd();


//            var encoded = encoder.GetBytes(html);



        }
        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());

            //*/
        }
Exemple #31
0
            public void ProcessRequest()
            {
                try {
                    string input = new StreamReader(context.Request.InputStream).ReadToEnd();
                    string msg = context.Request.HttpMethod + " " + context.Request.Url;
                    Console.Write(msg);
                    context.Response.Headers.Add("Access-Control-Allow-Origin", "*");
                    context.Response.Headers.Add("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");

                    StringBuilder sb = new StringBuilder();

                    var delimiter = input.IndexOf("?");
                    var data = "";
                    if (delimiter == -1) {
                        delimiter = input.Length;
                    } else {
                        data = input.Substring(delimiter + 1);
                    }
                    var name = input.Substring(0, delimiter);
                    Console.WriteLine(" " + name);

                    if (name.ToLower() == "login") {
                        var parameters = HttpUtility.ParseQueryString(data);
                        var login = new Login(parameters["login"], parameters["password"]); //json.Deserialize<Login>(data);
                        var id = DB.checkLogin(login.login, login.password);
                        if (id == 1) {
                            /*var loginCookie = new Cookie();
                            loginCookie.Name = "Session";
                            var cookie = "";
                            do {
                                cookie = System.Web.Security.Membership.GeneratePassword(22, 11);
                            } while (DB.checkCookie(cookie) != -1);
                            DB.addCookie(cookie, id);
                            loginCookie.Value = cookie;
                            loginCookie.Expires = DateTime.Now.AddDays(1);

                            context.Response.Cookies.Add(loginCookie);*/
                            sb.Append("success");
                        } else {
                            sb.Append("fail");
                        }
                    /*} /*else if (name.ToLower() == "logout") {
                        var cook = getCookie(context);
                        if (cook != null) {
                            var expCookie = new Cookie();
                            expCookie.Name = "Session";
                            expCookie.Expires = DateTime.Now.AddDays(-1d);
                            context.Response.Cookies.Add(expCookie);
                            if (DB.checkCookie(cook.Value) != -1) {
                                DB.deleteCookie(cook.Value);
                            }
                        }*/
                    } else if (name.ToLower() == "coordinates") {
                        /*Console.Write("LOLOL!");
                        var cook = getCookie(context);
                        if (cook != null) {
                            //var id = DB.checkCookie(cook.Value);
                            //if (id != -1) {*/
                                var id = 1;
                                var coords = DB.getCoordinates(id);
                                var json = new System.Web.Script.Serialization.JavaScriptSerializer();
                                  foreach(var coordinate in coords){
                                    sb.Append(String.Format(CultureInfo.InvariantCulture, "{0};{1};{2};", coordinate.x, coordinate.y, coordinate.comment));
                                }
                            //}
                        }

                    byte[] b = Encoding.UTF8.GetBytes(sb.ToString());
                    context.Response.ContentLength64 = b.Length;
                    var stream = context.Response.OutputStream;
                    stream.Write(b, 0, b.Length);
                    stream.Flush();
                    stream.Close();
                } catch (Exception e) {
                    Console.WriteLine(e);
                }
            }