internal WebResponse(System.Net.WebResponse webResponse)
        {
            if (webResponse == null)
                throw new ArgumentNullException("webResponse");

            _webResponse = webResponse;
        }
Exemplo n.º 2
0
        public ActionResult CreateByFiles(Album album, IEnumerable <HttpPostedFileBase> files)
        {
            album.TrackCount = files.Count();
            XOUNDContext ctx = new XOUNDContext();

            Bitmap bmp = new Bitmap(1, 1);

            System.Net.WebRequest request =
                System.Net.WebRequest.Create(album.ArtworkImageURL);
            System.Net.WebResponse response       = request.GetResponse();
            System.IO.Stream       responseStream = response.GetResponseStream();
            Bitmap orig = new Bitmap(responseStream);

            using (Graphics g = Graphics.FromImage(bmp))
            {
                g.InterpolationMode = InterpolationMode.HighQualityBicubic;
                g.DrawImage(orig, new Rectangle(0, 0, 1, 1));
            }
            Color  pixel = bmp.GetPixel(0, 0);
            string avg   = System.Drawing.ColorTranslator.ToHtml(pixel);

            album.ArtworkDominantColor = avg;
            //Color backgroundColor = (Color)value;

            var blackContrast = LuminosityContrast(Color.Black, pixel);
            var whiteContrast = LuminosityContrast(Color.White, pixel);

            album.ArtworkContrastColor = blackContrast >= whiteContrast?ColorTranslator.ToHtml(Color.Black) : ColorTranslator.ToHtml(Color.White);

            album.InsertDate = DateTime.Now;
            album.Active     = true;

            ctx.Albums.Add(album);
            ctx.SaveChanges();
            int ctr = 1;

            foreach (var file in files)
            {
                Track tr = new Track()
                {
                    Title     = file.FileName.Replace(".mp3", ""),
                    AudioFile = file,
                    TrackNo   = ctr,
                    AlbumID   = album.ID
                };
                SaveTrack(tr, ctx);
                ctr++;
            }

            return(View());
        }
Exemplo n.º 3
0
        private GMap.NET.PointLatLng GetCoordinates(string city, string street, string number)
        {
            GMap.NET.PointLatLng coords = new PointLatLng();
            string address = city + ", " + street + " " + number;
            string url     = string.Format(
                "http://maps.googleapis.com/maps/api/geocode/xml?address={0}&sensor=true_or_false&language=ru",
                Uri.EscapeDataString(address));

            //Выполняем запрос к универсальному коду ресурса (URI).
            System.Net.HttpWebRequest request =
                (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);

            //Получаем ответ от интернет-ресурса.
            System.Net.WebResponse response =
                request.GetResponse();

            //Экземпляр класса System.IO.Stream
            //для чтения данных из интернет-ресурса.
            System.IO.Stream dataStream =
                response.GetResponseStream();

            //Инициализируем новый экземпляр класса
            //System.IO.StreamReader для указанного потока.
            System.IO.StreamReader sreader =
                new System.IO.StreamReader(dataStream);

            //Считывает поток от текущего положения до конца.
            string responsereader = sreader.ReadToEnd();

            //Закрываем поток ответа.
            response.Close();

            System.Xml.XmlDocument xmldoc =
                new System.Xml.XmlDocument();

            xmldoc.LoadXml(responsereader);
            if (xmldoc.GetElementsByTagName("status")[0].ChildNodes[0].InnerText == "OK")
            {
                System.Xml.XmlNodeList nodes =
                    xmldoc.SelectNodes("//location");
                //Получаем широту и долготу.
                foreach (System.Xml.XmlNode node in nodes)
                {
                    coords.Lat =
                        System.Xml.XmlConvert.ToDouble(node.SelectSingleNode("lat").InnerText.ToString());
                    coords.Lng =
                        System.Xml.XmlConvert.ToDouble(node.SelectSingleNode("lng").InnerText.ToString());
                }
            }
            return(coords);
        }
Exemplo n.º 4
0
        private String[,] getRssData(String channel)
        {
            System.Net.WebRequest  _myRequest  = System.Net.WebRequest.Create(channel);
            System.Net.WebResponse _myResponse = _myRequest.GetResponse();

            System.IO.Stream       rssStream = _myResponse.GetResponseStream();
            System.Xml.XmlDocument rssDoc    = new System.Xml.XmlDocument();

            rssDoc.Load(rssStream);

            System.Xml.XmlNodeList rssItems = rssDoc.SelectNodes("rss/channel/item");

            String[,] tempRssData = new String[100, 3];

            for (int i = 0; i < rssItems.Count; i++)
            {
                System.Xml.XmlNode rssNode;

                rssNode = rssItems.Item(i).SelectSingleNode("title");
                if (rssNode != null)
                {
                    tempRssData[i, 0] = rssNode.InnerText;
                }
                else
                {
                    tempRssData[i, 0] = "";
                }


                rssNode = rssItems.Item(i).SelectSingleNode("description");
                if (rssNode != null)
                {
                    tempRssData[i, 1] = rssNode.InnerText;
                }
                else
                {
                    tempRssData[i, 1] = "";
                }

                rssNode = rssItems.Item(i).SelectSingleNode("link");
                if (rssNode != null)
                {
                    tempRssData[i, 2] = rssNode.InnerText;
                }
                else
                {
                    tempRssData[i, 2] = "";
                }
            }
            return(tempRssData);
        }
