Exemple #1
0
        public override List<StopTime> GetStopTimes(string stopID)
        {
            System.Net.WebClient client = new System.Net.WebClient();

            DataSet ds = new DataSet();
            ds.ReadXml(client.OpenRead("http://www.ctabustracker.com/bustime/api/v1/getpredictions?key=" + APIKey + "&stpid=" + stopID));

            List<StopTime> result = new List<StopTime>();

            if (ds.Tables["prd"] == null)
            {
                return result;
            }

            foreach (DataRow r in ds.Tables["prd"].Rows)
            {
                StopTime t = new StopTime();
                t.RouteShortName = r["rt"].ToString();
                t.RouteLongName = r["rt"].ToString();
                t.ArrivalTime = DateTime.ParseExact(r["prdtm"].ToString(), "yyyyMMdd HH:mm", new System.Globalization.CultureInfo("en-US")).ToString("hh:mm tt");
                t.DepartureTime = t.ArrivalTime;
                t.Type = "realtime";

                if ((from x in result where x.RouteShortName == t.RouteShortName select x).Count() < 2)
                    result.Add(t);
            }

            return result;
        }
        public Stream GetInstallFileStream(string packageFileDownloadUrl)
        {
            Log.LogVerbose("PackageServerFacade", string.Format("Downloading file: {0}", packageFileDownloadUrl));

            var client = new System.Net.WebClient();
            return client.OpenRead(packageFileDownloadUrl);
        }
        /// <summary>
        /// get an Assembly according to wsdl path.
        /// </summary>
        /// <param name="wsdl">wsdl path</param>
        /// <param name="nameSpace">namespace</param>
        /// <returns>return Assembly</returns>
        public static Assembly GetWebServiceAssembly(string wsdl, string nameSpace)
        {
            try
            {
                System.Net.WebClient webClient = new System.Net.WebClient();
                System.IO.Stream webStream = webClient.OpenRead(wsdl);

                ServiceDescription serviceDescription = ServiceDescription.Read(webStream);
                ServiceDescriptionImporter serviceDescroptImporter = new ServiceDescriptionImporter();

                serviceDescroptImporter.AddServiceDescription(serviceDescription, "", "");
                System.CodeDom.CodeNamespace codeNameSpace = new System.CodeDom.CodeNamespace(nameSpace);
                System.CodeDom.CodeCompileUnit codeCompileUnit = new System.CodeDom.CodeCompileUnit();
                codeCompileUnit.Namespaces.Add(codeNameSpace);
                serviceDescroptImporter.Import(codeNameSpace, codeCompileUnit);

                System.CodeDom.Compiler.CodeDomProvider codeDom = new Microsoft.CSharp.CSharpCodeProvider();
                System.CodeDom.Compiler.CompilerParameters codeParameters = new System.CodeDom.Compiler.CompilerParameters();
                codeParameters.GenerateExecutable = false;
                codeParameters.GenerateInMemory = true;

                codeParameters.ReferencedAssemblies.Add("System.dll");
                codeParameters.ReferencedAssemblies.Add("System.XML.dll");
                codeParameters.ReferencedAssemblies.Add("System.Web.Services.dll");
                codeParameters.ReferencedAssemblies.Add("System.Data.dll");

                System.CodeDom.Compiler.CompilerResults compilerResults = codeDom.CompileAssemblyFromDom(codeParameters, codeCompileUnit);

                return compilerResults.CompiledAssembly;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Exemple #4
0
        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            // the URL to download the file from
            string sUrlToReadFileFrom = textBoxSourceFile.Text;
            // the path to write the file to
            int iLastIndex = sUrlToReadFileFrom.LastIndexOf('/');
            string sDownloadFileName = sUrlToReadFileFrom.Substring(iLastIndex + 1, (sUrlToReadFileFrom.Length - iLastIndex - 1));
            string sFilePathToWriteFileTo = textBoxDestinationFolder.Text + "\\" + sDownloadFileName;

            // first, we need to get the exact size (in bytes) of the file we are downloading
            Uri url = new Uri(sUrlToReadFileFrom);
            System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
            System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse();
            response.Close();
            // gets the size of the file in bytes
            Int64 iSize = response.ContentLength;

            // keeps track of the total bytes downloaded so we can update the progress bar
            Int64 iRunningByteTotal = 0;

            // use the webclient object to download the file
            using (System.Net.WebClient client = new System.Net.WebClient())
            {
                // open the file at the remote URL for reading
                using (System.IO.Stream streamRemote = client.OpenRead(new Uri(sUrlToReadFileFrom)))
                {
                    // using the FileStream object, we can write the downloaded bytes to the file system
                    using (Stream streamLocal = new FileStream(sFilePathToWriteFileTo, FileMode.Create, FileAccess.Write, FileShare.None))
                    {
                        // loop the stream and get the file into the byte buffer
                        int iByteSize = 0;
                        byte[] byteBuffer = new byte[iSize];
                        while ((iByteSize = streamRemote.Read(byteBuffer, 0, byteBuffer.Length)) > 0)
                        {
                            // write the bytes to the file system at the file path specified
                            streamLocal.Write(byteBuffer, 0, iByteSize);
                            iRunningByteTotal += iByteSize;

                            // calculate the progress out of a base "100"
                            double dIndex = (double)(iRunningByteTotal);
                            double dTotal = (double)byteBuffer.Length;
                            double dProgressPercentage = (dIndex / dTotal);
                            int iProgressPercentage = (int)(dProgressPercentage * 100);

                            // update the progress bar
                            backgroundWorker1.ReportProgress(iProgressPercentage);
                        }

                        // clean up the file stream
                        streamLocal.Close();
                    }

                    // close the connection to the remote server
                    streamRemote.Close();
                }
            }
        }
        public GeoSuggestion GetOne(string term)
        {
            if (!string.IsNullOrEmpty(term))
            {
                var key = Regex.Replace(term, @"[\s\.,;:]", "");
                var cache = new Cahching.Cache<GeoSuggestion>();
                var geoSug = cache.Get(key);
                if (geoSug != null)
                    return geoSug;

                System.Net.WebClient client = new System.Net.WebClient();

                // Add a user agent header in case the
                // requested URI contains a query.

                //client.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
                client.QueryString.Add("input", term);
                client.QueryString.Add("sensor", "false");
                client.QueryString.Add("types", "geocode");
                client.QueryString.Add("key", ConfigurationManager.AppSettings["GoogleAPIKey"]);

                System.IO.Stream data = client.OpenRead("https://maps.googleapis.com/maps/api/place/autocomplete/xml");
                System.IO.StreamReader reader = new System.IO.StreamReader(data);
                string str = reader.ReadToEnd();

                data.Close();
                reader.Close();

                XDocument xdoc = XDocument.Parse(str);
                var status = xdoc.Root.Descendants("status").Single();
                if (status.Value == "OK")
                {
                    var suggestions = xdoc.Root.Descendants("prediction")
                        //.Where(p => p.Descendants("type").Any(s => s.Value == "geocode" || s.Value == "route"))
                            .Select(p => new Suggestion
                            {
                                id = p.Descendants("id").Single().Value,
                                descr = p.Descendants("description").Single().Value,
                                refer = p.Descendants("reference").Single().Value,
                                term = p.Descendants("term").Descendants("value").First().Value,
                                matches = p.Descendants("matched_substring").Skip(2).Select(s => new MatchedSubstring {
                                    offset = int.Parse(s.Descendants("offset").Single().Value),
                                    length = int.Parse(s.Descendants("length").Single().Value)}).ToArray()
                            }).ToArray();
                    geoSug = new GeoSuggestion { term = term, suggestions = suggestions };

                    cache.Set(key, geoSug);

                    return geoSug;
                }

            }

            return new GeoSuggestion { term = term, suggestions = new Suggestion[0] };
        }
Exemple #6
0
 public void Generate()
 {
     if (this.AddressType == AddressType.WebService)
     {
         string className = MethodHelper.GetClassName(this.Address);
         //Get wsdl information
         System.Net.WebClient wc = new System.Net.WebClient();
         System.IO.Stream strm = wc.OpenRead(Address + "?WSDL");
         ServiceDescription sd = ServiceDescription.Read(strm);
         ServiceDescriptionImporter sdi = new ServiceDescriptionImporter();
         sdi.AddServiceDescription(sd, "", "");
         CodeNamespace cn = new CodeNamespace(this.ComileNamespace);
         //Generate client proxy class
         CodeCompileUnit ccu = new CodeCompileUnit();
         ccu.Namespaces.Add(cn);
         sdi.Import(cn, ccu);
         CSharpCodeProvider csc = new CSharpCodeProvider();
         ICodeCompiler icc = csc.CreateCompiler();
         //Setting compile parameters
         CompilerParameters compilerParams = new CompilerParameters();
         compilerParams.GenerateExecutable = false;
         compilerParams.GenerateInMemory = true;
         compilerParams.ReferencedAssemblies.Add("System.dll");
         compilerParams.ReferencedAssemblies.Add("System.XML.dll");
         compilerParams.ReferencedAssemblies.Add("System.Web.Services.dll");
         compilerParams.ReferencedAssemblies.Add("System.Data.dll");
         //compile agentcy class
         CompilerResults cr = icc.CompileAssemblyFromDom(compilerParams, ccu);
         if (true == cr.Errors.HasErrors)
         {
             System.Text.StringBuilder sb = new System.Text.StringBuilder();
             foreach (System.CodeDom.Compiler.CompilerError ce in cr.Errors)
             {
                 sb.Append(ce.ToString());
                 sb.Append(System.Environment.NewLine);
             }
             throw new Exception(sb.ToString());
         }
         this.ProxyAssemble = cr.CompiledAssembly;
         Type t = this.ProxyAssemble.GetType(string.Concat(this.ComileNamespace, ".", className), true, true);
         ServiceObject = Activator.CreateInstance(t);
     }
     else
     {
         ServiceObject = new NormalRequest();
     }
     SetUrl(this.Address);
 }
        /// <summary>  
        /// 根据WEBSERVICE地址获取一个 Assembly  
        /// </summary>  
        /// <param name="p_Url">地址</param>  
        /// <param name="p_NameSpace">命名空间</param>  
        /// <returns>返回Assembly</returns>  
        public static Assembly GetWebServiceAssembly(string p_Url, string p_NameSpace)
        {
            try
            {
                System.Net.WebClient _WebClient = new System.Net.WebClient();

                System.IO.Stream _WebStream = _WebClient.OpenRead(p_Url);

                ServiceDescription _ServiceDescription = ServiceDescription.Read(_WebStream);

                _WebStream.Close();
                _WebClient.Dispose();
                ServiceDescriptionImporter _ServiceDescroptImporter = new ServiceDescriptionImporter();
                _ServiceDescroptImporter.AddServiceDescription(_ServiceDescription, "", "");
                System.CodeDom.CodeNamespace _CodeNameSpace = new System.CodeDom.CodeNamespace(p_NameSpace);
                System.CodeDom.CodeCompileUnit _CodeCompileUnit = new System.CodeDom.CodeCompileUnit();
                _CodeCompileUnit.Namespaces.Add(_CodeNameSpace);
                _ServiceDescroptImporter.Import(_CodeNameSpace, _CodeCompileUnit);

                System.CodeDom.Compiler.CodeDomProvider _CodeDom = new Microsoft.CSharp.CSharpCodeProvider();
                System.CodeDom.Compiler.CompilerParameters _CodeParameters = new System.CodeDom.Compiler.CompilerParameters();
                _CodeParameters.GenerateExecutable = false;
                _CodeParameters.GenerateInMemory = true;
                _CodeParameters.ReferencedAssemblies.Add("System.dll");
                _CodeParameters.ReferencedAssemblies.Add("System.XML.dll");
                _CodeParameters.ReferencedAssemblies.Add("System.Web.Services.dll");
                _CodeParameters.ReferencedAssemblies.Add("System.Data.dll");

                System.CodeDom.Compiler.CompilerResults _CompilerResults = _CodeDom.CompileAssemblyFromDom(_CodeParameters, _CodeCompileUnit);

                if (_CompilerResults.Errors.HasErrors)
                {
                    string _ErrorText = "";
                    foreach (CompilerError _Error in _CompilerResults.Errors)
                    {
                        _ErrorText += _Error.ErrorText + "/r/n";
                    }
                    throw new Exception(_ErrorText);
                }

                return _CompilerResults.CompiledAssembly;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Exemple #8
0
 public static bool CheckConnectInternet()
 {
     try
     {
         using (var client = new System.Net.WebClient())
         {
             using (var stream = client.OpenRead("http://api.nbp.pl"))
             {
                 return(true);
             }
         }
     }
     catch (Exception e)
     {
         return(false);
     }
 }
 private void SummaryButton_Click(object sender, RoutedEventArgs e)
 {
     System.Net.WebClient web = new System.Net.WebClient();
     web.BaseAddress = "https://github.com/IanMcT/April8_2019Assignment";
     System.IO.StreamReader stream = new System.IO.StreamReader
                                         (web.OpenRead("https://raw.githubusercontent.com/IanMcT/April8_2019Assignment/master/2018.txt"));
     Total         = 0;
     salesPerMonth = 0;
     stream.ReadLine();
     while (!stream.EndOfStream)
     {
         double.TryParse(stream.ReadLine(), out salesPerMonth);
         Total += salesPerMonth;
     }
     stream.Close();
     lblOutput.Content = "Total Sales: $" + Total + Environment.NewLine + "Average Sales: $" + Total / 12;
 }
        public static void CheckForUpdates()
        {
            // Get the installation path
            DirectoryInfo installationPath = GetInstallationPath();

            XmlSerializer deserializer = new XmlSerializer(typeof(ButtonConfiguration));
            ButtonConfiguration buttonConfig;

            // Iterate over Add-ins found
            DirectoryInfo buttonRoot = new DirectoryInfo(Path.Combine(installationPath.FullName, "Buttons"));
            DirectoryInfo[] buttons = buttonRoot.GetDirectories();
            foreach (FileInfo file in buttons.Select(button => new FileInfo(Path.Combine(button.FullName, "config.xml"))))
            {
                // open the configuration file for the button
                using (FileStream buttonStream = new FileStream(file.FullName, FileMode.Open, FileAccess.Read))
                {
                    buttonConfig = (ButtonConfiguration)deserializer.Deserialize(buttonStream);
                }

                // if an onlineUrl is present, then we look for an update
                if (!string.IsNullOrEmpty(buttonConfig.onlineUrl))
                {
                    string currentMenu;
                    using (TextReader tr = new StreamReader(Path.Combine(file.DirectoryName, @"button.xml")))
                    {
                        currentMenu = tr.ReadToEnd();
                    }

                    using (System.Net.WebClient client = new System.Net.WebClient())
                    {
                        Stream myStream = client.OpenRead(buttonConfig.onlineUrl);
                        using (StreamReader sr = new StreamReader(myStream))
                        {
                            string latestMenu = sr.ReadToEnd();
                            if (latestMenu != currentMenu)
                            {
                                using (TextWriter tw = new StreamWriter(Path.Combine(file.DirectoryName, @"button.xml")))
                                {
                                    tw.Write(latestMenu);
                                }
                            }
                        }
                    }
                }
            }
        }
 public static bool isConnected()
 {
     try
     {
         using (var client = new System.Net.WebClient())
         {
             using (client.OpenRead("http://clients3.google.com/generate_204"))
             {
                 return(true);
             }
         }
     }
     catch
     {
         return(false);
     }
 }
 private static bool CheckForInternetConnection()
 {
     try
     {
         using (var client = new System.Net.WebClient())
         {
             using (var stream = client.OpenRead("http://www.google.com"))
             {
                 return true;
             }
         }
     }
     catch
     {
         return false;
     }
 }
 private bool FileExists(string URL)
 {
     bool result = false;
     using (System.Net.WebClient client = new System.Net.WebClient())
     {
         try
         {
             System.IO.Stream str = client.OpenRead(URL);
             if (str != null) result = true; else result = false;
         }
         catch
         {
             result = false;
         }
     }
     return result;
 }
 private static bool CheckForInternetConnection()
 {
     try
     {
         using (var client = new System.Net.WebClient())
         {
             using (var stream = client.OpenRead("http://www.google.com"))
             {
                 return(true);
             }
         }
     }
     catch
     {
         return(false);
     }
 }
 private void ReadFromHubbleImages(string aPlayfieldMap)
 {
     using (System.Net.WebClient client = new System.Net.WebClient())
     {
         client.Headers.Add("content-type", "application/json");
         Stream data = client.OpenRead("http://hubblesite.org/api/v3/news_release/last");
         using (StreamReader messageReader = new StreamReader(data))
         {
             dynamic Content = JsonConvert.DeserializeObject(messageReader.ReadToEnd());
             using (var clientImg = new System.Net.WebClient())
             {
                 Directory.CreateDirectory(Path.GetDirectoryName(aPlayfieldMap));
                 clientImg.DownloadFile(new Uri("http:" + Content.keystone_image_2x.ToString()), aPlayfieldMap);
             }
         }
     }
 }
Exemple #16
0
        public MainWindow()
        {
            InitializeComponent();
            System.Net.WebClient webClient = new System.Net.WebClient();
            webClient.BaseAddress = "https://weather.gc.ca/city/pages/on-88_metric_e.html";
            System.IO.StreamWriter streamWriter = new System.IO.StreamWriter("Weather.txt");
            System.IO.StreamReader streamReader = new System.IO.StreamReader(webClient.OpenRead("https://weather.gc.ca/city/pages/on-88_metric_e.html"));
            bool temp = false;

            try
            {
                while (!streamReader.EndOfStream)
                {
                    string line = streamReader.ReadLine();
                    //        MessageBox.Show(line);
                    //        streamWriter.WriteLine(line);
                    if (temp == true)
                    {
                        //   string temp2 = line.IndexOf("u\0076",50).ToString();
                        //location of >

                        int locOfGreater = line.IndexOf("\x3E");
                        MessageBox.Show("\x26");
                        //find &
                        int    locOfAmpersand = line.IndexOf("\x26");
                        string tempTemp       = line.Substring(locOfGreater + 1, locOfAmpersand - locOfGreater - 1);
                        MessageBox.Show(tempTemp);
                        MessageBox.Show("> " + locOfGreater.ToString() + "\n" + "& " + locOfAmpersand.ToString());
                        MessageBox.Show(line);
                        MessageBox.Show(line.IndexOf("\u0076", line.IndexOf("\u0046")).ToString());
                        streamWriter.WriteLine(line);
                    }
                    temp = line.Contains("Temperature");
                }
                streamWriter.Write(streamReader.ReadToEnd());
                streamWriter.Flush();
                streamWriter.Close();
                streamWriter.Close();
                MessageBox.Show("I Have read everything!");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "Error");
            }
        }
Exemple #17
0
 static Bitmap DownloadImage(string fromUrl)
 {
     try
     {
         using (System.Net.WebClient webClient = new System.Net.WebClient())
         {
             using (System.IO.Stream stream = webClient.OpenRead(fromUrl))
             {
                 return((Bitmap)Image.FromStream(stream));
             }
         }
     }
     catch (Exception ex)
     {
         log.Error("exception in DownloadImage", ex);
     }
     return(null);
 }
 public void summary(string url)
 {
     lblOutput.Content = "";
     System.Net.WebClient   webClient    = new System.Net.WebClient();
     System.IO.StreamReader streamReader = new System.IO.StreamReader
                                               (webClient.OpenRead(url));
     total      = 0;
     monthSales = 0;
     streamReader.ReadLine();
     while (!streamReader.EndOfStream)
     {
         double.TryParse(streamReader.ReadLine(), out monthSales);
         total += monthSales;
     }
     streamReader.Close();
     lblOutput.Content = "Total sales: $" + total + Environment.NewLine +
                         "Average sales: $" + total / 12;
 }
Exemple #19
0
        private void FindAndReplace(object sender, RoutedEventArgs e)
        {
            string Link = txtInputLink.Text;

            System.Net.WebClient   theInterWebs = new System.Net.WebClient();
            System.IO.StreamReader streamReader = new System.IO.StreamReader(theInterWebs.OpenRead(Link));
            System.IO.StreamWriter streamWriter = new System.IO.StreamWriter("teams.txt");
            try
            {
                //variable
                string Output         = "Lines Found with word or phrase: " + "\r";
                string Word           = txtInputFind.Text;
                int    numberOfThings = 0;
                while (!streamReader.EndOfStream)
                {
                    string line = streamReader.ReadLine();
                    if (line.Contains(Word))
                    {
                        numberOfThings = numberOfThings + 1;
                        MessageBox.Show("Number of Items: " + numberOfThings.ToString());

                        /*// MessageBox.Show(line);
                         * //add the team to the variable with a new line
                         * int StartIndex = 12;
                         * int Length = 7;
                         * substring = line.Substring(StartIndex, Length);
                         * AllTeams = AllTeams + substring + "\r";
                         * //MessageBox.Show(substring);*/
                        streamWriter.WriteLine(line);
                        Output = Output + line + "\r";
                    }
                }
                lblOutput.Content = Output;
                //message box to show the variable
                streamWriter.Flush();
                streamWriter.Close();
                streamReader.Close();
                // MessageBox.Show("\n" + "    Here in my garage, just bought this new Lamborghini here. It’s fun to drive up here in the Hollywood hills. But you know what I like more than materialistic things? Knowledge.");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "error");
            }
        }
Exemple #20
0
        private byte[] DownloadData(string url)
        {
            System.IO.Stream stream = wc.OpenRead(url);

            try
            {
                byte[] buffer = new byte[512];
                int    read   = 0;
                int    chunk;

                while ((chunk = stream.Read(buffer, read, buffer.Length - read)) > 0)
                {
                    read += chunk;

                    if (read == buffer.Length)
                    {
                        Application.DoEvents();

                        int nextByte = stream.ReadByte();

                        if (nextByte == -1)
                        {
                            return(buffer);
                        }

                        byte[] newBuffer = new byte[buffer.Length * 2];
                        Array.Copy(buffer, newBuffer, buffer.Length);
                        newBuffer[read] = (byte)nextByte;
                        buffer          = newBuffer;
                        read++;
                    }
                }

                byte[] ret = new byte[read];
                Array.Copy(buffer, ret, read);

                return(ret);
            }
            finally
            {
                stream.Close();
                stream = null;
            }
        }
Exemple #21
0
        private static string[] readData()
        {
            string[] data = null;

            try
            {
                System.Net.ServicePointManager.ServerCertificateValidationCallback = Util.Helper.RemoteCertificateValidationCallback;

                using (System.Net.WebClient client = new System.Net.WebClient())
                {
                    using (System.IO.Stream stream = client.OpenRead(Util.Constants.ASSET_UPDATE_CHECK_URL))
                    {
                        using (System.IO.StreamReader reader = new System.IO.StreamReader(stream))
                        {
                            string content = reader.ReadToEnd();

                            foreach (string line in Util.Helper.SplitStringToLines(content))
                            {
                                if (line.StartsWith(Util.Constants.ASSET_UID.ToString()))
                                {
                                    data = line.Split(splitChar, System.StringSplitOptions.RemoveEmptyEntries);

                                    if (data != null && data.Length >= 3) //valid record?
                                    {
                                        break;
                                    }
                                    else
                                    {
                                        data = null;
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (System.Exception ex)
            {
                Debug.LogError("Could not load update file: " + System.Environment.NewLine + ex);
            }

            return(data);
        }
Exemple #22
0
 private void Updateskills_Click(object sender, RoutedEventArgs e)
 {
     try
     {
         using (System.Net.WebClient client = new System.Net.WebClient())
         {
             Stream stream = client.OpenRead("https://remon-7l.github.io/skills_ja.csv");
             using (StreamReader streamReader = new StreamReader(stream))
             {
                 string content = streamReader.ReadToEnd();
                 File.WriteAllText("skills_ja.csv", content);
             }
         }
     }
     catch
     {
         MessageBox.Show("skills.csvの取得に失敗しました。");
     }
 }
        private string GetProxyTicketFromCAS(string targetService, string _pgt)
        {
            string pt     = string.Empty;
            string server = "https://thekey.me/cas/";

            string validateurl = server + "proxy?targetService=" + targetService + "&pgt=" + _pgt.Trim().ToString();


            System.IO.Stream s;

            try
            {
                System.Net.WebClient wc = new System.Net.WebClient();
                s = wc.OpenRead(validateurl);
            }
            catch (Exception e)
            {
                // error
                return(pt);
            }

            StreamReader streamReader = new StreamReader(s);

            XmlDocument doc = new XmlDocument();

            doc.Load(streamReader);
            XmlNamespaceManager NamespaceMgr = new XmlNamespaceManager(doc.NameTable);

            NamespaceMgr.AddNamespace("cas", "http://www.yale.edu/tp/cas");

            XmlNode SuccessNode = doc.SelectSingleNode("/cas:serviceResponse/cas:proxySuccess", NamespaceMgr);

            if (!(SuccessNode == null))
            {
                XmlNode ProxyTicketNode = SuccessNode.SelectSingleNode("./cas:proxyTicket", NamespaceMgr);
                if (!(ProxyTicketNode == null))
                {
                    return(ProxyTicketNode.InnerText);
                }
            }

            return(pt);
        }
Exemple #24
0
        private void DataGridView1_RowEnter(object sender, DataGridViewCellEventArgs e)
        {
            pictureBox1.Image = null;
            if (e.RowIndex >= searchResults.Count)
            {
                return;
            }

            textBox_Synopsis.Text = searchResults[e.RowIndex].Synopsis;


            using (System.Net.WebClient webClient = new System.Net.WebClient())
            {
                using (Stream stream = webClient.OpenRead(searchResults[e.RowIndex].ImageURL))
                {
                    pictureBox1.Image = Image.FromStream(stream);
                }
            }
        }
        public Version GetRemoteVersion()
        {
            try {
                string json;
                using (var web_client = new System.Net.WebClient()) {
                    // https://developer.github.com/v3/#user-agent-required
                    web_client.Headers.Add("User-Agent", "RPHCCactbot");
                    using (var reader = new System.IO.StreamReader(web_client.OpenRead(kReleaseApiEndpointUrl))) {
                        json = reader.ReadToEnd();
                    }
                }
                dynamic latest_release = new System.Web.Script.Serialization.JavaScriptSerializer().DeserializeObject(json);

                return(new Version(latest_release["tag_name"].Replace("v", "")));
            } catch (Exception e) {
                logger_.LogError("Error fetching most recent github release: " + e.Message + "\n" + e.StackTrace);
                return(new Version());
            }
        }
Exemple #26
0
        /// <summary>
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static Bitmap GetBitmapByUrl(string url)
        {
            if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
            {
                System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;
            }
            var wc = new System.Net.WebClient();

            wc.Proxy = null;
            var image = new Bitmap(wc.OpenRead(url));

            if (image.HorizontalResolution == 0 && image.VerticalResolution == 0)
            {
                var gImage = Graphics.FromImage(image);
                image.SetResolution(gImage.DpiX, gImage.DpiY);
            }

            return(image);
        }
Exemple #27
0
 private string getRawInfoByAPI(string type, string id)
 {
     System.Net.WebClient wc = new System.Net.WebClient();
     using (System.IO.Stream s = wc.OpenRead(string.Format("http://120.24.210.35:3000/data/market/{0}?record_id={1}", type, id)))
     {
         using (System.IO.StreamReader sr = new System.IO.StreamReader(s))
         {
             JObject jo = (JObject)JsonConvert.DeserializeObject(sr.ReadToEnd());
             if ((string)jo["STS"] == "OK")
             {
                 return((string)jo["data"]);
             }
             else
             {
                 return(null);
             }
         }
     }
 }
Exemple #28
0
        public void ConnectionEstablished()
        {
            bool connection = false;

            try
            {
                using (var client = new System.Net.WebClient())
                {
                    using (client.OpenRead("https://cyberdrop.me/a/mowoshqo"))
                    {
                        connection = true;
                    }
                }
            } catch
            {
                connection = false;
            }
            Assert.True(connection);
        }
 private void bgOggSetup_DoWork(object sender, DoWorkEventArgs e)
 {
     try
     {
         string sUrlToReadFileFrom     = "http://85.195.82.94/PlayerFiles/XiphOrgOpenCodecs08517777.exe";
         string sFilePathToWriteFileTo = Application.StartupPath + "\\XiphOrgOpenCodecs08517777.exe";
         Uri    url = new Uri(sUrlToReadFileFrom);
         System.Net.HttpWebRequest  request  = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
         System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse();
         response.Close();
         Int64 iSize             = response.ContentLength;
         Int64 iRunningByteTotal = 0;
         using (System.Net.WebClient client = new System.Net.WebClient())
         {
             using (System.IO.Stream streamRemote = client.OpenRead(new Uri(sUrlToReadFileFrom)))
             {
                 using (Stream streamLocal = new FileStream(sFilePathToWriteFileTo, FileMode.Create, FileAccess.Write, FileShare.None))
                 {
                     int    iByteSize  = 0;
                     byte[] byteBuffer = new byte[iSize];
                     while ((iByteSize = streamRemote.Read(byteBuffer, 0, byteBuffer.Length)) > 0)
                     {
                         streamLocal.Write(byteBuffer, 0, iByteSize);
                         iRunningByteTotal += iByteSize;
                         double dIndex = (double)(iRunningByteTotal);
                         double dTotal = (double)byteBuffer.Length;
                         double dProgressPercentage = (dIndex / dTotal);
                         int    iProgressPercentage = (int)(dProgressPercentage * 100);
                         bgOggSetup.ReportProgress(iProgressPercentage);
                     }
                     streamLocal.Close();
                 }
                 streamRemote.Close();
             }
         }
     }
     catch (Exception ex)
     {
         Application.Restart();
         Console.WriteLine(ex.Message);
     }
 }
Exemple #30
0
        public void ConnectionEstablished()
        {
            bool connection = false;

            try
            {
                using (var client = new System.Net.WebClient())
                {
                    client.Headers.Add("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36");
                    using (client.OpenRead("https://cyberdrop.me/a/mowoshqo"))
                    {
                        connection = true;
                    }
                }
            } catch
            {
                connection = false;
            }
            Assert.True(connection);
        }
Exemple #31
0
        public static bool HasConnection()
        {
            var temp = false;

            try
            {
                using (var webClient = new System.Net.WebClient())
                {
                    using (webClient.OpenRead("http://google.com"))
                    {
                        temp = true;
                    }
                }
            }
            catch (Exception exc)
            {
                Logging.Logger.Log(exc);
            }
            return(temp);
        }
Exemple #32
0
    public string ToHtml()
    {
        var client = new System.Net.WebClient();

        do
        {
            try
            {
                using (var reader = new StreamReader(client.OpenRead(this.Uri)))
                {
                    return(reader.ReadToEnd());
                }
            }
            catch (WebException ex)
            {
                // log ex
            }
        }while (KeepTrying);
        return(null);
    }
Exemple #33
0
        public Dictionary<string, string> ParseAnimePreviewFromWeb(string url)
        {
            /*var web = new HtmlWeb ();
            web.AutoDetectEncoding = false;
            web.OverrideEncoding = System.Text.Encoding.GetEncoding ("windows-1251");
            var doc = web.Load (url);
            return ParseAnimePreview (doc);*/

            var document = new HtmlDocument();
            using (var client = new System.Net.WebClient())
            {
                using (var stream = client.OpenRead(url))
                {
                    var reader = new StreamReader(stream, System.Text.Encoding.GetEncoding("windows-1251"));
                    var html = reader.ReadToEnd();
                    document.LoadHtml(html);
                }
            }
            return ParseAnimePreview(document);
        }
Exemple #34
0
 void GetTextSearchRequest(string tGoogleSearch, out String Results)
 {
     Results = "";
     System.Net.WebClient http = new System.Net.WebClient();
     try
     {
         System.IO.Stream tStream = http.OpenRead(tGoogleSearch);
         if (tStream != null)
         {
             StreamReader sr = new StreamReader(tStream);
             Results = sr.ReadToEnd();
         }
     }
     catch (ArgumentNullException nex)
     {
     }
     catch (System.Net.WebException ex)
     {
     }
 }
        //
        // static methods
        //

        public static PDFImageData LoadImageFromURI(string uri, IPDFComponent owner = null)
        {
            System.Net.WebClient wc = new System.Net.WebClient();
            wc.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;

            bool compress = false;

            if (owner is IPDFOptimizeComponent)
            {
                compress = ((IPDFOptimizeComponent)owner).Compress;
            }

            using (wc.OpenRead(uri))
            {
                PDFImageData img;
                byte[]       data = wc.DownloadData(uri);
                img = InitImageData(uri, data, compress);
                return(img);
            }
        }
        public Version GetRemoteVersion()
        {
            string html;

            try
            {
                var web = new System.Net.WebClient();
                System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Ssl3 | System.Net.SecurityProtocolType.Tls | System.Net.SecurityProtocolType.Tls11 | System.Net.SecurityProtocolType.Tls12;
                var page_stream = web.OpenRead(kReleaseUrl);
                var reader      = new System.IO.StreamReader(page_stream);
                html = reader.ReadToEnd();
            }
            catch (Exception e)
            {
                PercentilePlugin.Logger.Log(LogLevel.Error, "Error fetching most recent github release: " + e.Message + "\n" + e.StackTrace);
                return(new Version());
            }

            var pattern = @"href=""/liquidize/FFXIV_PercentilePlugin/releases/download/v?(?<Version>.*?)/";
            var regex   = new Regex(pattern, RegexOptions.IgnoreCase | RegexOptions.Singleline);
            var match   = regex.Match(html);

            if (!match.Success)
            {
                PercentilePlugin.Logger.Log(LogLevel.Error, "Error parsing most recent github release, no match found. Please report an issue at " + kIssueUrl);
                return(new Version());
            }

            string version_string = match.Groups["Version"].Value;

            pattern = @"(?<VersionNumber>(?<Major>[0-9]+)\.(?<Minor>[0-9]+)\.(?<Revision>[0-9+]))";
            regex   = new Regex(pattern);
            match   = regex.Match(version_string);
            if (!match.Success)
            {
                PercentilePlugin.Logger.Log(LogLevel.Error, "Error parsing most recent github release, no version number found. Please report an issue at " + kIssueUrl);
                return(new Version());
            }

            return(new Version(int.Parse(match.Groups["Major"].Value), int.Parse(match.Groups["Minor"].Value), int.Parse(match.Groups["Revision"].Value)));
        }
Exemple #37
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="context"></param>
        public virtual void ReadFrom(AppHelperContext context)
        {
            if (context["year"] != null)
            {
                try
                {
                    this.Date = DateTime.Parse(context["year"].ToString());
                }
                catch
                {
                    try
                    {
                        int year = int.Parse(context["year"].ToString());
                        this.Date = new DateTime(year, 1, 1);
                    }
                    catch
                    {
                        this.Date = DateTime.MinValue;
                    }
                }
            }
            this.Genre       = (string)context["genre"];
            this.Description = (string)context["summary"];
            this.Title       = (string)context["title"];
            this.Country     = (string)context["country"];
            this.Length      = (string)context["length"];
            this.Rating      = (string)context["rating"];
            this.Director    = (string)context["director"];
            this.Cast        = (string)context["cast"];

            if (context["imageURL"] != null)

            {
                System.Net.WebClient client = new System.Net.WebClient( );
                this.Image = Image.FromStream(client.OpenRead(new Uri((string)context["imageURL"])));
            }
            else
            {
                this.Image = null;
            }
        }
Exemple #38
0
        public string GetHtml(string url)
        {
            using (System.Net.WebClient client = new System.Net.WebClient())
            {
                client.Headers.Add(
                    "User-Agent",
                    "Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; Touch; rv:11.0) like Gecko");

                System.IO.Stream srmBuff = client.OpenRead(url);
                Byte[]           bytBuff = {};

                using (System.IO.MemoryStream srmMemory = new System.IO.MemoryStream())
                {
                    Byte[] bytRead = { };
                    int    intRead = 0;
                    Array.Resize(ref bytRead, 1024);
                    intRead = srmBuff.Read(bytRead, 0, bytRead.Length);

                    do
                    {
                        srmMemory.Write(bytRead, 0, intRead);
                        intRead = srmBuff.Read(bytRead, 0, bytRead.Length);
                    } while (intRead > 0);

                    bytBuff = srmMemory.ToArray();
                }

                srmBuff.Close();

                System.Text.Encoding enc = GetCode(bytBuff);

                if (enc == null)
                {
                    enc = System.Text.Encoding.ASCII;
                }

                string html = enc.GetString(bytBuff);

                return(html);
            }
        }
Exemple #39
0
        /// <summary>
        /// Beszerzi a legfrisebb térképet, szétparszolja, és elrakja
        /// ToDo: Csak akkor kéne elrakni, ha különbözik az előzőtől
        /// Ijen egy sor:
        /// INSERT INTO `x_world` VALUES (188644,8,165,1,45770,'Mr G faluja',30778,'Mr G',0,'',3);
        /// </summary>
        /// <param name="url">Innen töltike lefelé</param>
        /// <param name="Data">Ide kell elrakni</param>
        public static void Collect(string url, TraviData Data)
        {
            System.Net.WebClient Client = new System.Net.WebClient();
            Stream strm = Client.OpenRead(url);
            StreamReader sr = new StreamReader(strm);
            string line;
            string[] details;
            DateTime now = DateTime.Now;
            do
            {
                line = sr.ReadLine();
                if (line != null)
                {
                    line = line.Substring(30, line.Length - 32);
                    details = line.Split(',');
                    MapElement me = new MapElement();
                    me.TimeStamp = now;

                    try
                    {
                        me.Id = int.Parse(details[0]);
                        me.X = int.Parse(details[1]);
                        me.Y = int.Parse(details[2]);
                        me.Tid = int.Parse(details[3]);
                        me.Vid = int.Parse(details[4]);
                        me.Village = details[5].Trim('\'');
                        me.Uid = int.Parse(details[6]);
                        me.Player = details[7].Trim('\'');
                        me.Aid = int.Parse(details[8]);
                        me.Alliance = details[9].Trim('\'');
                        me.Population = int.Parse(details[10]);

                    }
                    catch { }
                    Data.Map.Add(me);
                }

            }
            while (line != null);
            strm.Close();
        }
        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="DocType"></param>
        /// <param name="bwaID"></param>
        /// <param name="file"></param>
        /// <summary>
        //[HttpPost]
        //public ActionResult UploadFuJian(string recordId, string fjlb = "document")
        //{
        //    var file = Request.Files[0];

        //    if (string.IsNullOrEmpty(recordId))
        //    {
        //        throw new Exception("recordId不能为空");
        //    }

        //    if (file != null && file.ContentLength > 0)
        //    {
        //        try
        //        {
        //            var httpDirectory = string.Format("{0}/{1}/{2}/", FtpServerHttp, recordId, fjlb);
        //            //用全角#替换半角#,避免下载、预览时出错
        //            var ftpFileName = Path.GetFileName(file.FileName.Substring(0, file.FileName.LastIndexOf('.')).Replace("#", "#").Replace("+", "+")) + Path.GetExtension(file.FileName).ToLower();

        //            var filePath = string.Format("/{0}/{1}", recordId, fjlb);
        //            var uploadSuccess = fileUpload(file, filePath, ftpFileName, true);

        //            if (uploadSuccess == false)
        //            {
        //                return Json(new { success = false });
        //            }

        //            var entity = new Sys_Attachment()
        //            {
        //                NAME = ftpFileName.Replace("#", "#").Replace("+", "+"),
        //                PATH = httpDirectory + ftpFileName.Replace("#", "#").Replace("+", "+"),
        //                FILETYPE = Path.GetExtension(ftpFileName).ToLower(),
        //                ISDIRECTORY = false,
        //                CREATOR = User.Identity.Name,
        //                CREATETIME = DateTime.Now,
        //                RecordID = recordId,
        //                SortNumber = 100,
        //                PARENTID = "",
        //                Category = fjlb
        //            };
        //            entity.Save();
        //            return Json(new { name = ftpFileName.Replace("#", "#").Replace("+", "+"), path = httpDirectory + ftpFileName.Replace("#", "#").Replace("+", "+"), success = true });

        //        }
        //        catch (Exception)
        //        {
        //            return Json(new { success = false });
        //        }
        //    }
        //    else
        //    {
        //        return Json(new { success = false });
        //    }
        //}


        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <returns>文件流</returns>
        public ActionResult DownFile(string filePath, string fileName = "")
        {
            if (string.IsNullOrEmpty(fileName))
            {
                fileName = filePath.Split('/').Last();
                fileName = fileName.Split('\\').Last();
            }


            System.Net.WebClient myWebClient = new System.Net.WebClient();
            try
            {
                var stream = myWebClient.OpenRead(filePath);

                return(File(stream, "APPLICATION/OCTET-STREAM", HttpUtility.UrlEncode(fileName, Encoding.GetEncoding("UTF-8"))));
            }
            catch (Exception)
            {
            }
            return(View("Error"));
        }
        private void OpenRead()
        {
            this.LogTaskMessage(string.Format(CultureInfo.InvariantCulture, "Reading: {0}", this.Url));
            using (System.Net.WebClient client = new System.Net.WebClient())
            {
                if (!string.IsNullOrEmpty(this.Proxy))
                {
                    client.Proxy = new System.Net.WebProxy(this.Proxy, this.BypassOnLocal);
                }

                Stream myStream = client.OpenRead(this.Url);
                using (StreamReader sr = new StreamReader(myStream))
                {
                    this.Data = sr.ReadToEnd();
                    if (this.DisplayToConsole)
                    {
                        this.LogTaskMessage(MessageImportance.Normal, this.Data);
                    }
                }
            }
        }
Exemple #42
0
        public string hinetInfo()
        {
            string info = "[Hi-Net] ";
            var    wc   = new System.Net.WebClient();

            wc.Encoding = Encoding.GetEncoding("euc-jp");
            var doc = new HtmlAgilityPack.HtmlDocument();

            try
            {
                doc.Load(wc.OpenRead("http://www.hinet.bosai.go.jp/?LANG=ja"), Encoding.GetEncoding("euc-jp"));
                var node = doc.DocumentNode.SelectNodes("//table[@class='top_rtmap']//td[@class='td3']");
                info += $"{node[1].InnerText.ToString()} {node[0].InnerText.ToString()}({node[2].InnerText.ToString()}, {node[3].InnerText.ToString()}) M{node[5].InnerText.ToString()} {node[4].InnerText.ToString()}";
            }
            catch (Exception e)
            {
                info += $"ERROR: {e.Message}";
            }

            return(info);
        }
Exemple #43
0
        public override List<StopTime> GetStopTimes(string stopid)
        {
            System.Net.WebClient client = new System.Net.WebClient();

            GTFS engine = new GTFS(this.TransitAgency);
            Stop stop = engine.GetStop(stopid);

            DataSet ds = new DataSet();
            ds.ReadXml(client.OpenRead("http://myride.gocitybus.com/widget/Default1.aspx?pt=30&code=" + stop.Code));

            List<StopTime> result = new List<StopTime>();

            if (ds.Tables["Bus"] == null)
            {
                return result;
            }

            foreach (DataRow r in ds.Tables["Bus"].Rows)
            {
                StopTime t = new StopTime();

                t.RouteShortName = r["RouteName"].ToString().Substring(0, r["RouteName"].ToString().IndexOf(" ")).ToUpper().Trim(); if (t.RouteShortName.Length > 3) t.RouteShortName = t.RouteShortName.Substring(0, 3);
                t.RouteLongName = r["RouteName"].ToString().Replace(t.RouteShortName, "").Trim();

                var now = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, this.TransitAgency.FriendlyTimeZone);

                if (r["TimeTillArrival"].ToString() == "DUE")
                    t.ArrivalTime = now.ToString("hh:mm tt");
                else
                    t.ArrivalTime = now.AddMinutes(Convert.ToInt32(r["TimeTillArrival"].ToString().Replace("min", "").Trim())).ToString("hh:mm tt");

                t.DepartureTime = t.ArrivalTime;
                t.Type = "realtime";

                result.Add(t);
            }

            return result;
        }
Exemple #44
0
        public override List<StopTime> GetStopTimes(string stopID)
        {
            System.Net.WebClient client = new System.Net.WebClient();

            DataSet ds = new DataSet();
            ds.ReadXml(client.OpenRead("http://api.bart.gov/api/etd.aspx?cmd=etd&key=" + APIKey + "&orig=" + stopID));

            List<StopTime> result = new List<StopTime>();

            foreach (DataRow r in ds.Tables["etd"].Rows)
            {
                foreach (DataRow s in ds.Tables["estimate"].Rows)
                {
                    if (s["etd_Id"].ToString() == r["etd_Id"].ToString())
                    {
                        StopTime t = new StopTime();

                        t.RouteShortName = r["abbreviation"].ToString();
                        t.RouteLongName = r["destination"].ToString();

                        var now = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, this.TransitAgency.FriendlyTimeZone);

                        if (s["minutes"].ToString() == "Arrived")
                            t.ArrivalTime = now.ToString("hh:mm tt");
                        else
                            t.ArrivalTime = now.AddMinutes(Convert.ToInt32(s["minutes"].ToString().Trim())).ToString("hh:mm tt");

                        t.DepartureTime = t.ArrivalTime;
                        t.Type = "realtime";

                        if ((from x in result where x.RouteShortName == t.RouteShortName select x).Count() < 2)
                            result.Add(t);
                    }
                }
            }

            return result;
        }
        static void Main(string[] args)
        {
            //String url = "http://www.yelp.com/biz/bacchanalia-atlanta";
            //String url = "http://www.zagat.com/r/bacchanalia-atlanta";
            String url = "http://www.urbanspoon.com/r/9/120002/restaurant/Westside/Bacchanalia-Atlanta";

            htmlDoc = new HtmlDocument();
            using (System.Net.WebClient webClient = new System.Net.WebClient())
            {
                using (var stream = webClient.OpenRead(url))
                {
                    htmlDoc.Load(stream);
                }
            }

            if (url.Contains("dine"))
            {
                DineScraper dine = new DineScraper(url, htmlDoc, "dine");
            }
            else if (url.Contains("google"))
            {
                GoogleScraper google = new GoogleScraper(url, htmlDoc, "google");
            }
            else if (url.Contains("urbanspoon"))
            {
                UrbanspoonScraper urbanspoon = new UrbanspoonScraper(url, htmlDoc, "urbanspoon");
            }
            else if (url.Contains("yelp"))
            {
                YelpScraper yelp = new YelpScraper(url, htmlDoc, "yelp");
            }
            else if (url.Contains("zagat"))
            {
                ZagatScraper zagat = new ZagatScraper(url, htmlDoc, "zagat");
            }
        }
Exemple #46
0
 private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
 {
     string sUrlToReadFileFrom = "https://raw.githubusercontent.com/delta360/LetMePlayFFS/master/updateFolder/gameList.txt";
     int iLastIndex = sUrlToReadFileFrom.LastIndexOf('/');
     string sDownloadFileName = sUrlToReadFileFrom.Substring(iLastIndex + 1, (sUrlToReadFileFrom.Length - iLastIndex - 1));
     string sFilePathToWriteFileTo = System.IO.Path.GetDirectoryName(Application.ExecutablePath) + "\\" + sDownloadFileName;
     Uri url = new Uri(sUrlToReadFileFrom);
     System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
     System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse();
     response.Close();
     Int64 iSize = response.ContentLength;
     Int64 iRunningByteTotal = 0;
     using (System.Net.WebClient client = new System.Net.WebClient())
     {
         using (System.IO.Stream streamRemote = client.OpenRead(new Uri(sUrlToReadFileFrom)))
         {
             using (Stream streamLocal = new FileStream(sFilePathToWriteFileTo, FileMode.Create, FileAccess.Write, FileShare.None))
             {
                 int iByteSize = 0;
                 byte[] byteBuffer = new byte[iSize];
                 while ((iByteSize = streamRemote.Read(byteBuffer, 0, byteBuffer.Length)) > 0)
                 {
                     streamLocal.Write(byteBuffer, 0, iByteSize);
                     iRunningByteTotal += iByteSize;
                     double dIndex = (double)(iRunningByteTotal);
                     double dTotal = (double)byteBuffer.Length;
                     double dProgressPercentage = (dIndex / dTotal);
                     int iProgressPercentage = (int)(dProgressPercentage * 100);
                     backgroundWorker1.ReportProgress(iProgressPercentage);
                 }
                 streamLocal.Close();
             }
             streamRemote.Close();
         }
     }
 }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        public virtual void ReadFrom(AppHelperContext context)
        {
            if( context["year"] != null )
            {
                try
                {
                    this.Date = DateTime.Parse(context["year"].ToString());
                }
                catch
                {
                    try
                    {
                        int year = int.Parse(context["year"].ToString());
                        this.Date = new DateTime(year, 1, 1);
                    }
                    catch
                    {

                        this.Date = DateTime.MinValue;
                    }
                }
            }
            this.Genre = (string)context["genre"];
            this.Description = (string)context["summary"];
            this.Title = (string)context["title"];
            this.Country = (string)context["country"];
            this.Length = (string)context["length"];
            this.Rating = (string)context["rating"];
            this.Director = (string)context["director"];
            this.Cast = (string)context["cast"];

            if (context["imageURL"] != null)

            {
                System.Net.WebClient client = new System.Net.WebClient( );
                this.Image = Image.FromStream(client.OpenRead(new Uri((string)context["imageURL"])));
            }
            else
                this.Image = null;
        }
        public IEnumerable<Contract> GetAvailableContracts(APIKey key)
        {
            List<Contract> contracts = new List<Contract>();

            System.Net.WebClient webClient = new System.Net.WebClient();
            webClient.Headers.Add("user-agent", "LogisticiansTools: - Contact Natalie Cruella");
            string URL = string.Format("{0}/{1}/Contracts.xml.aspx?keyID={2}&vCode={3}", _baseEveApi, key.Type, key.KeyID, key.VCode);
            if (key.Type.ToUpper() == "CHAR")
            {
                URL += "&characterID=" + key.CharacterID;
            }
            System.IO.Stream dataStream = webClient.OpenRead(URL);
            string XMLData = new System.IO.StreamReader(dataStream).ReadToEnd();
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(XMLData);
            XmlNodeList nodes = doc.GetElementsByTagName("row");
            foreach (XmlNode node in nodes)
            {
                if (node.Attributes["type"].Value.ToString().ToLower() == "courier" && (node.Attributes["status"].Value.ToString().ToLower() == "outstanding" || node.Attributes["status"].Value.ToString().ToLower() == "inprogress"))
                {
                    Contract newContract = new Contract()
                    {
                        AssigneeID = Convert.ToInt32(node.Attributes["assigneeID"].Value),
                        ContractID = Convert.ToInt32(node.Attributes["contractID"].Value),
                        ContractType = node.Attributes["type"].Value.ToString(),
                        EndStationID = Convert.ToInt32(node.Attributes["endStationID"].Value),

                        Reward = Convert.ToDecimal(node.Attributes["reward"].Value),
                        Collateral = Convert.ToDecimal(node.Attributes["collateral"].Value),

                        Expiration = Convert.ToDateTime(node.Attributes["dateExpired"].Value),
                        IssuerCorpID = Convert.ToInt32(node.Attributes["issuerCorpID"].Value),
                        IssuerID = Convert.ToInt32(node.Attributes["issuerID"].Value),
                        StartStationID = Convert.ToInt32(node.Attributes["startStationID"].Value),
                        Status = node.Attributes["status"].Value.ToString(),
                        Volume = Convert.ToSingle(node.Attributes["volume"].Value)
                    };
                    newContract.StartStation = GetStationByID(newContract.StartStationID);
                    newContract.StartSystem = newContract.StartStation.SolarSystem;

                    newContract.EndStation = GetStationByID(newContract.EndStationID);
                    newContract.EndSystem = newContract.EndStation.SolarSystem;

                    contracts.Add(newContract);
                }
            }
            return contracts;
        }
Exemple #49
0
 private void download(string link, string path, int val)
 {
     int pbstart = parent.PBVal;
     try
     {
         Uri url = new Uri(link);
         System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
         System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse();
         response.Close();
         Int64 iSize = response.ContentLength;
         using (System.Net.WebClient client = new System.Net.WebClient())
         {
             using (System.IO.Stream streamRemote = client.OpenRead(new Uri(link)))
             {
                 using (Stream streamLocal = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None))
                 {
                     int iByteSize = 0;
                     int iRunningByteTotal = 0;
                     byte[] byteBuffer = new byte[8192];
                     while ((iByteSize = streamRemote.Read(byteBuffer, 0, byteBuffer.Length)) > 0)
                     {
                         streamLocal.Write(byteBuffer, 0, iByteSize);
                         iRunningByteTotal += iByteSize;
                         parent.PBVal = pbstart + (int)((double)val * ((double)iRunningByteTotal / (double)iSize));
                     }
                     streamLocal.Close();
                 }
                 streamRemote.Close();
             }
         }
     }
     catch { }
     parent.PBVal = pbstart + val;
 }
        public Dictionary<string, string> GetCharsOrCorpOnAPI(APIKey key)
        {
            Dictionary<string, string> chars = new Dictionary<string, string>();

            System.Net.WebClient webClient = new System.Net.WebClient();
            webClient.Headers.Add("user-agent", "LogisticiansTools: - Contact Natalie Cruella");
            string URL = string.Format("{0}/account/APIKeyInfo.xml.aspx?keyID={1}&vCode={2}", _baseEveApi, key.KeyID, key.VCode);

            System.IO.Stream dataStream = webClient.OpenRead(URL);
            string XMLData = new System.IO.StreamReader(dataStream).ReadToEnd();
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(XMLData);
            XmlNodeList nodes = doc.GetElementsByTagName("row");
            if (key.Type.ToLower() == "corp")
            {
                //chars.Add(nodes[0].Attributes["corporationName"].Value.ToString() + " (Corp)");
                chars.Add(nodes[0].Attributes["corporationName"].Value.ToString() + " (Corp)", nodes[0].Attributes["corporationID"].Value.ToString());
            }
            else if (key.Type.ToLower() == "char")
            {
                foreach (XmlNode nod in nodes)
                {
                    //chars.Add(nod.Attributes["characterName"].Value.ToString() + " (Pilot)");
                    chars.Add(nod.Attributes["characterName"].Value.ToString() + " (Pilot)", nod.Attributes["characterID"].Value.ToString());
                }
            }
            return chars;
        }
        public ActionResult Download(Uri ocr_url, string azure_url, List<string> creators_and_contributors, string date, string electronicsysnum,
        string flickr_original_jpeg, string flickr_url, string fromshelfmark, string height, string idx, string place, string printsysnum,
           string publisher, string scannumber, string sizebracket, string tags, string title, string vol, string width)
        {



            var outputStream = new MemoryStream();
            XDocument doc = new XDocument(new XElement("body",
                                         new XElement("metadata",
                                             new XElement("azure_url", azure_url),
                                             new XElement("date", date),
                                             new XElement("electronicsysnum", creators_and_contributors[0]),
                                             new XElement("electronicsysnum", electronicsysnum),
                                             new XElement("flickr_original_jpeg", flickr_original_jpeg),
                                             new XElement("flickr_url", flickr_url),
                                             new XElement("fromshelfmark", fromshelfmark),
                                             new XElement("height", height),
                                             new XElement("idx", idx),
                                             new XElement("ocrtext", ocr_url.ToString()),
                                             new XElement("place", place),
                                             new XElement("printsysnum", printsysnum),
                                             new XElement("publisher", publisher),
                                             new XElement("scannumber", scannumber),
                                             new XElement("sizebracket", sizebracket),
                                             new XElement("tags", tags),
                                             new XElement("title", title),
                                             new XElement("vol", vol),
                                             new XElement("width", width))));






            MemoryStream xmlStream = new MemoryStream();
            doc.Save(xmlStream);

            xmlStream.Flush();//Adjust this if you want read your data 
            xmlStream.Position = 0;


            using (var zip = new ZipFile())
            {

                System.Net.WebClient wc = new System.Net.WebClient();
                Stream s = wc.OpenRead(ocr_url);

                zip.AddEntry(date + "_" + printsysnum + ".txt", s);
                zip.AddEntry(date + "_" + printsysnum + ".xml", xmlStream);


                zip.Save(outputStream);
            }

            outputStream.Position = 0;
            return File(outputStream, "application/zip", date + "_" + printsysnum + ".zip");

        }
        private string GetProxyTicketFromCAS(string targetService, string _pgt)
        {
            string pt = string.Empty;
            string server = "https://thekey.me/cas/";

            string validateurl = server + "proxy?targetService=" + targetService + "&pgt=" + _pgt.Trim().ToString();

            System.IO.Stream s;

            try
            {
                System.Net.WebClient wc = new System.Net.WebClient();
                s = wc.OpenRead(validateurl);
            }
            catch (Exception e)
            {
                // error
               return pt;
            }

            StreamReader streamReader = new StreamReader(s);

            XmlDocument doc = new XmlDocument();
            doc.Load(streamReader);
            XmlNamespaceManager NamespaceMgr = new XmlNamespaceManager(doc.NameTable);
            NamespaceMgr.AddNamespace("cas", "http://www.yale.edu/tp/cas");

            XmlNode SuccessNode = doc.SelectSingleNode("/cas:serviceResponse/cas:proxySuccess", NamespaceMgr);

            if (!(SuccessNode == null))
            {
                XmlNode ProxyTicketNode = SuccessNode.SelectSingleNode("./cas:proxyTicket", NamespaceMgr);
                if (!(ProxyTicketNode == null))
                    return ProxyTicketNode.InnerText;
            }

            return pt;
        }
Exemple #53
0
        public static BarList DayFromEuronext(string isin, DateTime? startDate, DateTime? endDate)
        {
            string market;
            string urlTemplate =
                @"http://www.euronext.com/tools/datacentre/dataCentreDownloadExcell.jcsv?cha=2593&lan=EN&fileFormat=txt&separator=.&dateFormat=dd/MM/yy" +
                "&isinCode=[symbol]&selectedMep=[market]&indexCompo=&opening=on&high=on&low=on&closing=on&volume=on&dateFrom=[startDay]/[startMonth]/[startYear]&" +
                "dateTo=[endDay]/[endMonth]/[endYear]&typeDownload=2";

            if (!endDate.HasValue) endDate = DateTime.Now;
            if (!startDate.HasValue) startDate = DateTime.Now.AddYears(-5);
            if (isin == null || !Regex.IsMatch(isin, "[A-Za-z0-9]{12}"))
                throw new ArgumentException("Invalid ISIN: " + isin);

            /* ugly hack to get the market number from the isin (not always valid..) */
            CompareInfo myComp = CultureInfo.InvariantCulture.CompareInfo;
            if (myComp.IsPrefix(isin, "BE")) market = "3";
            else if (myComp.IsPrefix(isin, "FR")) market = "1";
            else if (myComp.IsPrefix(isin, "NL")) market = "2";
            else if (myComp.IsPrefix(isin, "PT")) market = "5";
            else market = "1";

            string startMonth = startDate.Value.Month.ToString();
            string startDay = startDate.Value.Day.ToString();
            string startYear = startDate.Value.Year.ToString();

            string endMonth = endDate.Value.Month.ToString();
            string endDay = endDate.Value.Day.ToString();
            string endYear = endDate.Value.Year.ToString();

            urlTemplate = urlTemplate.Replace("[symbol]", isin);
            urlTemplate = urlTemplate.Replace("[market]", market);
            urlTemplate = urlTemplate.Replace("[startMonth]", startMonth);
            urlTemplate = urlTemplate.Replace("[startDay]", startDay);
            urlTemplate = urlTemplate.Replace("[startYear]", startYear);

            urlTemplate = urlTemplate.Replace("[endMonth]", endMonth);
            urlTemplate = urlTemplate.Replace("[endDay]", endDay);
            urlTemplate = urlTemplate.Replace("[endYear]", endYear);

            BarListImpl bl = new BarListImpl(BarInterval.Day, isin);
            System.Net.WebClient wc = new System.Net.WebClient();
            StreamReader res;
            try
            {
                res = new StreamReader(wc.OpenRead(urlTemplate));
                int skipCount = 0;
                string tmp = null;
                do
                {
                    tmp = res.ReadLine();
                    if (skipCount++ < 7)
                        continue;
                    tmp = tmp.Replace(";", ",");
                    Bar b = BarImpl.FromCSV(tmp, isin, (int)BarInterval.Day);
                    foreach (Tick k in BarImpl.ToTick(b))
                        bl.newTick(k);
                } while (tmp != null);
            }
            catch (Exception)
            {
                return bl;
            }

            return bl;
        }
Exemple #54
0
        static List<Tuple<Tuple<string, List<string>>, Dictionary<string, List<string>>>> ParseFinancialData( string urlPath )
        {
            List<Tuple<Tuple<string, List<string>>, Dictionary<string, List<string>>>> Details = new List<Tuple<Tuple<string, List<string>>, Dictionary<string, List<string>>>>( );

            // maybe remove these later
            System.Net.WebClient wc = new System.Net.WebClient( );
            System.IO.MemoryStream ms = new System.IO.MemoryStream( );

            using ( var stream = wc.OpenRead( urlPath ) )
            {
                stream.CopyTo( ms );
                ms.Position = 0;
            }
            HtmlDocument html = new HtmlDocument( );
            html.Load( ms );
            var nodes = html.DocumentNode;
            var tables = nodes.SelectNodes( "//table[contains(@class, 'gf-table rgt')]" );
            foreach ( var table in tables )
            {
                string CurrencyDenomination = string.Empty;
                List<string> PeriodHeaders = new List<string>( );
                Dictionary<string, List<string>> Map = new Dictionary<string, List<string>>( );

                var header = table.ChildNodes.Where( i => i.Name == "thead" ).FirstOrDefault( ).ChildNodes.FirstOrDefault( ).ChildNodes.Where( j => j.Name == "th" );
                foreach ( var detail in header )
                {
                    if ( detail.Attributes.FirstOrDefault( ).Value == "lm lft nwp" )
                    {
                        CurrencyDenomination = detail.InnerText.Replace( "\n", "" );
                    }
                    else
                    {
                        PeriodHeaders.Add( detail.InnerText.Replace( "\n", "" ) );
                    }
                }

                var rows = table.ChildNodes.Where( i => i.Name == "tbody" ).FirstOrDefault( ).ChildNodes.Where( i => i.Name == "tr" );
                foreach ( var row in rows )
                {
                    var td = row.ChildNodes.Where( i => i.Name == "td" );
                    var rowHeader = td.Where( i => i.Attributes.FirstOrDefault( ).Value.Contains( "lft" ) ).FirstOrDefault( ).InnerText.Replace( "&quot;", "\"" ).Replace( "&amp;", "&" ).Replace( "&#39;", "'" ).Replace( "\n", "" );
                    var trs = td.Where( i => i.Attributes.FirstOrDefault( ) != null && i.Attributes.FirstOrDefault( ).Value.Contains( "r" ) );
                    List<string> rowData = new List<string>( );
                    foreach ( var tr in trs )
                    {
                        rowData.Add( tr.InnerText );
                    }
                    if ( !Map.ContainsKey( rowHeader ) )
                        Map.Add( rowHeader, rowData );
                }
                Details.Add( new Tuple<Tuple<string, List<string>>, Dictionary<string, List<string>>>( new Tuple<string, List<string>>( CurrencyDenomination, PeriodHeaders ), Map ) );
            }
            return Details;
        }
        public bool IsAPIValid(APIKey key)
        {
            System.Net.WebClient webClient = new System.Net.WebClient();
            webClient.Headers.Add("user-agent", "LogisticiansTools: - Contact Natalie Cruella");
            string URL = string.Format("{0}/account/APIKeyInfo.xml.aspx?keyID={1}&vCode={2}", _baseEveApi, key.KeyID, key.VCode);

            System.IO.Stream dataStream = webClient.OpenRead(URL);
            string XMLData = new System.IO.StreamReader(dataStream).ReadToEnd();
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(XMLData);
            XmlNode nod = doc.GetElementsByTagName("key")[0];
            int accessMask = Convert.ToInt32(nod.Attributes["accessMask"].Value);

            string apiType = GetAPIType(key);

            if (apiType.ToUpper() == "CHAR")
                return (accessMask & 67108864) == 67108864;
            else if (apiType.ToUpper() == "CORP")
                return (accessMask & 8388608) == 8388608;
            else
                return false;
        }
		/// <summary>
		/// given a bitmap url, saves it on the local machine and returns its size
		/// </summary>
		/// <param name="iconPath"></param>
		/// <param name="width"></param>
		/// <param name="height"></param>
		private Bitmap DownloadIcon(string iconPath, out int width, out int height)
		{
			//if the icon does not exist on the local machine, get it from RSS site
			string iconFileName = System.IO.Path.Combine(m_iconFolder, System.IO.Path.GetFileNameWithoutExtension(iconPath) + ".bmp");
			width = 0;
			height = 0;
			Bitmap bitmap = null;
			if(!File.Exists(iconFileName))
			{
				using (System.Net.WebClient webClient = new System.Net.WebClient())
				{
					//open a readable stream to download the bitmap
          using (System.IO.Stream stream = webClient.OpenRead(iconPath))
					{
						bitmap = new Bitmap(stream, true);

						//save the image as a bitmap in the icons folder
						bitmap.Save(iconFileName, ImageFormat.Bmp);

            //get the bitmap's dimensions
						width = bitmap.Width;
						height = bitmap.Height;
					}
				}
			}
			else
			{
				//get the bitmap's dimensions
				{
					bitmap = new Bitmap(iconFileName);
					width = bitmap.Width;
					height = bitmap.Height;
				}
			}

			return bitmap;
		}
Exemple #57
0
 public bool Read(string fname)
 {
     byte[] data = null;
     if (fname [fname.Length - 1] == ' ') {
         fname = fname.Substring (0, fname.Length - 1);
     }
     fname = fname.Trim('\'', '"');
     if (fname.Substring (0, 7) == "file://") {
         fname = System.Net.WebUtility.UrlDecode(fname.Substring (7));
     }
     if (fname.Substring (0, 7) == "http://") {
         System.Net.WebClient client = new System.Net.WebClient();
         Stream stream = client.OpenRead(fname);
         System.Threading.Thread.Sleep (2000); //Yes. Bad hack...
         data = ReadFully (stream);
     }
     else{
         data = File.ReadAllBytes (fname);
     }
     //Don't bother with exception passing, because that's silly... Right?
     if (data.Length < 14) {
         MyLastError = "Invalid Midi file (Too small)";
         return false;
     }
     if (!MatchBytes (ref data, 0, "MThd")) {
         MyLastError = "Invalid Midi file (no MThd at start)";
         return false;
     }
     int size = (data [4] << 24) + (data [5] << 16) + (data [6] << 8) + (data [7]);
     if (size != 6) {
         MyLastError = "Unsupported Midi file (Header is too long) " + Convert.ToString(size);
         return false;
     }
     SubFormat = (data [8] << 8) + data [9];
     Tracks = (data [10] << 8) + data [11];
     Speed = (data [12] << 8) + data [13];
     int offset = 14;
     int tracksFound = 0;
     while (true) {
         int result = ReadTrack(ref data, offset);
         //A status of 0 is end of file, -1 is an error, positive means continue reading.
         if (result < 0) {
             return false;
         }
         if (result == 0) {
             break;
         }
         offset = result;
         tracksFound++;
     }
     if (Tracks > tracksFound) {
         MyLastError = "Invalid Midi file (More tracks were declared than do exist)";
         return false;
     }
     valids = new bool[tracksFound];
     for (int i = 0; i < tracksFound; ++i) {
         valids [i] = true;
     }
     return true;
 }
 private Station GetConquerableStationByID(int stationID)
 {
     System.Net.WebClient webClient = new System.Net.WebClient();
     webClient.Headers.Add("user-agent", "LogisticiansTools: - Contact Natalie Cruella");
     string URL = string.Format("{0}/eve/ConquerableStationList.xml.aspx", _baseEveApi);
     System.IO.Stream dataStream = webClient.OpenRead(URL);
     string XMLData = new System.IO.StreamReader(dataStream).ReadToEnd();
     XmlDocument doc = new XmlDocument();
     doc.LoadXml(XMLData);
     XmlNodeList nodes = doc.GetElementsByTagName("row");
     Station station = new Station();
     foreach (XmlNode node in nodes)
     {
         if (Convert.ToInt32(node.Attributes["stationID"].Value) == stationID)
         {
             station = new Station()
             {
                 StationID = stationID,
                 SolarSystemID = Convert.ToInt32(node.Attributes["solarSystemID"].Value),
                 StationName = node.Attributes["stationName"].Value.ToString()
             };
             _connectionObject.Close();
             station.SolarSystem = GetSolarSystemByID(station.SolarSystemID);
             return station;
         }
     }
     return station;
 }
        /// <summary>
        /// ����HtmlԴ�ļ�
        /// </summary>
        /// <param name="Url">�����ַ</param>
        /// <returns></returns>
        private string DownHtmlSource(string Url)
        {
            string strHtmlContent = string.Empty;

            try
            {
               //System.Net.WebClient wc = new System.Net.WebClient();

               // strHtmlContent=wc.DownloadString(Url);

                //string PageUrl = UrlText.Text;
                System.Net.WebClient wc = new System.Net.WebClient();
                wc.Credentials = System.Net.CredentialCache.DefaultCredentials;
                Byte[] pageData = wc.DownloadData(Url);
                strHtmlContent = System.Text.Encoding.UTF8.GetString(pageData);

                Stream resStream = wc.OpenRead(Url);
                StreamReader sr = new StreamReader(resStream, System.Text.Encoding.UTF8);
                strHtmlContent = sr.ReadToEnd();
                resStream.Close();
            }
            catch
            {
            }

            return strHtmlContent;
        }
Exemple #60
0
 private static StreamReader ReadHttp(Uri uri)
 {
     var request = new System.Net.WebClient();
     return new StreamReader(request.OpenRead(uri));
 }