Search Results

Search found 349 results on 14 pages for 'webrequest'.

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

  • Silverlight 4 Twitter Client &ndash; Part 5

    - by Max
    In this post, we will look at implementing the following in our twitter client - displaying the profile picture in the home page after logging in. So to accomplish this, we will need to do the following steps. 1) First of all, let us create another field in our Global variable static class to hold the profile image url. So just create a static string field in that. public static string profileImage { get; set; } 2) In the Login.xaml.cs file, before the line where we redirect to the Home page if the login was successful. Create another WebClient request to fetch details from this url - .xml">http://api.twitter.com/1/users/show/<TwitterUsername>.xml I am interested only in the “profile_image_url” node in this xml string returned. You can choose what ever field you need – the reference to the Twitter API Documentation is here. 3) This particular url does not require any authentication so no need of network credentials for this and also the useDefaultCredentials will be true. So this code would look like. WebRequest.RegisterPrefix("http://", System.Net.Browser.WebRequestCreator.ClientHttp); WebClient myService = new WebClient(); myService.AllowReadStreamBuffering = myService.UseDefaultCredentials = true; myService.DownloadStringCompleted += new DownloadStringCompletedEventHandler(TimelineRequestCompleted_User);) myService.DownloadStringAsync(new Uri("http://api.twitter.com/1/users/show/" + TwitterUsername.Text + ".xml")); 4) To parse the xml file returned by this and get the value of the “profile_image_url” node, the LINQ code will look something like XDocument xdoc; xdoc = XDocument.Parse(e.Result); var answer = (from status in xdoc.Descendants("user") select status.Element("profile_image_url").Value); GlobalVariable.profileImage = answer.First().ToString(); 5) After this, we can then redirect to Home page completing our login formalities. 6) In the home page, add a image tag and give it a name, something like <Image Name="image1" Stretch="Fill" Margin="29,29,0,0" Height="73" VerticalAlignment="Top" HorizontalAlignment="Left" Width="73" /> 7) In the OnNavigated to event in home page, we can set the image source url as below image1.Source = new BitmapImage(new Uri(GlobalVariable.profileImage, UriKind.Absolute)); Hope this helps. If you have any queries / suggestions, please feel free to comment below or contact me. Technorati Tags: Silverlight,LINQ,Twitter API,Twitter

    Read the article

  • Code won't work under mono, any ideas whats wrong?

    - by JL
    Mono won't fire the following code: I get internal server error 500, error writing request error. Code works perfectly under normal .net.... any ideas why its broken and how to fix it? [WebServiceBinding] public class testService : System.Web.Services.Protocols.SoapHttpClientProtocol { private string DummySoapRequest = @"<?xml version=""1.0"" encoding=""utf-8""?> <soap:Envelope xmlns:soap=""http://schemas.xmlsoap.org/soap/envelope/"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema""> <soap:Body> <DummyOperation xmlns=""http://mynamespace.com""> </DummyOperation> </soap:Body> </soap:Envelope>"; public void SendDummyRequest() { System.Net.WebRequest req = GetWebRequest(new Uri(Url)); req.Headers.Add("SOAPAction", ""); req.ContentType = "text/xml;charset=\"utf-8\""; req.Method = "POST"; using (Stream stm = req.GetRequestStream()) { using (StreamWriter stmw = new StreamWriter(stm)) { stmw.Write(DummySoapRequest); } } System.Net.WebResponse response = req.GetResponse(); } }

    Read the article

  • C# 5 Async, Part 3: Preparing Existing code For Await

    - by Reed
    While the Visual Studio Async CTP provides a fantastic model for asynchronous programming, it requires code to be implemented in terms of Task and Task<T>.  The CTP adds support for Task-based asynchrony to the .NET Framework methods, and promises to have these implemented directly in the framework in the future.  However, existing code outside the framework will need to be converted to using the Task class prior to being usable via the CTP. Wrapping existing asynchronous code into a Task or Task<T> is, thankfully, fairly straightforward.  There are two main approaches to this. Code written using the Asynchronous Programming Model (APM) is very easy to convert to using Task<T>.  The TaskFactory class provides the tools to directly convert APM code into a method returning a Task<T>.  This is done via the FromAsync method.  This method takes the BeginOperation and EndOperation methods, as well as any parameters and state objects as arguments, and returns a Task<T> directly. For example, we could easily convert the WebRequest BeginGetResponse and EndGetResponse methods into a method which returns a Task<WebResponse> via: Task<WebResponse> task = Task.Factory .FromAsync<WebResponse>( request.BeginGetResponse, request.EndGetResponse, null); .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } Event-based Asynchronous Pattern (EAP) code can also be wrapped into a Task<T>, though this requires a bit more effort than the one line of code above.  This is handled via the TaskCompletionSource<T> class.  MSDN provides a detailed example of using this to wrap an EAP operation into a method returning Task<T>.  It demonstrates handling cancellation and exception handling as well as the basic operation of the asynchronous method itself. The basic form of this operation is typically: Task<YourResult> GetResultAsync() { var tcs = new TaskCompletionSource<YourResult>(); // Handle the event, and setup the task results... this.GetResultCompleted += (o,e) => { if (e.Error != null) tcs.TrySetException(e.Error); else if (e.Cancelled) tcs.TrySetCanceled(); else tcs.TrySetResult(e.Result); }; // Call the asynchronous method this.GetResult(); // Return the task from the TaskCompletionSource return tcs.Task; } We can easily use these methods to wrap our own code into a method that returns a Task<T>.  Existing libraries which cannot be edited can be extended via Extension methods.  The CTP uses this technique to add appropriate methods throughout the framework. The suggested naming for these methods is to define these methods as “Task<YourResult> YourClass.YourOperationAsync(…)”.  However, this naming often conflicts with the default naming of the EAP.  If this is the case, the CTP has standardized on using “Task<YourResult> YourClass.YourOperationTaskAsync(…)”. Once we’ve wrapped all of our existing code into operations that return Task<T>, we can begin investigating how the Async CTP can be used with our own code.

    Read the article

  • uploading large xml to WCF REST service -> 400 Bad request

    - by glenn.danthi
    I am trying to upload large xml files to a REST service... I have tried almost all methods specified on stackoverflow on google but I still cant find out where I am going wrong....I cannot upload a file greater than 64 kb!.. I have specified the maxRequestLength : <httpRuntime maxRequestLength="65536"/> and my binding config is as follows : <bindings> <webHttpBinding> <binding name="RESTBinding" maxBufferSize="67108864" maxReceivedMessageSize="67108864" openTimeout="00:10:00" receiveTimeout="00:10:00" sendTimeout="00:10:00"> <readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647"/> </binding> </webHttpBinding> </bindings> In my C# client side I am doing the following : WebRequest request = HttpWebRequest.Create(@"http://localhost.:2381/RepositoryServices.svc/deviceprofile/AddDdxml"); request.Credentials = new NetworkCredential("blah", "blah"); request.Method = "POST"; request.ContentType = "application/xml"; request.ContentLength = byteArray.LongLength; using (Stream postStream = request.GetRequestStream()) { postStream.Write(byteArray, 0, byteArray.Length); } There is no special configuration done on the client side...

    Read the article

  • PayPal IPN Response

    - by Gorkem Tolan
    I am having a problem with PayPal IPN response. After payment is made by the customer, PayPal IPN returns this URL: www.mywebsite.com?orderid=32&tx=2AC67201DL3533325&st=Pending&amt=2.50&cc=USD&cm=&item_number=32 There are a couple of issues Post-back field names are undefined or missing. Thus I can get the INVALID message. I am not sure if my website does not read POST variables. When I looked at IPN history, it shows that each IPN has been sent with the complete url. Payment status keeps coming Pending. Does this issue cause the first issue? Thank you for your responses in advance. Here is the code: Dim strSandbox As String, strLive As String Dim req As HttpWebRequest strSandbox = "http://www.sandbox.paypal.com/cgi-bin/webscr/" strLive = "https://www.paypal.com/cgi-bin/webscr" req = CType(WebRequest.Create(strSandbox), HttpWebRequest) 'Set values for the request back req.Method = "POST" req.ContentType = "application/x-www-form-urlencoded" Dim param() As Byte param = Request.BinaryRead(HttpContext.Current.Request.ContentLength) Dim strRequest As String strRequest = Encoding.ASCII.GetString(param) strRequest = strRequest & "&cmd=_notify-validate" req.ContentLength = strRequest.Length 'Response.Write(strRequest) 'Send the request to PayPal and get the response Dim streamOut As StreamWriter streamOut = New StreamWriter(req.GetRequestStream(), System.Text.Encoding.ASCII) streamOut.Write(strRequest) streamOut.Close() Dim streamIn As StreamReader streamIn = New StreamReader(req.GetResponse().GetResponseStream()) Dim strResponse As String strResponse = streamIn.ReadToEnd() Response.Write(strResponse) streamIn.Close() If (strResponse = "VERIFIED") Then Response.Redirect("thankyou.aspx") ElseIf (strResponse = "INVALID") Then End If

    Read the article

  • System.Net.WebException: The remote server returned an error: (405) Method Not Allowed .exception occurred during the execution of the web request

    - by user88
    When I ran my web application code I got this error on this line. using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()){} Actually when I ran my url directly on browser.It will give proper o/p but when I ran my url in code. It will give exception. Here MyCode is :- string service = "http://api.ean.com/ean-services/rs/hotel/"; string version = "v3/"; string method = "info/"; string hotelId1 = "188603"; int hotelId = Convert.ToInt32(hotelId1); string otherElemntsStr = "&cid=411931&minorRev=[12]&customerUserAgent=[hotel]&locale=en_US&currencyCode=INR"; string apiKey = "tzyw4x2zspckjayrbjekb397"; string sig = "a6f828b696ae6a9f7c742b34538259b0"; string url = service + version + method + "?&type=xml" + "&apiKey=" + apiKey + "&sig=" + sig + otherElemntsStr + "&hotelId=" + hotelId; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url) as HttpWebRequest; request.Method = "POST"; request.ContentType = "text/xml"; request.ContentLength = 0; XmlDocument xmldoc = new XmlDocument(); using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { StreamReader responsereader = new StreamReader(response.GetResponseStream()); var responsedata = responsereader.ReadToEnd(); xmldoc = (XmlDocument)JsonConvert.DeserializeXmlNode(responsedata); xmldoc.Save(@"D:\FlightSearch\myfile.xml"); xmldoc.Load(@"D:\FlightSearch\myfile.xml"); DataSet ds = new DataSet(); ds.ReadXml(Request.PhysicalApplicationPath + "myfile.xml"); GridView1.DataSource = ds.Tables["HotelSummary"]; GridView1.DataBind(); }

    Read the article

  • Blob container creation exception ...

    - by Egon
    I get an exception every time I try to create a container for the blob using the following code blobStorageType = storageAccInfo.CreateCloudBlobClient(); ContBlob = blobStorageType.GetContainerReference(containerName); //everything fine till here ; next line creates an exception ContBlob.CreateIfNotExist(); Microsoft.WindowsAzure.StorageClient.StorageClientException was unhandled Message="One of the request inputs is out of range." Source="Microsoft.WindowsAzure.StorageClient" StackTrace: at Microsoft.WindowsAzure.StorageClient.Tasks.Task1.get_Result() at Microsoft.WindowsAzure.StorageClient.Tasks.Task1.ExecuteAndWait() at Microsoft.WindowsAzure.StorageClient.TaskImplHelper.ExecuteImplWithRetry[T](Func2 impl, RetryPolicy policy) at Microsoft.WindowsAzure.StorageClient.CloudBlobContainer.CreateIfNotExist(BlobRequestOptions options) at Microsoft.WindowsAzure.StorageClient.CloudBlobContainer.CreateIfNotExist() at WebRole1.BlobFun..ctor() in C:\Users\cloud\Documents\Visual Studio 2008\Projects\CloudBlob\WebRole1\BlobFun.cs:line 58 at WebRole1.BlobFun.calling1() in C:\Users\cloud\Documents\Visual Studio 2008\Projects\CloudBlob\WebRole1\BlobFun.cs:line 29 at AzureBlobTester.Program.Main(String[] args) in C:\Users\cloud\Documents\Visual Studio 2008\Projects\CloudBlob\AzureBlobTester\Program.cs:line 19 at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args) at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args) at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly() at System.Threading.ThreadHelper.ThreadStart_Context(Object state) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Threading.ThreadHelper.ThreadStart() InnerException: System.Net.WebException Message="The remote server returned an error: (400) Bad Request." Source="System" StackTrace: at System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult) at Microsoft.WindowsAzure.StorageClient.EventHelper.ProcessWebResponse(WebRequest req, IAsyncResult asyncResult, EventHandler1 handler, Object sender) InnerException: Do you guys knw what is it that I am doing wrong ?

    Read the article

  • The server returned an address in response to the PASV command that is different than the address to

    - by senzacionale
    {System.Net.WebException: The server returned an address in response to the PASV command that is different than the address to which the FTP connection was made. at System.Net.FtpWebRequest.CheckError() at System.Net.FtpWebRequest.SyncRequestCallback(Object obj) at System.Net.CommandStream.Abort(Exception e) at System.Net.FtpWebRequest.FinishRequestStage(RequestStage stage) at System.Net.FtpWebRequest.GetRequestStream() at BackupDB.Program.FTPUploadFile(String serverPath, String serverFile, FileInfo LocalFile, NetworkCredential Cred) in D:\PROJEKTI\BackupDB\BackupDB\Program.cs:line 119} code: FTPMakeDir(new Uri(serverPath + "/"), Cred); FtpWebRequest request = (FtpWebRequest)WebRequest.Create(serverPath + serverFile); request.UsePassive = true; request.Method = WebRequestMethods.Ftp.UploadFile; request.Credentials = Cred; byte[] buffer = new byte[10240]; // Read/write 10kb using (FileStream sourceStream = new FileStream(LocalFile.ToString(), FileMode.Open)) { using (Stream requestStream = request.GetRequestStream()) { int bytesRead; do { bytesRead = sourceStream.Read(buffer, 0, buffer.Length); requestStream.Write(buffer, 0, bytesRead); } while (bytesRead > 0); } response = (FtpWebResponse)request.GetResponse(); response.Close(); }

    Read the article

  • DotNetOpenAuth RelayParty not working on load balanced cluster

    - by Garth
    We're trying to move an ASP.NET MVC application, which uses DotNetOpenAuth OpenID Version 3.4.1, from a single server web garden to a physical server cluster held behind a hardware load balancer. Our old setup (OpenID RP working): Browser = SHTTP = Server = WebGarden = Nonce/Session Store Our new setup (OpenID RP not working): Browser = SHTTP = Load Balancer = HTTP = Cluster Node = WebGarden = Nonce/Session Store DB When we authenticate with the new setup we are correctly redirected to the OpenID Provider but after authenticated we are redirected back to our cluster (relay party) and get the following exception: Exception DotNetOpenAuth.Messaging.ProtocolException: Redirects on POST requests that are to untrusted servers is not supported. at DotNetOpenAuth.Messaging.ErrorUtilities.VerifyProtocol(Boolean condition, String message, Object[] args) in c:\TeamCity\buildAgent\work\bf9e2ca68b75a334\src\DotNetOpenAuth\Messaging\ErrorUtilities.cs:line 235 at DotNetOpenAuth.Messaging.UntrustedWebRequestHandler.GetResponse(HttpWebRequest request, DirectWebRequestOptions options) in c:\TeamCity\buildAgent\work\bf9e2ca68b75a334\src\DotNetOpenAuth\Messaging\UntrustedWebRequestHandler.cs:line 258 at DotNetOpenAuth.OpenId.ChannelElements.OpenIdChannel.GetDirectResponse(HttpWebRequest webRequest) in c:\TeamCity\buildAgent\work\bf9e2ca68b75a334\src\DotNetOpenAuth\OpenId\ChannelElements\OpenIdChannel.cs:line 277 at DotNetOpenAuth.Messaging.Channel.RequestCore(IDirectedProtocolMessage request) in c:\TeamCity\buildAgent\work\bf9e2ca68b75a334\src\DotNetOpenAuth\Messaging\Channel.cs:line 542 at DotNetOpenAuth.Messaging.Channel.Request(IDirectedProtocolMessage requestMessage) in c:\TeamCity\buildAgent\work\bf9e2ca68b75a334\src\DotNetOpenAuth\Messaging\Channel.cs:line 425 at DotNetOpenAuth.Messaging.Channel.Request[TResponse](IDirectedProtocolMessage requestMessage) in c:\TeamCity\buildAgent\work\bf9e2ca68b75a334\src\DotNetOpenAuth\Messaging\Channel.cs:line 405 at DotNetOpenAuth.OpenId.ChannelElements.SigningBindingElement.ProcessIncomingMessage(IProtocolMessage message) in c:\TeamCity\buildAgent\work\bf9e2ca68b75a334\src\DotNetOpenAuth\OpenId\ChannelElements\SigningBindingElement.cs:line 154 at DotNetOpenAuth.Messaging.Channel.ProcessIncomingMessage(IProtocolMessage message) in c:\TeamCity\buildAgent\work\bf9e2ca68b75a334\src\DotNetOpenAuth\Messaging\Channel.cs:line 992 at DotNetOpenAuth.OpenId.ChannelElements.OpenIdChannel.ProcessIncomingMessage(IProtocolMessage message) in c:\TeamCity\buildAgent\work\bf9e2ca68b75a334\src\DotNetOpenAuth\OpenId\ChannelElements\OpenIdChannel.cs:line 172 at DotNetOpenAuth.Messaging.Channel.ReadFromRequest(HttpRequestInfo httpRequest) in c:\TeamCity\buildAgent\work\bf9e2ca68b75a334\src\DotNetOpenAuth\Messaging\Channel.cs:line 386 at DotNetOpenAuth.OpenId.RelyingParty.OpenIdRelyingParty.GetResponse(HttpRequestInfo httpRequestInfo) in c:\TeamCity\buildAgent\work\bf9e2ca68b75a334\src\DotNetOpenAuth\OpenId\RelyingParty\OpenIdRelyingParty.cs:line 501 We have added a machines involved into the trusted machine list and turned off requires ssl but it makes no difference. We even tried removing out nonce store and using a stateless connection, but that didn't work either. We always get the same error. We suspected the issue is arising as a result of the cluster node having a different IP from the load balancer when it connects to the OpenID Provider, but we're not sure. Any ideas?

    Read the article

  • HTTPWebResponse returning no content

    - by Richard Yale
    Our company works with another company called iMatrix and they have an API for creating our own forms. They have confirmed that our request is hitting their servers but a response is supposed to come back in 1 of a few ways determined by a parameter. I'm getting a 200 OK response back but no content and a content-length of 0 in the response header. here is the url: https://secure4.office2office.com/designcenter/api/imx_api_call.asp I'm using this class: namespace WebSumit { public enum MethodType { POST = 0, GET = 1 } public class WebSumitter { public WebSumitter() { } public string Submit(string URL, Dictionary<string, string> Parameters, MethodType Method) { StringBuilder _Content = new StringBuilder(); string _ParametersString = ""; // Prepare Parameters String foreach (KeyValuePair<string, string> _Parameter in Parameters) { _ParametersString = _ParametersString + (_ParametersString != "" ? "&" : "") + string.Format("{0}={1}", _Parameter.Key, _Parameter.Value); } // Initialize Web Request HttpWebRequest _Request = (HttpWebRequest)WebRequest.Create(URL); // Request Method _Request.Method = Method == MethodType.POST ? "POST" : (Method == MethodType.GET ? "GET" : ""); _Request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Win32)"; // Send Request using (StreamWriter _Writer = new StreamWriter(_Request.GetRequestStream(), Encoding.UTF8)) { _Writer.Write(_ParametersString); } // Initialize Web Response HttpWebResponse _Response = (HttpWebResponse)_Request.GetResponse(); // Get Response using (StreamReader _Reader = new StreamReader(_Response.GetResponseStream(), Encoding.UTF8)) { _Content.Append(_Reader.ReadToEnd()); } return _Content.ToString(); } } } I cannot post the actual parameters because they are to the live system, but can you look at this code and see if there is anything that is missing? Thanks!

    Read the article

  • File Upload with HttpWebRequest doesn't post the file

    - by Sri Kumar
    Hello All, Here is my code to post the file. I use asp fileupload control to get the file stream. HttpWebRequest requestToSender = (HttpWebRequest)WebRequest.Create("http://localhost:2518/Web/CrossPage.aspx"); requestToSender.Method = "POST"; requestToSender.ContentType = "multipart/form-data"; requestToSender.KeepAlive = true; requestToSender.Credentials = System.Net.CredentialCache.DefaultCredentials; requestToSender.ContentLength = BtnUpload.PostedFile.ContentLength; BinaryReader binaryReader = new BinaryReader(BtnUpload.PostedFile.InputStream); byte[] binData = binaryReader.ReadBytes(BtnUpload.PostedFile.ContentLength); Stream requestStream = requestToSender.GetRequestStream(); requestStream.Write(binData, 0, binData.Length); requestStream.Close(); HttpWebResponse responseFromSender = (HttpWebResponse)requestToSender.GetResponse(); string fromSender = string.Empty; using (StreamReader responseReader = new StreamReader(responseFromSender.GetResponseStream())) { fromSender = responseReader.ReadToEnd(); } XMLString.Text = fromSender; In the page load of CrossPage.aspx i have the following code NameValueCollection postPageCollection = Request.Form; foreach (string name in postPageCollection.AllKeys) { Response.Write(name + " " + postPageCollection[name]); } HttpFileCollection postCollection = Request.Files; foreach (string name in postCollection.AllKeys) { HttpPostedFile aFile = postCollection[name]; aFile.SaveAs(Server.MapPath(".") + "/" + Path.GetFileName(aFile.FileName)); } string strxml = "sample"; Response.Clear(); Response.Write(strxml); I don't get the file in Request.Files. The byte array is created. What was wrong with my HttpWebRequest?

    Read the article

  • HttpWebRequest does has empty response requesting a search from Bing

    - by Jarrod Maxwell
    I have the following code that sends a HttpWebRequest to Bing. When I request the url below though it returns what appears to be an empty response when it should be returning a list of results. var response = string.Empty; var httpWebRequest = WebRequest.Create("http://www.bing.com/search?q=stackoverflow&count=100") as HttpWebRequest; httpWebRequest.Method = WebRequestMethods.Http.Get; httpWebRequest.Headers.Add("Accept-Language", "en-US"); httpWebRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Win32)"; httpWebRequest.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate"); using (var httpWebResponse = httpWebRequest.GetResponse() as HttpWebResponse) { Stream stream = null; using (stream = httpWebResponse.GetResponseStream()) { if (httpWebResponse.ContentEncoding.ToLower().Contains("gzip")) stream = new GZipStream(stream, CompressionMode.Decompress); else if (httpWebResponse.ContentEncoding.ToLower().Contains("deflate")) stream = new DeflateStream(stream, CompressionMode.Decompress); var streamReader = new StreamReader(stream, Encoding.UTF8); response = streamReader.ReadToEnd(); } } Its pretty standard code for requesting and receiving a web page. Any ideas why the response is empty? Thanks in advance. EDIT I left off a query string parameter in the url. I also had &count=100 which I have now corrected. It seems to work for values of 50 and below but returns nothing when larger. This works ok when in the browser, but not for this web request. It makes me think the issue is that the response is large and HttpWebResponse is not handling that for me the way I have it set up. Just a guess though.

    Read the article

  • Simulate Windows Service with ASP.NET

    - by Bayonian
    Hi, I have small web app that generate PDF files as a report. I'm trying to delete those generated PDF files after 10 sec that they are generated. What I want to do is to read a folder with PDF files every 10 sec, and delete all the PDF files inside that folder. I read this post of Easy Background Tasks in ASP.NET. The following code is the VB version. Protected Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs) AddTask("DoStuff", 10) End Sub Private Sub AddTask(ByVal name As String, ByVal seconds As Integer) OnCacheRemove = New CacheItemRemovedCallback(CacheItemRemoved) HttpRuntime.Cache.Insert(name, seconds, Nothing, DateTime.Now.AddSeconds(seconds), Cache.NoSlidingExpiration, CacheItemPriority.NotRemovable, _ OnCacheRemove) End Sub Public Sub CacheItemRemoved(ByVal k As String, ByVal v As Object, ByVal r As CacheItemRemovedReason) ' do stuff here if it matches our taskname, like WebRequest DeletePDFilesInFoler() ' re-add our task so it recurs AddTask(k, Convert.ToInt32(v)) End Sub But I got this error Delegate 'System.Web.Caching.CacheItemRemovedCallback' requires an 'AddressOf' expression or lambda expression as the only argument to its constructor. If this code works, where I should put it. Right, now I'm putting it in the master page. How to get this error out? Thank you

    Read the article

  • Programmatically call webmethods in C#

    - by hancock
    I'm trying to write a function that can call a webmethod from a webserive given the method's name and URL of the webservice. I've found some code on a blog that does this just fine except for one detail. It requires that the request XML be provided as well. The goal here is to get the request XML template from the webservice itself. I'm sure this is possible somehow because I can see both the request and response XML templates if I access a webservice's URL in my browser. This is the code which calls the webmethod programmatically: XmlDocument doc = new XmlDocument(); //this is the problem. I need to get this automatically doc.Load("../../request.xml"); HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://localhost/dummyws/dummyws.asmx?op=HelloWorld"); req.ContentType = "text/xml;charset=\"utf-8\""; req.Accept = "text/xml"; req.Method = "POST"; Stream stm = req.GetRequestStream(); doc.Save(stm); stm.Close(); WebResponse resp = req.GetResponse(); stm = resp.GetResponseStream(); StreamReader r = new StreamReader(stm); Console.WriteLine(r.ReadToEnd());

    Read the article

  • Encoding issue - 2nd band of ISO-8859-1 values do not get encoded?

    - by bstack
    Hello, I want to send the pound sign character i.e. '£' encoded as ISO-8859-1 across the wire. I perform this by doing the following: var _encoding = Encoding.GetEncoding("iso-8859-1"); var _requestContent = _encoding.GetBytes(requestContent); var _request = (HttpWebRequest)WebRequest.Create(target); _request.Headers[HttpRequestHeader.ContentEncoding] = _encoding.WebName; _request.Method = "POST"; _request.ContentType = "application/x-www-form-urlencoded; charset=iso-8859-1"; _request.ContentLength = _requestContent.Length; _requestStream = _request.GetRequestStream(); _requestStream.Write(_requestContent, 0, _requestContent.Length); _requestStream.Flush(); _requestStream.Close(); When I put a breakpoint at the target, I expect to receive the following: '%a3', however I receive '%u00a3' instead. ISO-8859-1 is divided into 2 groups of characters: (ref: http://en.wikipedia.org/wiki/ISO_8859-1) The lower range 20 to 7E - is where all characters seem to be encoded correctly The higher range A0 to FF - is where all characters seem to encode to their Unicode equivalent value As '£' is in higher range A0 to FF, it gets encoded to %u00a3. In fact when I use the first few characters of the higher range A0 to FF i.e. '¡¢£¤¥¦§¨©ª«¬®', I get '%u00a1%u00a2%u00a3%u00a4%u00a5%u00a6%u00a7%u00a8%u00a9%u00aa%u00ab%u00ac%u00ae'. This behaviour is consistent. The question I have is why do characters in the higher range A0 to FF get encoded to their unicode value - and not to their equivalent ISO-8859-1 value? Help would be greatly appreciated... Billy

    Read the article

  • How to log in to a vbulletin forum with C#?

    - by Yustme
    Hi, I'm trying to log into a vbulletin forum. I got this far: private string login(string url, string username, string password) { string values = "vb_login_username={0}&vb_login_password={1}" values += "&securitytoken=guest&cookieuser=checked&do=login"; values = string.Format(values, username, password); HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url); CookieContainer a = new CookieContainer(); req.CookieContainer = a; System.Net.ServicePointManager.Expect100Continue = false; // prevents 417 error using (StreamWriter writer = new StreamWriter(req.GetRequestStream(), System.Text.Encoding.ASCII)) { writer.Write(values); } this.response = (HttpWebResponse)req.GetResponse(); StringBuilder output = new StringBuilder(); foreach (var cookie in response.Cookies) { output.Append(cookie.ToString()); output.Append(";"); } return output.ToString(); } It looks like i am getting logged in, but when i download the page, i can't find my username in it. Do you guys see anything that i might be doing wrong? Thanks in advance!

    Read the article

  • C# Client to Consume Google App Engine RESTful Webservice (rpc XML)

    - by Ngu Soon Hui
    I think I hit a problem when using C# client to consume Google App Engine Webservice. The Google App Engine code I use is here. This is how the python script on server would look like: from google.appengine.ext import webapp from google.appengine.ext.webapp.util import run_wsgi_app import logging from StringIO import StringIO import traceback import xmlrpclib from xmlrpcserver import XmlRpcServer class Application: def __init__(self): pass def getName(self,meta): return 'example' class XMLRpcHandler(webapp.RequestHandler): rpcserver = None def __init__(self): self.rpcserver = XmlRpcServer() app = Application() self.rpcserver.register_class('app',app) def post(self): request = StringIO(self.request.body) request.seek(0) response = StringIO() try: self.rpcserver.execute(request, response, None) except Exception, e: logging.error('Error executing: '+str(e)) for line in traceback.format_exc().split('\n'): logging.error(line) finally: response.seek(0) rstr = response.read() self.response.headers['Content-type'] = 'text/xml' self.response.headers['Content-length'] = "%d"%len(rstr) self.response.out.write(rstr) application = webapp.WSGIApplication( [('/xmlrpc/', XMLRpcHandler)], debug=True) def main(): run_wsgi_app(application) if __name__ == "__main__": main() The client side ( in Python) is this: import xmlrpclib s = xmlrpclib.Server('http://localhost:8080/xmlrpc/') print s.app.getName() I have no problem in using Python client to retrieve values from Google App Engine, but I do have difficulties in using a C# client to retrieve the values. The error I got was 404 method not found when I am trying to GetResponse from the web request. This is my code var request = (HttpWebRequest)WebRequest.Create("http://localhost:8080/xmlrpc/app"); request.Method = "GET"; request.ContentLength = 0; request.ContentType = "text/xml"; using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) //404 method not found error here. { } I think it must be that the url is wrong, but I don't know how to get it right. Any idea?

    Read the article

  • Payapl sandbox a/c in Dotnet..IPN Response Invaild

    - by Sam
    Hi, I am Integrating paypal to mysite.. i use sandbox account,One Buyer a/c and one more for seller a/c...and downloaded the below code from paypal site string strSandbox = "https://www.sandbox.paypal.com/cgi-bin/webscr"; HttpWebRequest req = (HttpWebRequest)WebRequest.Create(strSandbox); //Set values for the request back req.Method = "POST"; req.ContentType = "application/x-www-form-urlencoded"; byte[] param = Request.BinaryRead(HttpContext.Current.Request.ContentLength); string strRequest = Encoding.ASCII.GetString(param); strRequest += "&cmd=_notify-validate"; req.ContentLength = strRequest.Length; //for proxy //WebProxy proxy = new WebProxy(new Uri("http://url:port#")); //req.Proxy = proxy; //Send the request to PayPal and get the response StreamWriter streamOut = new StreamWriter(req.GetRequestStream(), System.Text.Encoding.ASCII); streamOut.Write(strRequest); streamOut.Close(); StreamReader streamIn = new StreamReader(req.GetResponse().GetResponseStream()); string strResponse = streamIn.ReadToEnd(); streamIn.Close(); if (strResponse == "VERIFIED") { //check the payment_status is Completed //check that txn_id has not been previously processed //check that receiver_email is your Primary PayPal email //check that payment_amount/payment_currency are correct //process payment } else if (strResponse == "INVALID") { //log for manual investigation } else { //log response/ipn data for manual investigation } and when add this snippets in pageload event of success page i get the ipn response as INVALID but amount paid successfully but i am getting invalid..any help..Paypal Docs in not Clear. thanks in advance

    Read the article

  • Paypal sandbox account in dotnet: "IPN Response invalid"

    - by Sam
    I am integrating Paypal with my website. I use a sandbox account, one buyer account and one seller account. I downloaded the code below from Paypal: string strSandbox = "https://www.sandbox.paypal.com/cgi-bin/webscr"; HttpWebRequest req = (HttpWebRequest)WebRequest.Create(strSandbox); //Set values for the request back req.Method = "POST"; req.ContentType = "application/x-www-form-urlencoded"; byte[] param = Request.BinaryRead(HttpContext.Current.Request.ContentLength); string strRequest = Encoding.ASCII.GetString(param); strRequest += "&cmd=_notify-validate"; req.ContentLength = strRequest.Length; //for proxy //WebProxy proxy = new WebProxy(new Uri("http://url:port#")); //req.Proxy = proxy; //Send the request to PayPal and get the response StreamWriter streamOut = new StreamWriter(req.GetRequestStream(), System.Text.Encoding.ASCII); streamOut.Write(strRequest); streamOut.Close(); StreamReader streamIn = new StreamReader(req.GetResponse().GetResponseStream()); string strResponse = streamIn.ReadToEnd(); streamIn.Close(); if (strResponse == "VERIFIED") { //check the payment_status is Completed //check that txn_id has not been previously processed //check that receiver_email is your Primary PayPal email //check that payment_amount/payment_currency are correct //process payment } else if (strResponse == "INVALID") { //log for manual investigation } else { //log response/ipn data for manual investigation } When I add this snippet in my pageload event of my success page, I show the IPN response as INVALID, but amount is paid successfully. Why is this? Paypal's docs are not clear.

    Read the article

  • FtpWebRequest Download File

    - by pm_2
    The following code is intended to retrieve a file via FTP. However, I'm getting an error with it. serverPath = "ftp://x.x.x.x/tmp/myfile.txt"; FtpWebRequest request = (FtpWebRequest)WebRequest.Create(serverPath); request.KeepAlive = true; request.UsePassive = true; request.UseBinary = true; request.Method = WebRequestMethods.Ftp.DownloadFile; request.Credentials = new NetworkCredential(username, password); // Read the file from the server & write to destination using (FtpWebResponse response = (FtpWebResponse)request.GetResponse()) // Error here using (Stream responseStream = response.GetResponseStream()) using (StreamReader reader = new StreamReader(responseStream)) using (StreamWriter destination = new StreamWriter(destinationFile)) { destination.Write(reader.ReadToEnd()); destination.Flush(); } The error is: The remote server returned an error: (550) File unavailable (e.g., file not found, no access) The file definately does exist on the remote machine and I am able to perform this ftp manually (i.e. I have permissions). Can anyone tell me why I might be getting this error?

    Read the article

  • JSON.Net and Linq

    - by user1745143
    I'm a bit of a newbie when it comes to linq and I'm working on a site that parses a json feed using json.net. The problem that I'm having is that I need to be able to pull multiple fields from the json feed and use them for a foreach block. The documentation for json.net only shows how to pull just one field. I've done a few variations after checking out the linq documentation, but I've not found anything that works best. Here's what I've got so far: WebResponse objResponse; WebRequest objRequest = HttpWebRequest.Create(url); objResponse = objRequest.GetResponse(); using (StreamReader reader = new StreamReader(objResponse.GetResponseStream())) { string json = reader.ReadToEnd(); JObject rss = JObject.Parse(json); var postTitles = from p in rss["feedArray"].Children() select (string)p["item"], //These are the fields I need to also query //(string)p["title"], (string)p["message"]; //I've also tried this with console.write and labeling the field indicies for each pulled field foreach (var item in postTitles) { lbl_slides.Text += "<div class='slide'><div class='slide_inner'><div class='slide_box'><div class='slide_content'></div><!-- slide content --></div><!-- slide box --></div><div class='rotator_photo'><img src='" + item + "' alt='' /></div><!-- rotator photo --></div><!-- slide -->"; } } Has anyone seen how to pull multiple fields from a json feed and use them as part of a foreach block (or something similar?

    Read the article

  • Does "for" in .Net Framework 4.0 execute loops in parallel? Or why is the total not the sum of the p

    - by Shiraz Bhaiji
    I am writing code to performance test a web site. I have the following code: string url = "http://xxxxxx"; System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch(); System.Diagnostics.Stopwatch totalTime = new System.Diagnostics.Stopwatch(); totalTime.Start(); for (int i = 0; i < 10; i++) { stopwatch.Start(); WebRequest request = HttpWebRequest.Create(url); WebResponse webResponse = request.GetResponse(); webResponse.Close(); stopwatch.Stop(); textBox1.Text += "Time Taken " + i.ToString() + " = " + stopwatch.Elapsed.Milliseconds.ToString() + Environment.NewLine; stopwatch.Reset(); } totalTime.Stop(); textBox1.Text += "Total Time Taken = " + totalTime.Elapsed.Milliseconds.ToString() + Environment.NewLine; Which is giving the following result: Time Taken 0 = 88 Time Taken 1 = 161 Time Taken 2 = 218 Time Taken 3 = 417 Time Taken 4 = 236 Time Taken 5 = 217 Time Taken 6 = 217 Time Taken 7 = 218 Time Taken 8 = 409 Time Taken 9 = 48 Total Time Taken = 257 I had expected the total time to be the sum of the individual times. Can anybody see why it is not?

    Read the article

  • HttpWebRequest Timeouts After Ten Consecutive Requests

    - by Bob Mc
    I'm writing a web crawler for a specific site. The application is a VB.Net Windows Forms application that is not using multiple threads - each web request is consecutive. However, after ten successful page retrievals every successive request times out. I have reviewed the similar questions already posted here on SO, and have implemented the recommended techniques into my GetPage routine, shown below: Public Function GetPage(ByVal url As String) As String Dim result As String = String.Empty Dim uri As New Uri(url) Dim sp As ServicePoint = ServicePointManager.FindServicePoint(uri) sp.ConnectionLimit = 100 Dim request As HttpWebRequest = WebRequest.Create(uri) request.KeepAlive = False request.Timeout = 15000 Try Using response As HttpWebResponse = DirectCast(request.GetResponse, HttpWebResponse) Using dataStream As Stream = response.GetResponseStream() Using reader As New StreamReader(dataStream) If response.StatusCode <> HttpStatusCode.OK Then Throw New Exception("Got response status code: " + response.StatusCode) End If result = reader.ReadToEnd() End Using End Using response.Close() End Using Catch ex As Exception Dim msg As String = "Error reading page """ & url & """. " & ex.Message Logger.LogMessage(msg, LogOutputLevel.Diagnostics) End Try Return result End Function Have I missed something? Am I not closing or disposing of an object that should be? It seems strange that it always happens after ten consecutive requests. Notes: In the constructor for the class in which this method resides I have the following: ServicePointManager.DefaultConnectionLimit = 100 If I set KeepAlive to true, the timeouts begin after five requests. All the requests are for pages in the same domain. EDIT I added a delay between each web request of between two and seven seconds so that I do not appear to be "hammering" the site or attempting a DOS attack. However, the problem still occurs.

    Read the article

  • How to get "AuthSub " token in C#? For google APPS Contacts ?

    - by Pari
    Hi, I fount this code on net : HttpWebRequest update = (HttpWebRequest)WebRequest.Create(**editUrl** ); // editUrl is a string containing the contact's edit URL update.Method = "PUT"; update.ContentType = "application/atom+xml"; update.Headers.Add(HttpRequestHeader.Authorization, "GoogleLogin auth=" + **AuthToken**); update.Headers.Add(HttpRequestHeader.IfMatch, **etag**); // etag is a string containing the <entry> element's gd:etag attribute value update.Headers.Add("GData-Version", "3.0"); Stream streamRequest = update.GetRequestStream(); StreamWriter streamWriter = new StreamWriter(streamRequest, Encoding.UTF8); streamWriter.Write(entry); // entry is the string representation of the atom entry to update streamWriter.Close(); WebResponse response = update.GetResponse(); But here i am not getting what to put in " editurl" , "AuthToken" and "Etag". a) I studied abt "AuthToken" from this Link .But not getting how to create it? Can anyone help me out here? b) Also not getting " editurl" and "Etag". I am trying to use this method to Migrate my contacts to Google Apps. Thanx

    Read the article

  • Asynchronous crawling F#

    - by jlezard
    When crawling on webpages I need to be careful as to not make too many requests to the same domain, for example I want to put 1 s between requests. From what I understand it is the time between requests that is important. So to speed things up I want to use async workflows in F#, the idea being make your requests with 1 sec interval but avoid blocking things while waiting for request response. let getHtmlPrimitiveAsyncTimer (uri : System.Uri) (timer:int) = async{ let req = (WebRequest.Create(uri)) :?> HttpWebRequest req.UserAgent<-"Mozilla" try Thread.Sleep(timer) let! resp = (req.AsyncGetResponse()) Console.WriteLine(uri.AbsoluteUri+" got response") use stream = resp.GetResponseStream() use reader = new StreamReader(stream) let html = reader.ReadToEnd() return html with | _ as ex -> return "Bad Link" } Then I do something like: let uri1 = System.Uri "http://rue89.com" let timer = 1000 let jobs = [|for i in 1..10 -> getHtmlPrimitiveAsyncTimer uri1 timer|] jobs |> Array.mapi(fun i job -> Console.WriteLine("Starting job "+string i) Async.StartAsTask(job).Result) Is this alright ? I am very unsure about 2 things: -Does the Thread.Sleep thing work for delaying the request ? -Is using StartTask a problem ? I am a beginner (as you may have noticed) in F# (coding in general actually ), and everything envolving Threads scares me :) Thanks !!

    Read the article

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