Exemplo n.º 5
0
        private void fillDataGrid()
        {
            this.Enabled = false;

            LoadingWindow loadingWindow = new LoadingWindow();

            loadingWindow.Show();

            Application.DoEvents();

            DatabaseControl.ConnectDB();

            string           sql     = "SELECT * FROM recipes ORDER BY title ASC";
            SQLiteCommand    command = new SQLiteCommand(sql, DatabaseControl.m_dbConnection);
            SQLiteDataReader reader  = command.ExecuteReader();

            dataGridView1.Rows.Clear();
            dataGridView1.Refresh();
            while (reader.Read())
            {
                dataGridView1.Rows.Add();
                dataGridView1.Rows[dataGridView1.Rows.Count - 1].Cells["id"].Value    = reader["id"];
                dataGridView1.Rows[dataGridView1.Rows.Count - 1].Cells["Title"].Value = reader["title"];

                Bitmap img;

                try
                {
                    System.Net.WebRequest request = System.Net.WebRequest.Create(reader["img"].ToString());
                    request.Timeout = 500;
                    System.Net.WebResponse response       = request.GetResponse();
                    System.IO.Stream       responseStream = response.GetResponseStream();
                    img = new Bitmap(responseStream);
                }
                catch (Exception ex)
                {
                    img = null;
                }

                dataGridView1.Rows[dataGridView1.Rows.Count - 1].Cells["Image"].Value            = img;
                dataGridView1.Rows[dataGridView1.Rows.Count - 1].Cells["Time"].Value             = reader["time"];
                dataGridView1.Rows[dataGridView1.Rows.Count - 1].Cells["Difficulty_level"].Value = reader["difficulty_level"];
            }

            ((DataGridViewImageColumn)dataGridView1.Columns[2]).ImageLayout = DataGridViewImageCellLayout.Stretch;

            DatabaseControl.DisonnectDB();

            this.Enabled = true;
            loadingWindow.Close();
        }
 public static bool DownloadBitmap(string url, ref Bitmap b)
 {
     System.Net.WebRequest request = System.Net.WebRequest.Create(url);
     try {
         System.Net.WebResponse response       = request.GetResponse();
         System.IO.Stream       responseStream = response.GetResponseStream();
         b = new Bitmap(responseStream);
         responseStream.Close();
         response.Close();
         return(true);
     } catch (Exception) {
         return(false);
     }
 }
Exemplo n.º 7
0
        public void ProcessRequest(HttpContext context)
        {
            //pass on request to tile server
            string targetUrl = context.Request.Params["imagesrc"];

            System.Net.WebRequest  myRequest  = System.Net.WebRequest.Create(targetUrl);
            System.Net.WebResponse myResponse = myRequest.GetResponse();

            Bitmap myImage = new Bitmap(Image.FromStream(myResponse.GetResponseStream()));

            //context.Response.Headers.Add("Access-Control-Allow-Origin", "*");
            context.Response.ContentType = "image/jpeg";
            WritePngToStream(myImage, context.Response.OutputStream);
        }
