Search Results

Search found 455 results on 19 pages for 'httpwebrequest'.

Page 9/19 | < Previous Page | 5 6 7 8 9 10 11 12 13 14 15 16  | Next Page >

  • How to terminate a request in JSP (not the "return;")

    - by Genom
    I am programming a website with JSP. There are pages where user must be logged in to see it. If they are not logged in, they should see a login form. I have seen in a php code that you can make a .jsp page (single file), which checkes, whether the user is logged in or not. If not it will show the login form. If the user is logged in, nothing will be done. So in order to do that I use this structure in my JSPs: Headers, menus, etc. etc... normal stuff which would be shown such as body, footer to a logged in user. This structure is very easy to apply to all webpages. So I don't have to apply checking algorithm to each webpage! I can simply add this "" and the page is secure! So my problem is that if the user is not logged in, then only the log in form should be shown and the footer. So code should bypass the body. Therefore structured my checklogin.jsp so: If user is not logged in show the login form and footer and terminate request. The problem is that I don't know how to terminate the request... If I use "return;" then only the checklogin.jsp stops but server continues to process parent page! Therefore page has 2 footers! (1 from parent page and 1 from checklogin.jsp). How can I avoid this? (There is exit(); in php for this by the way!) Thanks for any suggestions!

    Read the article

  • How can I call multiple nutrient information from ESHA Research API? (apid.esha.com)

    - by user1833044
    I want to call ESHA Research nutrient REST API. I cannot seem to figure out how to call multiple nutrients using ESHA REST API. So far I am calling the following and only able to retrieve the calories, or protein, or another type of nutrient information. So I was hoping someone had experience in retrieving all the nutrient information with one call. Is this possible? This is how I call to retrieve the TWIX nutrient http://api.esha.com/analysis?apikey=xxxx&fo=urn:uuid:81d268ac-f1dc-4991-98c1-1b4d3a5006da (returns calories, please note the api key is not xxxx but instead a key generated from Esha once you sign up as developer) The return is JSON format. If I want to call fat it would be the following http://api.esha.com/analysis?apikey=xxxx&fo=urn:uuid:81d268ac-f1dc-4991-98c1-1b4d3a5006da&n=urn:uuid:589294dc-3dcc-4b64-be06-c07e7f65c4bd How can I make a call once and get a return of all the nutrients (so Fat, Calories, Carbs, Vitamins, etc..) for a particular food ID? I have researched and looked at this for a while and cannot seem to find the answer. Thanks in advance for your help.

    Read the article

  • .NET - Is it possible to proxy a HTTPS request using HttpListener & HttpWebRequest? (or is it not p

    - by Greg
    Hi, Question - Is it possible to proxy a HTTPS request using HttpListener & HttpWebRequest? (or is it not possbile due to the encryption?) I have got a .NET proxy working by using HttpListener & HttpWebRequest using the approach here. I'm trying to extend this at the moment to listen for HTTPS too (refer this question) however I'm wondering if I'm trying to tackle something that is not possible...That is if this code works by listening for the HTTPS request (using HttpListener) and then copying headers & content across to a new HttpWebRequest, is this flawed as it may not be able to decrypt the request to get the content? But then normal proxy servers obviously can proxy HTTPS, so I guess perhaps it will work because it will just copy across the encrypted content?

    Read the article

  • Accessing SharePoint 2010 Data with REST/OData on Windows Phone 7

    - by Jan Tielens
    Consuming SharePoint 2010 data in Windows Phone 7 applications using the CTP version of the developer tools is quite a challenge. The issue is that the SharePoint 2010 data is not anonymously available; users need to authenticate to be able to access the data. When I first tried to access SharePoint 2010 data from my first Hello-World-type Windows Phone 7 application I thought “Hey, this should be easy!” because Windows Phone 7 development based on Silverlight and SharePoint 2010 has a Client Object Model for Silverlight. Unfortunately you can’t use the Client Object Model of SharePoint 2010 on the Windows Phone platform; there’s a reference to an assembly that’s not available (System.Windows.Browser). My second thought was “OK, no problem!” because SharePoint 2010 also exposes a REST/OData API to access SharePoint data. Using the REST API in SharePoint 2010 is as easy as making a web request for a URL (in which you specify the data you’d like to retrieve), e.g. http://yoursiteurl/_vti_bin/listdata.svc/Announcements. This is very easy to accomplish in a Silverlight application that’s running in the context of a page in a SharePoint site, because the credentials of the currently logged on user are automatically picked up and passed to the WCF service. But a Windows Phone application is of course running outside of the SharePoint site’s page, so the application should build credentials that have to be passed to SharePoint’s WCF service. This turns out to be a small challenge in Silverlight 3, the WebClient doesn’t support authentication; there is a Credentials property but when you set it and make the request you get a NotImplementedException exception. Probably this issued will be solved in the very near future, since Silverlight 4 does support authentication, and there’s already a WCF Data Services download that uses this new platform feature of Silverlight 4. So when Windows Phone platform switches to Silverlight 4, you can just use the WebClient to get the data. Even more, if the OData Client Library for Windows Phone 7 gets updated after that, things should get even easier! By the way: the things I’m writing in this paragraph are just assumptions that I make which make a lot of sense IMHO, I don’t have any info all of this will happen, but I really hope so. So are SharePoint developers out of the Windows Phone development game until they get this fixed? Well luckily not, when the HttpWebRequest class is being used instead, you can pass credentials! Using the HttpWebRequest class is slightly more complex than using the WebClient class, but the end result is that you have access to your precious SharePoint 2010 data. The following code snippet is getting all the announcements of an Annoucements list in a SharePoint site: HttpWebRequest webReq =     (HttpWebRequest)HttpWebRequest.Create("http://yoursite/_vti_bin/listdata.svc/Announcements");webReq.Credentials = new NetworkCredential("username", "password"); webReq.BeginGetResponse(    (result) => {        HttpWebRequest asyncReq = (HttpWebRequest)result.AsyncState;         XDocument xdoc = XDocument.Load(            ((HttpWebResponse)asyncReq.EndGetResponse(result)).GetResponseStream());         XNamespace ns = "http://www.w3.org/2005/Atom";        var items = from item in xdoc.Root.Elements(ns + "entry")                    select new { Title = item.Element(ns + "title").Value };         this.Dispatcher.BeginInvoke(() =>        {            foreach (var item in items)                MessageBox.Show(item.Title);        });    }, webReq); When you try this in a Windows Phone 7 application, make sure you add a reference to the System.Xml.Linq assembly, because the code uses Linq to XML to parse the resulting Atom feed, so the Title of every announcement is being displayed in a MessageBox. Check out my previous post if you’d like to see a more polished sample Windows Phone 7 application that displays SharePoint 2010 data.When you plan to use this technique, it’s of course a good idea to encapsulate the code doing the request, so it becomes really easy to get the data that you need. In the following code snippet you can find the GetAtomFeed method that gets the contents of any Atom feed, even if you need to authenticate to get access to the feed. delegate void GetAtomFeedCallback(Stream responseStream); public MainPage(){    InitializeComponent();     SupportedOrientations = SupportedPageOrientation.Portrait |         SupportedPageOrientation.Landscape;     string url = "http://yoursite/_vti_bin/listdata.svc/Announcements";    string username = "username";    string password = "password";    string domain = "";     GetAtomFeed(url, username, password, domain, (s) =>    {        XNamespace ns = "http://www.w3.org/2005/Atom";        XDocument xdoc = XDocument.Load(s);         var items = from item in xdoc.Root.Elements(ns + "entry")                    select new { Title = item.Element(ns + "title").Value };         this.Dispatcher.BeginInvoke(() =>        {            foreach (var item in items)            {                MessageBox.Show(item.Title);            }        });    });} private static void GetAtomFeed(string url, string username,     string password, string domain, GetAtomFeedCallback cb){    HttpWebRequest webReq = (HttpWebRequest)HttpWebRequest.Create(url);    webReq.Credentials = new NetworkCredential(username, password, domain);     webReq.BeginGetResponse(        (result) =>        {            HttpWebRequest asyncReq = (HttpWebRequest)result.AsyncState;            HttpWebResponse resp = (HttpWebResponse)asyncReq.EndGetResponse(result);            cb(resp.GetResponseStream());        }, webReq);}

    Read the article

  • What might cause the big overhead of making a HttpWebRequest call?

    - by Dimitri C.
    When I send/receive data using HttpWebRequest (on Silverlight, using the HTTP POST method) in small blocks, I measure the very small throughput of 500 bytes/s over a "localhost" connection. When sending the data in large blocks, I get 2 MB/s, which is some 5000 times faster. Does anyone know what could cause this incredibly big overhead? Update: I did the performance measurement on both Firefox 3.6 and Internet Explorer 7. Both showed similar results. Update: The Silverlight client-side code I use is essentially my own implementation of the WebClient class. The reason I wrote it is because I noticed the same performance problem with WebClient, and I thought that the HttpWebRequest would allow to tweak the performance issue. Regrettably, this did not work. The implementation is as follows: public class HttpCommChannel { public delegate void ResponseArrivedCallback(object requestContext, BinaryDataBuffer response); public HttpCommChannel(ResponseArrivedCallback responseArrivedCallback) { this.responseArrivedCallback = responseArrivedCallback; this.requestSentEvent = new ManualResetEvent(false); this.responseArrivedEvent = new ManualResetEvent(true); } public void MakeRequest(object requestContext, string url, BinaryDataBuffer requestPacket) { responseArrivedEvent.WaitOne(); responseArrivedEvent.Reset(); this.requestMsg = requestPacket; this.requestContext = requestContext; this.webRequest = WebRequest.Create(url) as HttpWebRequest; this.webRequest.AllowReadStreamBuffering = true; this.webRequest.ContentType = "text/plain"; this.webRequest.Method = "POST"; this.webRequest.BeginGetRequestStream(new AsyncCallback(this.GetRequestStreamCallback), null); this.requestSentEvent.WaitOne(); } void GetRequestStreamCallback(IAsyncResult asynchronousResult) { System.IO.Stream postStream = webRequest.EndGetRequestStream(asynchronousResult); postStream.Write(requestMsg.Data, 0, (int)requestMsg.Size); postStream.Close(); requestSentEvent.Set(); webRequest.BeginGetResponse(new AsyncCallback(this.GetResponseCallback), null); } void GetResponseCallback(IAsyncResult asynchronousResult) { HttpWebResponse response = (HttpWebResponse)webRequest.EndGetResponse(asynchronousResult); Stream streamResponse = response.GetResponseStream(); Dim.Ensure(streamResponse.CanRead); byte[] readData = new byte[streamResponse.Length]; Dim.Ensure(streamResponse.Read(readData, 0, (int)streamResponse.Length) == streamResponse.Length); streamResponse.Close(); response.Close(); webRequest = null; responseArrivedEvent.Set(); responseArrivedCallback(requestContext, new BinaryDataBuffer(readData)); } HttpWebRequest webRequest; ManualResetEvent requestSentEvent; BinaryDataBuffer requestMsg; object requestContext; ManualResetEvent responseArrivedEvent; ResponseArrivedCallback responseArrivedCallback; } I use this code to send data back and forth to an HTTP server.

    Read the article

  • scraping website with javascript cookie with c#

    - by erwin
    Hi all, I want to scrap some things from the following site: http://www.conrad.nl/modelspoor This is my function: public string SreenScrape(string urlBase, string urlPath) { CookieContainer cookieContainer = new CookieContainer(); HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(urlBase + urlPath); httpWebRequest.CookieContainer = cookieContainer; httpWebRequest.UserAgent = "Mozilla/6.0 (Windows; U; Windows NT 7.0; en-US; rv:1.9.0.8) Gecko/2009032609 Firefox/3.0.9 (.NET CLR 3.5.30729)"; WebResponse webResponse = httpWebRequest.GetResponse(); string result = new System.IO.StreamReader(webResponse.GetResponseStream(), Encoding.Default).ReadToEnd(); webResponse.Close(); if (result.Contains("<frame src=")) { Regex metaregex = new Regex("http:[a-z:/._0-9!?=A-Z&]*",RegexOptions.Multiline); result = result.Replace("\r\n", ""); Match m = metaregex.Match(result); string key = m.Groups[0].Value; foreach (Match match in metaregex.Matches(result)) { HttpWebRequest redirectHttpWebRequest = (HttpWebRequest)WebRequest.Create(key); redirectHttpWebRequest.CookieContainer = cookieContainer; webResponse = redirectHttpWebRequest.GetResponse(); string redirectResponse = new System.IO.StreamReader(webResponse.GetResponseStream(), Encoding.Default).ReadToEnd(); webResponse.Close(); return redirectResponse; } } return result; } But when i do this i get a string with an error from the website that it use javascript. Does anybody know how to fix this? Kind regards Erwin

    Read the article

  • Is there a Better Way to Retreive Raw XML from a URL than WebClient or HttpWebRequest? [.NET]

    - by DaMartyr
    I am working on a Geocoding app where I put the address in the URL and retreive the XML. I need the complete XML response for this project. Is there any other class for downloading the XML from a website that may be faster than using WebClient or HttpWebRequest? Can the XMLReader be used to get the full XML without string manipulation and would that be faster and/or more efficient?

    Read the article

  • Is there a Javascript equivalent of .NET HttpWebRequest.ClientCertificates?

    - by Coder 42
    I have this code working in C#: var request = (HttpWebRequest)WebRequest.Create("https://x.com/service"); request.Method = "GET"; // Add X509 certificate var bytes = Convert.FromBase64String(certBase64); var certificate = new X509Certificate2(bytes, password); request.ClientCertificates.Add(certificate, "password")); Is there any way to reproduce this request in Javascript? Third-party libraries would be fine for my purposes.

    Read the article

  • WCF GZip Compression Request/Response Processing

    - by IanT8
    How do I get a WCF client to process server responses which have been GZipped or Deflated by IIS? On IIS, I've followed the instructions here on how to make IIS 6 gzip all responses (where the request contained "Accept-Encoding: gzip, deflate") emitted by .svc wcf services. On the client, I've followed the instructions here and here on how to inject this header into the web request: "Accept-Encoding: gzip, deflate". Fiddler2 shows the response is binary and not plain old Xml. The client crashes with an exception which basically says there's no Xml header, which ofcourse is true. In my IClientMessageInspector, the app crashes before AfterReceiveReply is called. Some further notes: (1) I can't change the WCF service or client as they are supplied by a 3rd party. I can however attach behaviors and/or message inspectors via configuration if this is the right direction to take. (2) I don't want to compress/uncompress just the soap body, but the entire message. Any ideas/solutions? * SOLVED * It was not possible to write a WCF extension to achieve these goals. Instead I followed this CodeProject article which advocate a helper class: public class CompressibleHttpRequestCreator : IWebRequestCreate { public CompressibleHttpRequestCreator() { } WebRequest IWebRequestCreate.Create(Uri uri) { HttpWebRequest httpWebRequest = Activator.CreateInstance(typeof(HttpWebRequest), BindingFlags.CreateInstance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, new object[] { uri, null }, null) as HttpWebRequest; if (httpWebRequest == null) { return null; } httpWebRequest.AutomaticDecompression =DecompressionMethods.GZip | DecompressionMethods.Deflate; return httpWebRequest; } } and also, an addition to the application configuration file: <configuration> <system.net> <webRequestModules> <remove prefix="http:"/> <add prefix="http:" type="Pajocomo.Net.CompressibleHttpRequestCreator, Pajocomo" /> </webRequestModules> </system.net> </configuration> What seems to be happening is that WCF eventually asks some factory or other deep down in system.net to provide an HttpWebRequest instance, and we provide the helper that will be asked to create the required instance. In the WCF client configuration file, a simple basicHttpBinding is all that is required, without the need for any custom extensions. When the application runs, the client Http request contains the header "Accept-Encoding: gzip, deflate", the server returns a gzipped web response, and the client transparently decompresses the http response before handing it over to WCF. When I tried to apply this technique to Web Services I found that it did NOT work. Although the helper class was executed in the same was as when used by the WCF client, the http request did not contain the "Accept-Encoding: ..." header. To make this work for Web Services, I had to edit the Web Proxy class, and add this method: protected override System.Net.WebRequest GetWebRequest(Uri uri) { System.Net.HttpWebRequest rq = (System.Net.HttpWebRequest)base.GetWebRequest(uri); rq.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate; return rq; } Note that it did not matter whether the CompressibleHttpRequestCreator and block from the application config file were present or not. For web services, only overriding GetWebRequest in the Web Service Proxy worked.

    Read the article

  • Trying to use HttpWebRequest to load a page in a file.

    - by Malcolm
    Hi, I have a ASP.NET MVC app that works fine in the browser. I am using the following code to be able to write the html of a retrieved page to a file. (This is to use in a PDF conversion component) But this code errors out continually but not in the browser. I get timeout errors sometimes asn 500 errors. Public Function GetPage(ByVal url As String, ByVal filename As String) As Boolean Dim request As HttpWebRequest Dim username As String Dim password As String Dim docid As String Dim poststring As String Dim bytedata() As Byte Dim requestStream As Stream Try username = "pdfuser" password = "pdfuser" docid = "docid=inv12154" poststring = String.Format("username={0}&password={1}&{2}", username, password, docid) bytedata = Encoding.UTF8.GetBytes(poststring) request = WebRequest.Create(url) request.Method = "Post" request.ContentLength = bytedata.Length request.ContentType = "application/x-www-form-urlencoded" requestStream = request.GetRequestStream() requestStream.Write(bytedata, 0, bytedata.Length) requestStream.Close() request.Timeout = 60000 Dim response As HttpWebResponse Dim responseStream As Stream Dim reader As StreamReader Dim sb As New StringBuilder() Dim line As String = String.Empty response = request.GetResponse() responseStream = response.GetResponseStream() reader = New StreamReader(responseStream, System.Text.Encoding.ASCII) line = reader.ReadLine() While (Not line Is Nothing) sb.Append(line) line = reader.ReadLine() End While File.WriteAllText(filename, sb.ToString()) Catch ex As Exception MsgBox(ex.Message) End Try Return True End Function

    Read the article

  • Asynchronous Silverlight 4 call to the World of Warcraft armoury streaming XML in C#

    - by user348446
    Hello - I have been stuck on this all weekend and failed miserably! Please help me to claw back my sanity!! Your challenge For my first Silverlight application I thought it would be fun to use the World of Warcraft armoury to list the characters in my guild. This involves making an asyncronous from Silverlight (duh!) to the WoW armoury which is XML based. SIMPLE EH? Take a look at this link and open the source. You'll see what I mean: http://eu.wowarmory.com/guild-info.xml?r=Eonar&n=Gifted and Talented Below is code for getting the XML (the call to ShowGuildies will cope with the returned XML - I have tested this locally and I know it works). I have not managed to get the expected returned XML at all. Notes: If the browser is capable of transforming the XML it will do so, otherwise HTML will be provided. I think it examines the UserAgent I am a seasoned asp.net web developer C# so go easy if you start talking about native to Windows Forms / WPF I can't seem to set the UserAgent setting in .net 4.0 - doesn't seem to be a property off the HttpWebRequest object for some reason - i think it used to be available. Silverlight 4.0 (created as 3.0 originally before I updated my installation of Silverlight to 4.0) Created using C# 4.0 Please explain as if you talking to a web developer and not a proper programming lol! Below is the code - it should return the XML from the wow armoury. private void button7_Click(object sender, RoutedEventArgs e) { // URL for armoury lookup string url = @"http://eu.wowarmory.com/guild-info.xml?r=Eonar&n=Gifted and Talented"; // Create the web request HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url); // Set the user agent so we are returned XML and not HTML //httpWebRequest.Headers["User-Agent"] = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0)"; // Not sure about this dispatcher thing - it's late so i have started to guess. Dispatcher.BeginInvoke(delegate() { // Call asyncronously IAsyncResult asyncResult = httpWebRequest.BeginGetResponse(ReqCallback, httpWebRequest); // End the response and use the result using (HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.EndGetResponse(asyncResult)) { // Load an XML document from a stream XDocument x = XDocument.Load(httpWebResponse.GetResponseStream()); // Basic function that will use LINQ to XML to get the list of characters. ShowGuildies(x); } }); } private void ReqCallback(IAsyncResult asynchronousResult) { // Not sure what to do here - maybe update the interface? } Really hope someone out there can help me! Thanks mucho! Dan. PS Yes, I have noticed the irony in the name of the guild :)

    Read the article

  • Trouble getting email attachment from Exchange

    - by JimR
    I am getting the error message “The remote server returned an error: (501) Not Implemented.” when I try to use the HttpWebRequest.GetResponse() using the GET Method to get an email attachment from exchange. I have tried to change the HttpVersion and don’t think it is a permissions issue since I can search the inbox. I know my credentials are correct as they are used to get HREF using the HttpWebRequest.Method = Search on the inbox (https://mail.mailserver.com/exchange/testemailaccount/Inbox/). HREF = https://mail.mailserver.com/exchange/testemailaccount/Inbox/testemail.EML/attachment.csv Sample Code: HttpWebRequest req = (System.Net.HttpWebRequest) HttpWebRequest.CreateHREF); req.Method = "GET"; req.Credentials = this.mCredentialCache; string data = string.Empty; using (WebResponse resp = req.GetResponse()) { Encoding enc = Encoding.Default; if (resp == null) { throw new Exception("Response contains no information."); } using (StreamReader sr = new StreamReader(resp.GetResponseStream(), Encoding.ASCII)) { data = sr.ReadToEnd(); } }

    Read the article

  • Login Website, curious Cookie Problem

    - by Collin Peters
    Hello, Language: C# Development Environment: Visual Studio 2008 Sorry if the english is not perfect. I want to login to a Website and get some Data from there. My Problem is that the Cookies does not work. Everytime the Website says that I should activate Cookies but i activated the Cookies trough a Cookiecontainer. I sniffed the traffic serveral times for the login progress and I see no problem there. I tried different methods to login and I have searched if someone else have this Problem but no results... Login Page is: "www.uploaded.to", Here is my Code to Login in Short Form: private void login() { //Global CookieContainer for all the Cookies CookieContainer _cookieContainer = new CookieContainer(); //First Login to the Website HttpWebRequest _request1 = (HttpWebRequest)WebRequest.Create("http://uploaded.to/login"); _request1.Method = "POST"; _request1.CookieContainer = _cookieContainer; string _postData = "email=XXXXX&password=XXXXX"; byte[] _byteArray = Encoding.UTF8.GetBytes(_postData); Stream _reqStream = _request1.GetRequestStream(); _reqStream.Write(_byteArray, 0, _byteArray.Length); _reqStream.Close(); HttpWebResponse _response1 = (HttpWebResponse)_request1.GetResponse(); _response1.Close(); //######################## //Follow the Link from Request1 HttpWebRequest _request2 = (HttpWebRequest)WebRequest.Create("http://uploaded.to/login?coo=1"); _request2.Method = "GET"; _request2.CookieContainer = _cookieContainer; HttpWebResponse _response2 = (HttpWebResponse)_request2.GetResponse(); _response2.Close(); //####################### //Get the Data from the Page after Login HttpWebRequest _request3 = (HttpWebRequest)WebRequest.Create("http://uploaded.to/home"); _request3.Method = "GET"; _request3.CookieContainer = _cookieContainer; HttpWebResponse _response3 = (HttpWebResponse)_request3.GetResponse(); _response3.Close(); } I'm stuck at this problem since many weeks and i found no solution that works, please help...

    Read the article

  • How to play non buffered .wav with MediaStreamSource implementation in Silverlight 4?

    - by kyrisu
    Background I'm trying to stream a wave file in Silverlight 4 using MediaStreamSource implementation found here. The problem is I want to play the file while it's still buffering, or at least give user some visual feedback while it's buffering. For now my code looks like that: private void button1_Click(object sender, RoutedEventArgs e) { HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri(App.Current.Host.Source, "../test.wav")); //request.ContentType = "audio/x-wav"; request.AllowReadStreamBuffering = false; request.BeginGetResponse(new AsyncCallback(RequestCallback), request); } private void RequestCallback(IAsyncResult ar) { this.Dispatcher.BeginInvoke(delegate() { HttpWebRequest request = (HttpWebRequest)ar.AsyncState; HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(ar); WaveMediaStreamSource wavMss = new WaveMediaStreamSource(response.GetResponseStream()); try { me.SetSource(wavMss); } catch (InvalidOperationException) { // This file is not valid } me.Play(); }); } The problem is that after settings request.AllowREadStreamBuffer to false the stream does not support seeking and the above mentioned implementation throws an exception (keep in mind I've put some of the position setting logic into if(stream.CanSeek) block): Read is not supported on the main thread when buffering is disabled Question Is there a way to play wav stream without buffering it in advance?

    Read the article

  • ASP.net WebRequest Exception "System.Net.WebException: The server committed a protocol violation"

    - by Billy
    I call WebRequest.GetResponse() and encounter the error: The server committed a protocol violation. Section=ResponseStatusLine I google this error and add the following lines in web.config: <configuration> <system.net> <settings> <httpWebRequest useUnsafeHeaderParsing="true" /> </settings> </system.net> </configuration> However, it doesn't work. Here is my ASP.net code: HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url); request.Method = "HEAD"; using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { ...... }

    Read the article

  • .NET - downloading multiple pages from a website with a single DNS query

    - by lampak
    I'm using HttpRequest to download several pages from a website (in a loop). Simplifying it looks like this: HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create( "http://sub.domain.com/something/" + someString ); HttpWebResponse resp = (HttpWebResponse)req.GetResponse(); //do something I'm not quite sure actually but every request seems to resolve the address again (I don't know how to test if I'm right). I would like to boost it a little and resolve the address once and then reuse it for all requests. I can't work out how to force HttpRequest into using it, though. I have tried using Dns.GetHostAddresses, converting the result to a string and passing it as the address to HttpWebRequest.Create. Unfortunately, server returns error 404 then. I managed to google that's probably because the "Host" header of the http query doesn't match what the server expects. Is there a simple way to solve this?

    Read the article

  • How do I sign a HTTP request with a X.509 certificate in Java?

    - by Rune
    How do I perform an HTTP request and sign it with a X.509 certificate using Java? I usually program in C#. Now, what I would like to do is something similar to the following, only in Java: private HttpWebRequest CreateRequest(Uri uri, X509Certificate2 cert) { HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri); request.ClientCertificates.Add(cert); /* ... */ return request; } In Java I have created a java.security.cert.X509Certificate instance but I cannot figure out how to associate it to a HTTP request. I can create a HTTP request using a java.net.URL instance, but I don't seem to be able to associate my certificate with that instance (and I'm not sure whether using java.net.URL is even appropriate).

    Read the article

  • where is POST params for WCF REST

    - by Costa
    Hi Can u put some code sample to get Post parameters sent by client to WCF REST webservice. The request is though a HttpWebRequest. The client will not serialize anything if I will request a certain XML format from PHP programmer, how to make WCF convert this XML to one parameter. currently I am trying to send the request like this and I am stuck HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://100.100.1.4000:2805/Something.svc/Bomba/Data.php"); request.ContentType = "text/xml"; request.Method = "POST"; StreamWriter stream = new StreamWriter(request.GetRequestStream()); { stream.Write("FirstName=0&LastName=2"); } request.GetResponse(); stream.Close(); Thanks

    Read the article

  • ResponseStatusLine protocol violation

    - by Tom Hines
    I parse/scrape a few web page every now and then and recently ran across an error that stated: "The server committed a protocol violation. Section=ResponseStatusLine".   After a few web searches, I found a couple of suggestions – one of which said the problem could be fixed by changing the HttpWebRequest ProtocolVersion to 1.0 with the command: 1: HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(strURI); 2: req.ProtocolVersion = HttpVersion.Version10;   …but that did not work in my particular case.   What DID work was the next suggestion I found that suggested the use of the setting: “useUnsafeHeaderParsing” either in the app.config file or programmatically. If added to the app.config, it would be: 1: <!-- after the applicationSettings --> 2: <system.net> 3: <settings> 4: <httpWebRequest useUnsafeHeaderParsing ="true"/> 5: </settings> 6: </system.net>   If done programmatically, it would look like this: C++: 1: // UUHP_CPP.h 2: #pragma once 3: using namespace System; 4: using namespace System::Reflection; 5:   6: namespace UUHP_CPP 7: { 8: public ref class CUUHP_CPP 9: { 10: public: 11: static bool UseUnsafeHeaderParsing(String^% strError) 12: { 13: Assembly^ assembly = Assembly::GetAssembly(System::Net::Configuration::SettingsSection::typeid); //__typeof 14: if (nullptr==assembly) 15: { 16: strError = "Could not access Assembly"; 17: return false; 18: } 19:   20: Type^ type = assembly->GetType("System.Net.Configuration.SettingsSectionInternal"); 21: if (nullptr==type) 22: { 23: strError = "Could not access internal settings"; 24: return false; 25: } 26:   27: Object^ obj = type->InvokeMember("Section", 28: BindingFlags::Static | BindingFlags::GetProperty | BindingFlags::NonPublic, 29: nullptr, nullptr, gcnew array<Object^,1>(0)); 30:   31: if(nullptr == obj) 32: { 33: strError = "Could not invoke Section member"; 34: return false; 35: } 36:   37: FieldInfo^ fi = type->GetField("useUnsafeHeaderParsing", BindingFlags::NonPublic | BindingFlags::Instance); 38: if(nullptr == fi) 39: { 40: strError = "Could not access useUnsafeHeaderParsing field"; 41: return false; 42: } 43:   44: if (!(bool)fi->GetValue(obj)) 45: { 46: fi->SetValue(obj, true); 47: } 48:   49: return true; 50: } 51: }; 52: } C# (CSharp): 1: using System; 2: using System.Reflection; 3:   4: namespace UUHP_CS 5: { 6: public class CUUHP_CS 7: { 8: public static bool UseUnsafeHeaderParsing(ref string strError) 9: { 10: Assembly assembly = Assembly.GetAssembly(typeof(System.Net.Configuration.SettingsSection)); 11: if (null == assembly) 12: { 13: strError = "Could not access Assembly"; 14: return false; 15: } 16:   17: Type type = assembly.GetType("System.Net.Configuration.SettingsSectionInternal"); 18: if (null == type) 19: { 20: strError = "Could not access internal settings"; 21: return false; 22: } 23:   24: object obj = type.InvokeMember("Section", 25: BindingFlags.Static | BindingFlags.GetProperty | BindingFlags.NonPublic, 26: null, null, new object[] { }); 27:   28: if (null == obj) 29: { 30: strError = "Could not invoke Section member"; 31: return false; 32: } 33:   34: // If it's not already set, set it. 35: FieldInfo fi = type.GetField("useUnsafeHeaderParsing", BindingFlags.NonPublic | BindingFlags.Instance); 36: if (null == fi) 37: { 38: strError = "Could not access useUnsafeHeaderParsing field"; 39: return false; 40: } 41:   42: if (!Convert.ToBoolean(fi.GetValue(obj))) 43: { 44: fi.SetValue(obj, true); 45: } 46:   47: return true; 48: } 49: } 50: }   F# (FSharp): 1: namespace UUHP_FS 2: open System 3: open System.Reflection 4: module CUUHP_FS = 5: let UseUnsafeHeaderParsing(strError : byref<string>) : bool = 6: // 7: let assembly : Assembly = Assembly.GetAssembly(typeof<System.Net.Configuration.SettingsSection>) 8: if (null = assembly) then 9: strError <- "Could not access Assembly" 10: false 11: else 12: 13: let myType : Type = assembly.GetType("System.Net.Configuration.SettingsSectionInternal") 14: if (null = myType) then 15: strError <- "Could not access internal settings" 16: false 17: else 18: 19: let obj : Object = myType.InvokeMember("Section", BindingFlags.Static ||| BindingFlags.GetProperty ||| BindingFlags.NonPublic, null, null, Array.zeroCreate 0) 20: if (null = obj) then 21: strError <- "Could not invoke Section member" 22: false 23: else 24: 25: // If it's not already set, set it. 26: let fi : FieldInfo = myType.GetField("useUnsafeHeaderParsing", BindingFlags.NonPublic ||| BindingFlags.Instance) 27: if(null = fi) then 28: strError <- "Could not access useUnsafeHeaderParsing field" 29: false 30: else 31: 32: if (not(Convert.ToBoolean(fi.GetValue(obj)))) then 33: fi.SetValue(obj, true) 34: 35: // Now return true 36: true VB (Visual Basic): 1: Option Explicit On 2: Option Strict On 3: Imports System 4: Imports System.Reflection 5:   6: Public Class CUUHP_VB 7: Public Shared Function UseUnsafeHeaderParsing(ByRef strError As String) As Boolean 8:   9: Dim assembly As [Assembly] 10: assembly = [assembly].GetAssembly(GetType(System.Net.Configuration.SettingsSection)) 11:   12: If (assembly Is Nothing) Then 13: strError = "Could not access Assembly" 14: Return False 15: End If 16:   17: Dim type As Type 18: type = [assembly].GetType("System.Net.Configuration.SettingsSectionInternal") 19: If (type Is Nothing) Then 20: strError = "Could not access internal settings" 21: Return False 22: End If 23:   24: Dim obj As Object 25: obj = [type].InvokeMember("Section", _ 26: BindingFlags.Static Or BindingFlags.GetProperty Or BindingFlags.NonPublic, _ 27: Nothing, Nothing, New [Object]() {}) 28:   29: If (obj Is Nothing) Then 30: strError = "Could not invoke Section member" 31: Return False 32: End If 33:   34: ' If it's not already set, set it. 35: Dim fi As FieldInfo 36: fi = [type].GetField("useUnsafeHeaderParsing", BindingFlags.NonPublic Or BindingFlags.Instance) 37: If (fi Is Nothing) Then 38: strError = "Could not access useUnsafeHeaderParsing field" 39: Return False 40: End If 41:   42: If (Not Convert.ToBoolean(fi.GetValue(obj))) Then 43: fi.SetValue(obj, True) 44: End If 45:   46: Return True 47: End Function 48: End Class   Technorati Tags: C++,CPP,VB,Visual Basic,F#,FSharp,C#,CSharp,ResponseStatusLine,protocol violation

    Read the article

  • Integrating Windows Form Click Once Application into SharePoint 2007 &ndash; Part 2 of 4

    - by Kelly Jones
    In my last post, I explained why we decided to use a Click Once application to solve our business problem. To quickly review, we needed a way for our business users to upload documents to a SharePoint 2007 document library in mass, set the meta data, set the permissions per document, and to do so easily. Let’s look at the pieces that make up our solution.  First, we have the Windows Form application.  This app is deployed using Click Once and calls SharePoint web services in order to upload files and then calls web services to set the meta data (SharePoint columns and permissions).  Second, we have a custom action.  The custom action is responsible for providing our users a link that will launch the Windows app, as well as passing values to it via the query string.  And lastly, we have the web services that the Windows Form application calls.  For our solution, we used both out of the box web services and a custom web service in order to set the column values in the document library as well as the permissions on the documents. Now, let’s look at the technical details of each of these pieces.  (All of the code is downloadable from here: )   Windows Form application deployed via Click Once The Windows Form application, called “Custom Upload”, has just a few classes in it: Custom Upload -- the form FileList.xsd -- the dataset used to track the names of the files and their meta data values SharePointUpload -- this class handles uploading the file SharePointUpload uses an HttpWebRequest to transfer the file to the web server. We had to change this code from a WebClient object to the HttpWebRequest object, because we needed to be able to set the time out value.  public bool UploadDocument(string localFilename, string remoteFilename) { bool result = true; //Need to use an HttpWebRequest object instead of a WebClient object // so we can set the timeout (WebClient doesn't allow you to set the timeout!) HttpWebRequest req = (HttpWebRequest)WebRequest.Create(remoteFilename); try { req.Method = "PUT"; req.Timeout = 60 * 1000; //convert seconds to milliseconds req.AllowWriteStreamBuffering = true; req.Credentials = System.Net.CredentialCache.DefaultCredentials; req.SendChunked = false; req.KeepAlive = true; Stream reqStream = req.GetRequestStream(); FileStream rdr = new FileStream(localFilename, FileMode.Open, FileAccess.Read); byte[] inData = new byte[4096]; int bytesRead = rdr.Read(inData, 0, inData.Length); while (bytesRead > 0) { reqStream.Write(inData, 0, bytesRead); bytesRead = rdr.Read(inData, 0, inData.Length); } reqStream.Close(); rdr.Close(); System.Net.HttpWebResponse response = (HttpWebResponse)req.GetResponse(); if (response.StatusCode != HttpStatusCode.OK && response.StatusCode != HttpStatusCode.Created) { String msg = String.Format("An error occurred while uploading this file: {0}\n\nError response code: {1}", System.IO.Path.GetFileName(localFilename), response.StatusCode.ToString()); LogWarning(msg, "2ACFFCCA-59BA-40c8-A9AB-05FA3331D223"); result = false; } } catch (Exception ex) { LogException(ex, "{E9D62A93-D298-470d-A6BA-19AAB237978A}"); result = false; } return result; } The class also contains the LogException() and LogWarning() methods. When the application is launched, it parses the query string for some initial values.  The query string looks like this: string queryString = "Srv=clickonce&Sec=N&Doc=DMI&SiteName=&Speed=128000&Max=50"; This Srv is the path to the server (my Virtual Machine is name “clickonce”), the Sec is short for security – meaning HTTPS or HTTP, the Doc is the shortcut for which document library to use, and SiteName is the name of the SharePoint site.  Speed is used to calculate an estimate for download speed for each file.  We added this so our users uploading documents would realize how long it might take for clients in remote locations (using slow WAN connections) to download the documents. The last value, Max, is the maximum size that the SharePoint site will allow documents to be.  This allowed us to give users a warning that a file is too large before we even attempt to upload it. Another critical piece is the meta data collection.  We organized our site using SharePoint content types, so when the app loads, it gets a list of the document library’s content types.  The user then select one of the content types from the drop down list, and then we query SharePoint to get a list of the fields that make up that content type.  We used both an out of the box web service, and one that we custom built, in order to get these values. Once we have the content type fields, we then add controls to the form.  Which type of control we add depends on the data type of the field.  (DateTime pickers for date/time fields, etc)  We didn’t write code to cover every data type, since we were working with a limited set of content types and field data types. Here’s a screen shot of the Form, before and after someone has selected the content types and our code has added the custom controls:     The other piece of meta data we collect is the in the upper right corner of the app, “Users with access”.  This box lists the different SharePoint Groups that we have set up and by checking the boxes, the user can set the permissions on the uploaded documents. All of this meta data is collected and submitted to our custom web service, which then sets the values on the documents on the list.  We’ll look at these web services in a future post. In the next post, we’ll walk through the Custom Action we built.

    Read the article

  • Accurately display upload progress in Silverilght upload

    - by Matt
    I'm trying to debug a file upload / download issue I'm having. I've got a Silverlight file uploader, and to transmit the files I make use of the HttpWebRequest class. So I create a connection to my file upload handler on the server and begin transmitting. While a file uploads I keep track of total bytes written to the RequestStream so I can figure out a percentage. Now working at home I've got a rather slow connection, and I think Silverlight, or the browser, is lying to me. It seems that my upload progress logic is inaccurate. When I do multiple file uploads (24 images of 3-6mb big in my testing), the logic reports the files finish uploading but I believe that it only reflects the progress of written bytes to the RequestStream, not the actual amount of bytes uploaded. What is the most accurate way to measure upload progress. Here's the logic I'm using. public void Upload() { if( _TargetFile != null ) { Status = FileUploadStatus.Uploading; Abort = false; long diff = _TargetFile.Length - BytesUploaded; UriBuilder ub = new UriBuilder( App.siteUrl + "upload.ashx" ); bool complete = diff <= ChunkSize; ub.Query = string.Format( "{3}name={0}&StartByte={1}&Complete={2}", fileName, BytesUploaded, complete, string.IsNullOrEmpty( ub.Query ) ? "" : ub.Query.Remove( 0, 1 ) + "&" ); HttpWebRequest webrequest = ( HttpWebRequest ) WebRequest.Create( ub.Uri ); webrequest.Method = "POST"; webrequest.BeginGetRequestStream( WriteCallback, webrequest ); } } private void WriteCallback( IAsyncResult asynchronousResult ) { HttpWebRequest webrequest = ( HttpWebRequest ) asynchronousResult.AsyncState; // End the operation. Stream requestStream = webrequest.EndGetRequestStream( asynchronousResult ); byte[] buffer = new Byte[ 4096 ]; int bytesRead = 0; int tempTotal = 0; Stream fileStream = _TargetFile.OpenRead(); fileStream.Position = BytesUploaded; while( ( bytesRead = fileStream.Read( buffer, 0, buffer.Length ) ) != 0 && tempTotal + bytesRead < ChunkSize && !Abort ) { requestStream.Write( buffer, 0, bytesRead ); requestStream.Flush(); BytesUploaded += bytesRead; tempTotal += bytesRead; int percent = ( int ) ( ( BytesUploaded / ( double ) _TargetFile.Length ) * 100 ); UploadPercent = percent; if( UploadProgressChanged != null ) { UploadProgressChangedEventArgs args = new UploadProgressChangedEventArgs( percent, bytesRead, BytesUploaded, _TargetFile.Length, _TargetFile.Name ); SmartDispatcher.BeginInvoke( () => UploadProgressChanged( this, args ) ); } } //} // only close the stream if it came from the file, don't close resizestream so we don't have to resize it over again. fileStream.Close(); requestStream.Close(); webrequest.BeginGetResponse( ReadCallback, webrequest ); }

    Read the article

  • Downloading attachments from Exchange with WebDAV

    - by arturito
    Hi there! I've been trying to retrive attachment from message in Exchange server using WebDAV.I don't know which version of Exchange the company is running. I'can successfully read messages and retrive list of attachments. However I am failing to save attachments. In both cases errors is: "The remote server returned an error: <403 Forbidden. Any idea what I'm doing wrong? My code: static void Main(string[] args) { HttpWebRequest Request; WebResponse Response; CredentialCache MyCredentialCache; string attachment = "http://mailserver/Exchange/Username/Inbox/Test.EML/Test.txt"; string strUserName = "username"; string strPassword = "password"; string strDomain = "domain"; try { // HttpWebRequest MyCredentialCache = new System.Net.CredentialCache(); MyCredentialCache.Add(new System.Uri(attachment), "NTLM", new NetworkCredential(strUserName, strPassword, strDomain)); Request = (HttpWebRequest)HttpWebRequest.Create(attachment); Request.Credentials = MyCredentialCache; Request.Method = "GET"; Response = (HttpWebResponse)Request.GetResponse(); } catch(Exception ex) { Console.WriteLine(ex.Message.ToString()); } try { //Web Client string downloadPath = "D:\\Downloads"; WebClient wcClient = new WebClient(); wcClient.Credentials = new NetworkCredential(strUserName, strPassword, strDomain); string file = Path.GetFileName(attachment); string filename = Path.Combine(downloadPath, file); wcClient.DownloadFile(attachment, filename); } catch (Exception ex) { Console.WriteLine(ex.Message.ToString()); } Console.ReadLine(); }

    Read the article

  • Asp.net Crawler Webresponse Operation Timed out.

    - by Leon
    Hi I have built a simple threadpool based web crawler within my web application. Its job is to crawl its own application space and build a Lucene index of every valid web page and their meta content. Here's the problem. When I run the crawler from a debug server instance of Visual Studio Express, and provide the starting instance as the IIS url, it works fine. However, when I do not provide the IIS instance and it takes its own url to start the crawl process(ie. crawling its own domain space), I get hit by operation timed out exception on the Webresponse statement. Could someone please guide me into what I should or should not be doing here? Here is my code for fetching the page. It is executed in the multithreaded environment. private static string GetWebText(string url) { string htmlText = ""; HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url); request.UserAgent = "My Crawler"; using (WebResponse response = request.GetResponse()) { using (Stream stream = response.GetResponseStream()) { using (StreamReader reader = new StreamReader(stream)) { htmlText = reader.ReadToEnd(); } } } return htmlText; } And the following is my stacktrace: at System.Net.HttpWebRequest.GetResponse() at CSharpCrawler.Crawler.GetWebText(String url) in c:\myAppDev\myApp\site\App_Code\CrawlerLibs\Crawler.cs:line 366 at CSharpCrawler.Crawler.CrawlPage(String url, List1 threadCityList) in c:\myAppDev\myApp\site\App_Code\CrawlerLibs\Crawler.cs:line 105 at CSharpCrawler.Crawler.CrawlSiteBuildIndex(String hostUrl, String urlToBeginSearchFrom, List1 threadCityList) in c:\myAppDev\myApp\site\App_Code\CrawlerLibs\Crawler.cs:line 89 at crawler_Default.threadedCrawlSiteBuildIndex(Object threadedCrawlerObj) in c:\myAppDev\myApp\site\crawler\Default.aspx.cs:line 108 at System.Threading.QueueUserWorkItemCallback.WaitCallback_Context(Object state) at System.Threading.ExecutionContext.runTryCode(Object userData) at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData) at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx) at System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem() at System.Threading.ThreadPoolWorkQueue.Dispatch() at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback() Thanks and cheers, Leon.

    Read the article

  • how to get response from remote server

    - by ruhit
    I have made a desktop application in asp.net using c# that connecting with remote server.I am able to connect but how do i show that my login is successful or not. After that i want to retrieve data from the remote server..........so plz help me.I have written the below code..............is there any better way try { string strId = UserId_TextBox.Text; string strpasswrd = Password_TextBox.Text; ASCIIEncoding encoding = new ASCIIEncoding(); string postData = "UM_email=" + strId; postData += ("&UM_password=" + strpasswrd); byte[] data = encoding.GetBytes(postData); MessageBox.Show(postData); // Prepare web request... //HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create("http://localhost/ruhit/basic_framework/index.php?menu=login=" + postData); HttpWebRequest myRequest =(HttpWebRequest)WebRequest.Create("http://www.facebook.com/login.php=" + postData); myRequest.Method = "POST"; myRequest.ContentType = "application/x-www-form-urlencoded"; myRequest.ContentLength = data.Length; Stream newStream = myRequest.GetRequestStream(); // Send the data. newStream.Write(data, 0, data.Length); MessageBox.Show("u r now connected"); HttpWebResponse response = (HttpWebResponse)myRequest.GetResponse(); // WebResponse response = myRequest.GetResponse(); StreamReader reader = new StreamReader(response.GetResponseStream()); string str = reader.ReadLine(); while (str != null) { str = reader.ReadLine(); MessageBox.Show(str); } reader.Close(); newStream.Close(); } catch { MessageBox.Show("error connecting"); }

    Read the article

< Previous Page | 5 6 7 8 9 10 11 12 13 14 15 16  | Next Page >