Exemplo n.º 8
0
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            ////////////////////////////

            if (!IsRunAsAdministrator())
            {
                // It is not possible to launch a ClickOnce app as administrator directly, so instead we launch the
                // app as administrator in a new process.
                var processInfo = new ProcessStartInfo(Assembly.GetExecutingAssembly().CodeBase);

                // The following properties run the new process as administrator
                processInfo.UseShellExecute = true;
                processInfo.Verb            = "runas";

                // Start the new process
                try
                {
                    Process.Start(processInfo);
                }
                catch (Exception)
                {
                    // The user did not allow the application to run as administrator
                    MessageBox.Show("Sorry, this application must be run as Administrator.");
                }

                // Shut down the current process
                Application.Current.Shutdown();
            }
            else
            {
                // We are running as administrator

                // Do normal startup stuff.

                try
                {
                    System.Net.WebRequest  myRequest  = System.Net.WebRequest.Create("http://www.Google.co.in");
                    System.Net.WebResponse myResponse = myRequest.GetResponse();
                    Uri a = new System.Uri("http://shubhalabha.in/eng/ads/www/delivery/afr.php?zoneid=22&amp;target=_blank&amp;cb=INSERT_RANDOM_NUMBER_HERE");
                    //  Uri a = new System.Uri(" http://shubhalabha.in/products-2/");

                    advertisement.Source = a;
                    //  wad4.Source = a4;
                }
                catch
                {
                    advertisement.Visibility = Visibility.Hidden;
                }
            }
        }
        private System.IO.MemoryStream PerformHttpsRequest(string url, int maxRetries, int msDelay)
        {
            System.Net.HttpWebRequest req;
            System.IO.MemoryStream    memstr = null;

            System.Net.SecurityProtocolType proto = System.Net.SecurityProtocolType.Ssl3 | System.Net.SecurityProtocolType.Tls12 |
                                                    System.Net.SecurityProtocolType.Tls11 | System.Net.SecurityProtocolType.Tls;
            System.Net.ServicePointManager.SecurityProtocol = proto;

            int tryCount = 0;

            while (true)
            {
                tryCount++;

                try
                {
                    req    = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
                    memstr = new System.IO.MemoryStream();

                    req.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36";

                    req.Timeout                      = 10000;
                    req.AllowAutoRedirect            = true;
                    req.MaximumAutomaticRedirections = 1;

                    using (System.Net.WebResponse res = req.GetResponse())
                    {
                        System.IO.Stream rs     = res.GetResponseStream();
                        long             length = res.ContentLength;

                        rs.CopyTo(memstr);
                        memstr.Seek(0, System.IO.SeekOrigin.Begin);
                    }

                    break;
                }
                catch (Exception e)
                {
                    if (tryCount >= maxRetries)
                    {
                        throw e;
                    }
                }

                System.Threading.Thread.Sleep(msDelay);
            }

            return(memstr);
        }
        private void unirest_test()
        {
            //HttpResponse<String> response = Unirest.post("https://textanalysis-text-summarization.p.mashape.com/text-summarizer-text")
            // .header("X-Mashape-Key", "pl80tf1WWmmshuVLZUCcmLqOM1Gkp1m52x5jsnKzqoMSgldcOF")
            //    .header("Content-Type", "application/x-www-form-urlencoded")
            //  //  .header("Accept", "application/json")
            //    .field("sentnum", "5")
            //    .field("text", "Automatic summarization is the process of reducing a text document with a computer program in order to create a summary that retains the most important points of the original document. As the problem of information overload has grown, and as the quantity of data has increased, so has interest in automatic summarization. Technologies that can make a coherent summary take into account variables such as length, writing style and syntax. An example of the use of summarization technology is search engines such as Google. Document summarization is another.")
            //    .asJson<String>();
            //System.Threading.Tasks.Task<HttpResponse<String>> response = Unirest.post("https://textanalysis-text-summarization.p.mashape.com/text-summarizer-text")
            //.header("X-Mashape-Key", "<required>")
            //.header("Content-Type", "application/json")
            //.header("Accept", "application/json")
            //.body("{\"url\":\"http://en.wikipedia.org/wiki/Automatic_summarization\",\"text\":\"Automatic summarization is the process of reducing a text document with a computer program in order to create a summary that retains the most important points of the original document. As the problem of information overload has grown, and as the quantity of data has increased, so has interest in automatic summarization. Technologies that can make a coherent summary take into account variables such as length, writing style and syntax. An example of the use of summarization technology is search engines such as Google. Document summarization is another.\",\"sentnum\":8}")
            //.asJson<String>();
            //HttpResponse<String> response = Unirest.post("https://textanalysis-text-summarization.p.mashape.com/text-summarizer-text")
            //.header("X-Mashape-Key", "pl80tf1WWmmshuVLZUCcmLqOM1Gkp1m52x5jsnKzqoMSgldcOF")
            //.header("Content-Type", "application/x-www-form-urlencoded")
            //.header("Accept", "application/json")
            //.field("sentnum", "5")
            //.field("text", "Automatic summarization is the process of reducing a text document with a computer program in order to create a summary that retains the most important points of the original document. As the problem of information overload has grown, and as the quantity of data has increased, so has interest in automatic summarization. Technologies that can make a coherent summary take into account variables such as length, writing style and syntax. An example of the use of summarization technology is search engines such as Google. Document summarization is another.")
            //.asJson<String>();
            const string URL  = "https://textanalysis-text-summarization.p.mashape.com/text-summarizer-text";
            const string DATA = @"sentnum=5&text=Automatic summarization is the process of reducing a text document with a computer program in order to create a summary that retains the most important points of the original document. As the problem of information overload has grown, and as the quantity of data has increased, so has interest in automatic summarization. Technologies that can make a coherent summary take into account variables such as length, writing style and syntax. An example of the use of summarization technology is search engines such as Google. Document summarization is another.";

            System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(URL);
            request.Method                   = "POST";
            request.ContentType              = "application/x-www-form-urlencoded";
            request.ContentLength            = DATA.Length;
            request.Headers["X-Mashape-Key"] = "pl80tf1WWmmshuVLZUCcmLqOM1Gkp1m52x5jsnKzqoMSgldcOF";
            StreamWriter requestWriter = new StreamWriter(request.GetRequestStream(), System.Text.Encoding.ASCII);

            requestWriter.Write(DATA);
            requestWriter.Close();

            try
            {
                System.Net.WebResponse webResponse = request.GetResponse();
                Stream       webStream             = webResponse.GetResponseStream();
                StreamReader responseReader        = new StreamReader(webStream);
                string       response = responseReader.ReadToEnd();
                Console.Out.WriteLine(response);
                responseReader.Close();
            }
            catch (Exception e)
            {
                Console.Out.WriteLine("-----------------");
                Console.Out.WriteLine(e.Message);
            }
        }
Exemplo n.º 11
0
        /// <summary>
        /// 检查小说ID是否正确
        /// </summary>
        /// <param name="id">小说ID</param>
        /// <returns></returns>
        private bool CheckBookID(string id)
        {
            if (string.IsNullOrEmpty(id))
            {
                MessageBox.Show("ID不能为空!");
                return(false);
            }

            var web      = new HtmlAgilityPack.HtmlWeb();
            var doc_book = web.Load($"{_strRootUrl}/book/{id}/");

            HtmlAgilityPack.HtmlNode           node_book_name       = doc_book.DocumentNode.SelectSingleNode("//div[@id='info']/h1");
            HtmlAgilityPack.HtmlNode           node_book_cover      = doc_book.DocumentNode.SelectSingleNode("//div[@id='fmimg']/img");
            HtmlAgilityPack.HtmlNodeCollection node_book_properties = doc_book.DocumentNode.SelectNodes("//div[@id='info']/p");
            if (node_book_name == null)
            {
                MessageBox.Show($"找不到ID:{id}!");
                return(false);
            }
            if (node_book_cover != null)
            {
                var url = node_book_cover.Attributes["src"].Value;
                System.Net.WebRequest  request        = System.Net.WebRequest.Create(url);
                System.Net.WebResponse response       = request.GetResponse();
                System.IO.Stream       responseStream = response.GetResponseStream();
                Bitmap bmp = new Bitmap(responseStream);
                if (pictureBox1.Image != null)
                {
                    pictureBox1.Image.Dispose();
                }
                pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
                pictureBox1.Image    = bmp;
            }
            if (node_book_properties != null && node_book_properties.Count > 0)
            {
                textBox3.Text = "";
                for (int i = 0; i < node_book_properties.Count; i++)
                {
                    string property = node_book_properties[i].InnerText;
                    if (property.Contains("&nbsp;"))
                    {
                        property = property.Replace("&nbsp;", " ");
                    }
                    property += "\r\n";
                    textBox3.AppendText(property);
                }
            }

            return(true);
        }
Exemplo n.º 12
0
        private string HttpGet(Uri URI)
        {
            System.Net.WebRequest weatherRequest = System.Net.WebRequest.Create(URI);

            //weatherRequest.Proxy = new System.Net.WebProxy(ProxyString, )

            // weatherRequest.Timeout = 9;

            System.Net.WebResponse weatherResponse = weatherRequest.GetResponse();

            StreamReader reader = new StreamReader(weatherResponse.GetResponseStream());

            return(reader.ReadToEnd().Trim());
        }
Exemplo n.º 13
0
        public static void ImportSJC(string url)
        {
            System.Net.WebRequest  webReq   = System.Net.WebRequest.Create(url);
            System.Net.WebResponse webRes   = webReq.GetResponse();
            System.IO.Stream       mystream = webRes.GetResponseStream();
            if (mystream == null)
            {
                return;
            }

            HtmlAgilityPack.HtmlDocument myHtmlDoc = new HtmlAgilityPack.HtmlDocument();
            myHtmlDoc.Load(mystream);

            List <String> row = new List <string>();

            try
            {
                //string xpathGoldTable = "//*[@id='main_container']/tr[1]/td[1]/div[3]/div[2]/table/";
                //string xpathGoldTable = "//*[@id='main_container']/tr[1]/td[1]/div[1]/div[2]/table/";
                //string xpathGoldTable = "//*[@id='price']";
                //HtmlNodeCollection tdNodeCollection = myHtmlDoc
                //                     .DocumentNode
                //                     .SelectNodes("//div[@id = 'price']");


                //foreach (HtmlNode tdNode in tdNodeCollection)
                //{
                //    Console.WriteLine(tdNode.InnerText);
                //}

                //var askNode = myHtmlDoc.DocumentNode.SelectSingleNode(xpathGoldTable).ChildNodes[2];
                //string xpathGoldTable = "//*[@class='right_box']";
                string xpathGoldTable = "*[@id='price']";
                var    askNode        = myHtmlDoc.DocumentNode.SelectSingleNode(xpathGoldTable).SelectSingleNode("//table[2]");
                //code
                row.Add("SJC");
                //last
                //var askNode = myHtmlDoc.DocumentNode.SelectSingleNode(xpathGoldTable + "tr[1]/td[3]");
                //string xpathGoldTable

                //if (askNode != null)
                //    row.Add(askNode.InnerText.Trim());
            }
            catch (System.Exception ex)
            {
                return;
            }

            //return Convert2ForexData(row);
        }
Exemplo n.º 14
0
        /// <summary>
        ///     Подключение структуры из URL
        /// </summary>
        /// <param name="url">Ссылка</param>
        /// <returns>Структура</returns>
        public static T LoadURL(string url)
        {
            System.Xml.Serialization.XmlSerializer xs = new System.Xml.Serialization.XmlSerializer(typeof(T));
            System.Net.WebRequest wr = System.Net.HttpWebRequest.Create(url);
            wr.Method  = "GET";
            wr.Timeout = 30000;
            System.Net.WebResponse rp = wr.GetResponse();
            System.IO.Stream       ss = rp.GetResponseStream();
            T c = (T)xs.Deserialize(ss);

            ss.Close();
            rp.Close();
            return(c);
        }
Exemplo n.º 15
0
        private Image LoadImage(string url)
        {
            System.Net.WebRequest request =
                System.Net.WebRequest.Create(url);

            System.Net.WebResponse response       = request.GetResponse();
            System.IO.Stream       responseStream =
                response.GetResponseStream();

            Bitmap bmp = new Bitmap(responseStream);

            responseStream.Dispose();
            return(bmp);
        }
Exemplo n.º 16
0
        private void button2_Click(object sender, EventArgs e)
        {
            buttonAddBook.Enabled = false;
            button3.Enabled       = true;
            button2.Enabled       = true;

            DataGridViewRow row            = dataGridView1.Rows[dataGridView1.CurrentCell.RowIndex];
            string          SelectedPIDsrt = row.Cells[0].Value.ToString();
            int             SelectedPID    = Int32.Parse(SelectedPIDsrt);

            PublicSelectedPID = SelectedPID;

            Com.Product SelectedProduct = AllBookProducts.Where(W => W.PID == SelectedPID).SingleOrDefault();

            richTextBox1.Text = SelectedProduct.Description;
            textBoxName.Text  = SelectedProduct.Name;
            textBox13.Text    = SelectedProduct.Price.ToString();
            textBox14.Text    = SelectedProduct.Discount.ToString();
            int ImgCount = Int32.Parse(SelectedProduct.Img);

            checkBox2.Checked = SelectedProduct.Available;
            var     serializer = new JavaScriptSerializer();
            SpecObj spec       = serializer.Deserialize <SpecObj>(SelectedProduct.specifications);

            textBox1.Text  = spec.Nevisande;
            textBox3.Text  = spec.GerdAavari;
            textBox2.Text  = spec.Nasher;
            textBox5.Text  = spec.Mozoo;
            textBox10.Text = spec.Vazn;
            textBox4.Text  = spec.NobateChap;
            textBox6.Text  = spec.SaleChap;
            textBox7.Text  = spec.TedadeSafhe;
            textBox8.Text  = spec.Ghat;
            textBox9.Text  = spec.Shabok;
            textBox11.Text = spec.MonasebBaraye;
            for (int i = 0; i < ImgCount; i++)
            {
                try
                {
                    System.Net.WebRequest  request  = System.Net.WebRequest.Create("https://www.hasma.ir/FitnessResource/Product/" + SelectedProduct.PID.ToString() + "/" + ImgCount + ".jpg");
                    System.Net.WebResponse response = request.GetResponse();
                    Stream responseStream           = response.GetResponseStream();
                    publicBitmapBookSelected = new Bitmap(responseStream);
                    imageList1.Images.Add(publicBitmapBookSelected);
                }
                catch
                {
                }
            }
        }
Exemplo n.º 17
0
        /// <summary>
        /// Realiza la petición utilizando el método POST y devuelve la respuesta del servidor
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        /// <author>Findemor http://findemor.porExpertos.es</author>
        /// <history>Creado 17/02/2012</history>
        public static string GetResponse_POST(string url, Dictionary <string, string> parameters, string contentType, string user, string pass)
        {
            try
            {
                //Concatenamos los parametros, OJO: NO se añade el caracter "?"
                string parametrosConcatenados = ConcatParams(parameters);

                System.Net.WebRequest wr = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
                wr.Method = "POST";

                wr.ContentType = contentType;//"application/x-www-form-urlencoded";

                System.IO.Stream newStream;
                //Codificación del mensaje
                System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
                byte[] byte1 = encoding.GetBytes(parametrosConcatenados);
                wr.ContentLength = byte1.Length;
                wr.Headers.Add("Pxp-User", user);
                wr.Headers.Add("Php-Auth-User", user);
                wr.Headers.Add("Php-Auth-Pw", pass);
                //Envio de parametros
                newStream = wr.GetRequestStream();
                newStream.Write(byte1, 0, byte1.Length);

                // Obtiene la respuesta
                System.Net.WebResponse response = wr.GetResponse();
                // Stream con el contenido recibido del servidor
                newStream = response.GetResponseStream();
                System.IO.StreamReader reader = new System.IO.StreamReader(newStream);
                // Leemos el contenido
                string responseFromServer = reader.ReadToEnd();

                // Cerramos los streams
                reader.Close();
                newStream.Close();
                response.Close();
                return(responseFromServer);
            }
            catch (Exception ex)
            {
                if (ex.HResult == 404)
                {
                    throw new Exception("Not found remote service " + url);
                }
                else
                {
                    throw ex;
                }
            }
        }
Exemplo n.º 18
0
        // GET api/values
        //public IEnumerable<master_record> Get()
        public IEnumerable <mmria.common.model.census.Census_Variable> Get
        (
            string state,
            string county,
            string tract
        )
        {
            string request_string = string.Format("http://api.census.gov/data/2014/acs5?get=B27010_001E,B15001_001E,B17020_001E&in=state:{0}+county:{1}&for=tract:{2}&key={3}", state, county, tract, census_api_key);

            //System.Net.ServicePointManager.Expect100Continue = true;
            //System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Ssl3;
            System.Net.WebRequest request = System.Net.WebRequest.Create(new Uri(request_string));
            request.ContentType = "application/json; charset=utf-8";
            System.Net.WebResponse response = request.GetResponse();

            System.IO.Stream dataStream = response.GetResponseStream();
            // Open the stream using a StreamReader for easy access.
            System.IO.StreamReader reader = new System.IO.StreamReader(dataStream);
            // Read the content.
            string responseFromServer         = reader.ReadToEnd();
            List <List <string> > json_result = Newtonsoft.Json.JsonConvert.DeserializeObject <List <List <string> > >(responseFromServer);

            mmria.common.model.census.Census_Variable[] result = null;

            if (json_result.Count > 1)
            {
                result = new mmria.common.model.census.Census_Variable[json_result.Count - 1];

                for (var i = 1; i < json_result.Count; i++)
                {
                    mmria.common.model.census.Census_Variable item = new mmria.common.model.census.Census_Variable();
                    item.B27010_001E = json_result[i][0];
                    item.B15001_001E = json_result[i][1];
                    item.B17020_001E = json_result[i][2];
                    item.state       = json_result[i][3];
                    item.county      = json_result[i][4];
                    item.tract       = json_result[i][5];

                    result[i - 1] = item;
                }
            }


            /*
             * [["B27010_001E","B15001_001E","B17020_001E","state","county","tract"],
             * ["6254","6143","2655","06","037","224700"]]*/


            return(result);
        }
Exemplo n.º 19
0
 //URL 是否能连接
 /// <summary>
 /// 判断网络文件是否存在 1.5秒得到出结果 如这样的格式  http://191.168.1.105:8000/CPW/wmgjUpdate.7
 /// </summary>
 /// <param name="URL"></param>
 /// <returns></returns>
 public static bool UrlIsExists(string URL)
 {
     try
     {
         System.Net.WebRequest webRequest1 = System.Net.WebRequest.Create(URL);
         webRequest1.Timeout = 2500;
         System.Net.WebResponse webResponse1 = webRequest1.GetResponse();
         return(webResponse1 == null ? false : true);
     }
     catch
     {
         return(false);
     }
 }
Exemplo n.º 20
0
 /// <summary>
 /// Gets the response string from the specified request.
 /// </summary>
 /// <param name="request">The request to get the response string from.</param>
 /// <returns>The response string from the specified request.</returns>
 public static string GetResponseString(this System.Net.WebRequest request)
 {
     System.Net.WebResponse response = null;
     try
     {
         response = request.GetResponse();
     }
     catch (System.Net.WebException webException)
     {
         response = webException.Response;
         throw;
     }
     return(GetResponseString(response));
 }
        static StackObject *Close_1(ILIntepreter __intp, StackObject *__esp, IList <object> __mStack, CLRMethod __method, bool isNewObj)
        {
            ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
            StackObject *ptr_of_this_method;
            StackObject *__ret = ILIntepreter.Minus(__esp, 1);

            ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
            System.Net.WebResponse instance_of_this_method = (System.Net.WebResponse) typeof(System.Net.WebResponse).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
            __intp.Free(ptr_of_this_method);

            instance_of_this_method.Close();

            return(__ret);
        }
Exemplo n.º 22
0
        public async System.Threading.Tasks.Task <System.Dynamic.ExpandoObject> Get()
        {
            System.Console.WriteLine("Recieved message.");
            string result = null;

            System.Dynamic.ExpandoObject json_result = null;
            try
            {
                //"2016-06-12T13:49:24.759Z"
                string request_string = this.get_couch_db_url() + "/metadata/2016-06-12T13:49:24.759Z";

                System.Net.WebRequest request = System.Net.WebRequest.Create(new Uri(request_string));

                request.PreAuthenticate = false;


                if (this.Request.Headers.Contains("Cookie") && this.Request.Headers.GetValues("Cookie").Count() > 0)
                {
                    string[] cookie_set = this.Request.Headers.GetValues("Cookie").First().Split(';');
                    for (int i = 0; i < cookie_set.Length; i++)
                    {
                        string[] auth_session_token = cookie_set[i].Split('=');
                        if (auth_session_token[0].Trim() == "AuthSession" && auth_session_token[1] != "null")
                        {
                            request.Headers.Add("Cookie", "AuthSession=" + auth_session_token[1]);
                            request.Headers.Add("X-CouchDB-WWW-Authenticate", auth_session_token[1]);
                            break;
                        }
                    }
                }


                System.Net.WebResponse response = await request.GetResponseAsync();

                //System.Net.WebResponse response = request.GetResponse() as System.Net.WebResponse;
                System.IO.Stream       dataStream = response.GetResponseStream();
                System.IO.StreamReader reader     = new System.IO.StreamReader(dataStream);
                result = reader.ReadToEnd();

                json_result = Newtonsoft.Json.JsonConvert.DeserializeObject <System.Dynamic.ExpandoObject>(result, new  Newtonsoft.Json.Converters.ExpandoObjectConverter());
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }


            //return result;
            return(json_result);
        }
Exemplo n.º 23
0
        public static IEnumerable GetXmlFromService(string restEndpoint)
        {
            System.Net.WebRequest req = System.Net.WebRequest.Create(restEndpoint);
            req.Timeout = 300000;
            System.Net.WebResponse resp = req.GetResponse();
            System.IO.StreamReader sr   = new System.IO.StreamReader(resp.GetResponseStream());

            XmlDocument xmlDocument = new XmlDocument();

            xmlDocument.LoadXml(sr.ReadToEnd());
            XmlNode node = xmlDocument;

            return(node);
        }
Exemplo n.º 24
0
        public static Image RequestImage(string link)
        {
            System.Net.HttpWebRequest webRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(link);
            webRequest.AllowWriteStreamBuffering = true;
            webRequest.Timeout = 30000;

            System.Net.WebResponse webResponse = webRequest.GetResponse();

            Stream stream = webResponse.GetResponseStream();
            Image  final  = Image.FromStream(stream);

            webResponse.Close();
            return(final);
        }
Exemplo n.º 25
0
        public static void ImportKitco(string url)
        {
            System.Net.WebRequest  webReq   = System.Net.WebRequest.Create(url);
            System.Net.WebResponse webRes   = webReq.GetResponse();
            System.IO.Stream       mystream = webRes.GetResponseStream();
            if (mystream == null)
            {
                return;
            }

            HtmlAgilityPack.HtmlDocument myHtmlDoc = new HtmlAgilityPack.HtmlDocument();
            myHtmlDoc.Load(mystream);

            List <String> row = new List <string>();

            try
            {
                //string xpathGoldTable = "//*[@id='main_container']/tr[1]/td[1]/div[3]/div[2]/table/";
                //string xpathGoldTable = "//*[@id='main_container']/tr[1]/td[1]/div[1]/div[2]/table/";
                string xpathGoldTable = "//*[@id='main_container']/tr[1]/td[1]/div[2]/div[2]/table/";
                //code
                row.Add("XAUUSD");
                //last
                //var askNode = myHtmlDoc.DocumentNode.SelectSingleNode(xpathGoldTable + "tr[1]/td[3]");
                //string xpathGoldTable
                var askNode = myHtmlDoc.DocumentNode.SelectSingleNode(xpathGoldTable + "tr[1]/td[2]");
                if (askNode != null)
                {
                    row.Add(askNode.InnerText.Trim());
                }
                //high / low
                var lhNodes = myHtmlDoc.DocumentNode.SelectSingleNode(xpathGoldTable + "tr[2]/td[2]");
                if (lhNodes != null)
                {
                    //row.Add(lhNodes[5].InnerText.Trim()
                    //    + "/" + lhNodes[3].InnerText.Trim().Substring(0, lhNodes[3].InnerText.Length - 2).Trim()); //1781.30 -
                    row.Add(lhNodes.InnerText.Trim());
                }
                //change
                var changeNode = myHtmlDoc.DocumentNode.SelectSingleNode(xpathGoldTable + "tr[3]/td[2]/span/font");
                row.Add(changeNode.InnerText.Trim());
            }
            catch (System.Exception ex)
            {
                return;
            }

            //return Convert2ForexData(row);
        }
Exemplo n.º 26
0
        public override List <TagItem> GetTags(string word, System.Net.IWebProxy proxy)
        {
            //http://mjv-art.org/pictures/autocomplete_tag POST
            List <TagItem> re = new List <TagItem>();

            //no result with length less than 3
            if (word.Length < 3)
            {
                return(re);
            }

            string url = SiteUrl + "/pictures/autocomplete_tag";

            System.Net.HttpWebRequest req = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
            req.UserAgent         = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36";
            req.Proxy             = proxy;
            req.Headers["Cookie"] = sessionId;
            req.Timeout           = 8000;
            req.Method            = "POST";

            byte[] buf = Encoding.UTF8.GetBytes("tag=" + word);
            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();

            string txt = new System.IO.StreamReader(rsp.GetResponseStream()).ReadToEnd();

            rsp.Close();

            //JSON format response
            //{"tags_list": [{"c": 3, "t": "suzumiya <b>haruhi</b> no yuutsu"}, {"c": 1, "t": "suzumiya <b>haruhi</b>"}]}
            object[] tagList = ((new System.Web.Script.Serialization.JavaScriptSerializer()).DeserializeObject(txt) as Dictionary <string, object>)["tags_list"] as object[];
            for (int i = 0; i < tagList.Length && i < 8; i++)
            {
                Dictionary <string, object> tag = tagList[i] as Dictionary <string, object>;
                if (tag["t"].ToString().Trim().Length > 0)
                {
                    re.Add(new TagItem()
                    {
                        Name = tag["t"].ToString().Trim().Replace("<b>", "").Replace("</b>", ""), Count = "N/A"
                    });
                }
            }

            return(re);
        }
Exemplo n.º 27
0
        // GET api/values
        //public IEnumerable<master_record> Get()

        public System.Dynamic.ExpandoObject Get()
        {
            try
            {
                string request_string         = Program.config_couchdb_url + "/mmrds/_all_docs?include_docs=true";
                System.Net.WebRequest request = System.Net.WebRequest.Create(new Uri(request_string));

                request.PreAuthenticate = false;


                if (this.Request.Headers.Contains("Cookie") && this.Request.Headers.GetValues("Cookie").Count() > 0)
                {
                    string[] cookie_set = this.Request.Headers.GetValues("Cookie").First().Split(';');
                    for (int i = 0; i < cookie_set.Length; i++)
                    {
                        string[] auth_session_token = cookie_set[i].Split('=');
                        if (auth_session_token[0].Trim() == "AuthSession")
                        {
                            request.Headers.Add("Cookie", "AuthSession=" + auth_session_token[1]);
                            request.Headers.Add("X-CouchDB-WWW-Authenticate", auth_session_token[1]);
                            break;
                        }
                    }
                }

                System.Net.WebResponse response   = (System.Net.HttpWebResponse)request.GetResponse();
                System.IO.Stream       dataStream = response.GetResponseStream();
                System.IO.StreamReader reader     = new System.IO.StreamReader(dataStream);
                string responseFromServer         = reader.ReadToEnd();

                var result = Newtonsoft.Json.JsonConvert.DeserializeObject <System.Dynamic.ExpandoObject>(responseFromServer);

                return(result);

                /*
                 * < HTTP/1.1 200 OK
                 * < Set-Cookie: AuthSession=YW5uYTo0QUIzOTdFQjrC4ipN-D-53hw1sJepVzcVxnriEw;
                 * < Version=1; Path=/; HttpOnly
                 * > ...
                 * <
                 * {"ok":true}*/
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }

            return(null);
        }
Exemplo n.º 28
0
        // POST api/values
        public async System.Threading.Tasks.Task Post([FromBody] mmria.common.metadata.app metadata)
        {
            bool valid_login = false;

            try
            {
                string request_string         = Program.config_couchdb_url + "/_session";
                System.Net.WebRequest request = System.Net.WebRequest.Create(new System.Uri(request_string));

                request.PreAuthenticate = false;

                if (!string.IsNullOrWhiteSpace(this.Request.Cookies["AuthSession"]))
                {
                    string auth_session_value = this.Request.Cookies["AuthSession"];
                    request.Headers.Add("Cookie", "AuthSession=" + auth_session_value);
                    request.Headers.Add("X-CouchDB-WWW-Authenticate", auth_session_value);
                }

                System.Net.WebResponse response = await request.GetResponseAsync();

                System.IO.Stream       dataStream   = response.GetResponseStream();
                System.IO.StreamReader reader       = new System.IO.StreamReader(dataStream);
                string           responseFromServer = reader.ReadToEnd();
                session_response json_result        = Newtonsoft.Json.JsonConvert.DeserializeObject <session_response>(responseFromServer);

                valid_login = json_result.userCTX.name != null;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }

            if (valid_login)
            {
                Newtonsoft.Json.JsonSerializerSettings settings = new Newtonsoft.Json.JsonSerializerSettings();
                settings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
                string object_string = Newtonsoft.Json.JsonConvert.SerializeObject(metadata, settings);
                string hash          = GetHash(object_string);
                if (current_edit_list ["metadata"].id != hash)
                {
                    Current_Edit current = new Current_Edit();
                    current.id        = hash;
                    current.metadata  = object_string;
                    current.edit_type = "json";

                    current_edit_list ["metadata"] = current;
                }
            }
        }
Exemplo n.º 29
0
        protected LocationDetailsQuery QueryGoogleForLocation(string locstr)
        {
            System.IO.Stream       Str    = null;
            System.IO.StreamReader srRead = null;

            string retStr = null;

            try {
                // make a Web request
                System.Type            t    = this.GetType();
                string                 s    = "http://maps.google.com/maps/api/geocode/xml?address=" + locstr.Replace(" ", "%20") + "&sensor=false";
                System.Net.WebRequest  req  = System.Net.WebRequest.Create(s);
                System.Net.WebResponse resp = req.GetResponse();
                Str    = resp.GetResponseStream();
                srRead = new System.IO.StreamReader(Str);
                // read all the text
                retStr = srRead.ReadToEnd();
            } catch (Exception ex) {
                throw new Exception("Couldnt Load Data From Google : " + ex.ToString());
                retStr = null;
            } finally {
                //  Close Stream and StreamReader when done
                if (srRead != null)
                {
                    srRead.Close();
                }
                if (Str != null)
                {
                    Str.Close();
                }
            }

            LocationDetailsQuery details = new LocationDetailsQuery();


            if (!(ReadResult(retStr) == "OK"))
            {
                details.ErrorCode = "Error Getting Status Code";
            }
            else
            {
                details.LongLat = ReadLong(retStr) + ", " + ReadLat(retStr);
                details.PCode   = ReadAddressComponent(retStr, "postal_code");
                details.Country = ReadAddressComponent(retStr, "country", true);
            }


            return(details);
        }
        public static bool WebRequestTest()
        {
            string url = "http://www.google.com";

            try
            {
                System.Net.WebRequest  myRequest  = System.Net.WebRequest.Create(url);
                System.Net.WebResponse myResponse = myRequest.GetResponse();
            }
            catch (System.Net.WebException)
            {
                return(false);
            }
            return(true);
        }
Exemplo n.º 31
0
 public static Image GetImgFromUrl(string httpurl)
 {
     try
     {
         System.Net.WebRequest  webreq = System.Net.WebRequest.Create(httpurl);
         System.Net.WebResponse webres = webreq.GetResponse();
         System.IO.Stream       stream = webres.GetResponseStream();
         Image result = Image.FromStream(stream);
         return(result);
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
			public NavigationRoutedEventArgs(RoutedEvent RoutedEvent, Uri uri, System.Net.WebResponse response) {
				base.RoutedEvent = RoutedEvent;
				Uri = uri;
				Response = response;
			}