Grapevine.RESTClient throws exception about cookies if service is not up - c#

So I'm using Grapevine.RESTClient to manage the client side of my REST interface. I'm using it to communicate between a service running in LocalSystem and a process run by the user on the same machine.
My problem is that when the service is not running my client gets an exception with a message of 'Error: Value cannot be null. Parameter name: cookies'
I'm trying to create some logic on the client that is supposed to understand and accept that sometimes the service is unavailable like when the service is auto updating.
Or maybe I should just accept that the message of the exception is a little odd?
RESTClient client;
client = new RESTClient(baseUrl);
RESTRequest request = new RESTRequest(resource);
request.Method = Grapevine.HttpMethod.GET;
request.ContentType = Grapevine.ContentType.JSON;
request.Timeout = 30000;
RESTResponse response = client.Execute(request);
The above throws a System.ArgumentNullException with e.Message = "Value cannot be null.\r\nParameter name: cookies"
Hmmm... Looking at the Grapevine code on github it seems the code tries to add a cookie collection to this.Cookies even if the response object was created out of e.response in the catch block of the GetResponse call. It may or may not have a cookie collection. There should have been a test for null block around the this.Cookies.Add(response.Cookies) right?
https://github.com/scottoffen/Grapevine/blob/master/Grapevine/Client/RESTClient.cs
Unable to create a grapevine tag as the developer of grapevine suggested to do. Dont have enough points

I've had the same problem. Unfortunately the error message is misleading. To me the fix was to add a default proxy to the file App.config.
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.net>
<defaultProxy useDefaultCredentials="true" />
</system.net>
</configuration>

Related

WebPush {"Received unexpected response code"}

How to send notification using Webpush library. I was trying but its throws error msg like {"Received unexpected response code"}
****Now i have created web API to send notification & calling you through fiddler,but did n't get exception it's stuck somewhere
here is my code sample****
public void Sendnotification()
{
try
{
WebPush.VapidDetails vapidKeys = apidHelper.GenerateVapidKeys();
string subject =#"mailto:xyz.com";
string publicKey = Convert.ToString(vapidKeys.PublicKey);
string privateKey = Convert.ToString(vapidKeys.PrivateKey);
var subscription = new PushSubscription(pushEndpoint, p256dh, auth);
var vapidDetails = new VapidDetails(subject, publicKey, privateKey);
client.SendNotification(subscription, "payload", vapidDetails);
}
catch (WebPushException e)
{
}
}
I have configured Https enabled to call api using fidder. Please have look. also its throws error, it stuck somewhere
now it got the error please have look it's showing error HTTP/1.1 410 NotRegistered
See the full screen of Fiddler response error details
If you are getting the error 410 (to check the error use fiddler to intercept the https call), probably what you have is an error in the subscription data of the user probably the keys stored in your database doesn't match the subscription in the browser an easy fix could be to re-subscribe and re-save the subscription data and try again.
to setup fiddler, you have to use it as a proxy visual studio to intercept the https calls and also you have to enable https decryption.
EDIT
you can set up fiddler just by adding this configuration in your web.config or app.config:
<system.net>
<defaultProxy
enabled = "true"
useDefaultCredentials = "true">
<proxy autoDetect="false" bypassonlocal="false" proxyaddress="http://127.0.0.1:8888" usesystemdefault="false" />
</defaultProxy>
</system.net>
if in any case, you get unauthorized registration check this questions:
Web Push API Chrome, returning "Unauthorized Registration"
WebPushError and UnauthorizedRegistration when try to send push notification to Chrome and Opera, FF is OK

The maximum size of object that can be passed as Parameter to POST method

I have a web API controller with a POST method as follows.
public class MyController : ApiController
{
// POST: api/Scoring
public HttpResponseMessage Post([FromBody]MyClass request)
{
// some processing of request object
return Request.CreateResponse(HttpStatusCode.OK, someResponseObject);
}
....
}
This is consumed by a HTTPClient as follows
HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
httpClient.BaseAddress = new Uri("http://localhost");
MyClass requestClient = new MyClass();
var task = httpClient.PostAsJsonAsync("api/my", requestClient)
It works great when MyObject object size passed in POST method parameter of controller is small in size. However in case when this object size is big, I get a null for the request object in the POST method parameters. In one case, the size of the requestClient object passed from client side request is ~5 MB and in the POST method, I get request object as null. Note that Web API is hosted under IIS. Is there any setting that I need to change for permissible size.
UPDATE:
Adding following in web.config solved the null object issue in the POST method parameter.
httpRuntime maxRequestLength="2147483647" />
I then increased the size of requestClient object to ~50MB. Now the code in POST method never getting hit. On the client side, at the call to PostAsJsonAsyn, I get System.Net.HttpRequestException with following message.
Response status code does not indicate success: 404 (Not Found).
Now changing maxRequestLength doesn’t seem to have any impact.
From OP:
> then increased the size of requestClient object to ~50MB. Now the code in POST method never getting hit. On the client side, at the call to PostAsJsonAsyn, I get System.Net.HttpRequestException with following message.
Response status code does not indicate success: 404 (Not Found).
Now changing maxRequestLength doesn’t seem to have any impact.
When request filtering blocks an HTTP request because an HTTP request exceeds the request limits, IIS will return an HTTP 404 error to the client and log one of the following HTTP statuses with a unique substatus that identifies the reason that the request was denied:
HTTP Substatus Description
404.13 Content Length Too Large
404.14 URL Too Long
404.15 Query String Too Long
..etc
For Resolving the max limit issue, the Request Filtering role service(built-in security feature that was introduced in (IIS) 7.0 and above) should be configured: by SERVER MANAGER GUI or command utility appcmd.exe or modifying Web.config
<configuration>
<system.webServer>
<security>
<requestFiltering>
.....
<!-- limit post size to 10mb, query string to 256 chars, url to 1024 chars -->
<requestLimits maxQueryString="256" maxUrl="1024" maxAllowedContentLength="102400000" />
.....
</requestFiltering>
</security>
</system.webServer>
</configuration>
For Configuration details review :
https://www.iis.net/configreference/system.webserver/security/requestfiltering

Webexception:remote server returned an error (401)unauthorized

Giving Exception on
HttpWebResponse webresponse = (HttpWebResponse)webrequest.GetResponse();
this line.And Error message is
remote server returned an error 401 unauthorized
It occures only when am calling web service from other project solution...
This exception is not occuring when calling service from same project solution.
what should I do to remove this exception and get Response from Remote server??
Plz help me.
Possible solutions can be:
1) add <identity impersonate="true"></identity> in web.config
2) If you have credentials
using (client = new MyWebService())
{
var username = ConfigurationManager.AppSettings["WSUserName"]
var password = ConfigurationManager.AppSettings["WSPassword"]
client.Credentials = new NetworkCredential(username, password);
// .. and the call here ..
}
Let me know if it doesn't fix your problem.

How to use IE proxy server settings and its credentials in .Net Application

How to use the saved proxy settings and credentials as default for HttpWebRequests? The proxy settings are accessible and used but not the credentials:
IWebProxy proxy = WebRequest.GetSystemWebProxy();
proxy.Credentials = CredentialCache.DefaultNetworkCredentials;
WebRequest.DefaultWebProxy = proxy;
Are there any permissions on using the credentials?
It works with passing the credentials via NetworkCredential instance:
proxy.Credentials = new NetworkCredential("username", "password");
But I would like to use the saved ones from the operating system/IE.
Edit:
I am using a third party lib creating and calling the HttpWebRequests which should be passed through the proxy. Could that be part of the problem?
Using the App.Config file with this content doesn't work either
<configuration>
<system.net>
<defaultProxy enabled="true" useDefaultCredentials="true">
</defaultProxy>
</system.net>
</configuration>
I was having this exact same issue maybe two weeks ago!! HTTP 407 errors. I tried both suggestions, set network credentials and add the default proxy line in the app.config but neither worked. Strange too because I didn't have this issue on a vb application I wrote last year that did the exact same thing, go out to a web site and download the source as a string. When I did it then, I ran into this issue but adding the defaultProxy line in App.config worked! Weird.
This is how I was able to get around the issue.
I don't create a proxy, I assign the default one (pulled from app.config) to the webRequest's proxy attribute. I then ensure that "UseDefaultCredentials" is set to "true".
HttpWebRequest request = (HttpWebRequest.Create(m.Url) as HttpWebRequest);
request.Proxy = WebRequest.DefaultWebProxy;
request.UseDefaultCredentials = true;
I added this to the app.config (same as the above post).
<system.net>
<defaultProxy useDefaultCredentials="true"/>
</system.net>
Here's the kicker (and I wish I could explain why this solved my issue). Right after I create the request and assign the proxy with the correct credentials... I had to create a cookie container and assign it to my web request. Seriously, I don't know why this solved this issue because I didn't have to do it before.
CookieContainer cc = new CookieContainer();
request.CookieContainer = cc;
I hope this helps you.
Here's the complete code (minus the app.config lines):
HttpWebRequest request = (HttpWebRequest.Create(m.Url) as HttpWebRequest);
request.Proxy = WebRequest.DefaultWebProxy;
request.UseDefaultCredentials = true;
CookieContainer cc = new CookieContainer();
request.CookieContainer = cc;
HttpWebResponse response = (request.GetResponse() as HttpWebResponse);
As klugerama already suggested you should use CredentialCache.DefaultNetworkCredentials.
This contains the network credentials even when they seem empty.
I had like to paste another answer from this post on SO with an excellent explanation:
The NetworkCredential returned from CredentialCache.DefaultCredential is just a placeholder. ... Internal API check for this type to see if integrated authentication should be used or not.
So the things you should check is:
Is there really a problem or do you think there is because of the missing username and password?
Check which account is used as 'default network credentials' (check the Credential Manager control panel)
Check your app.config (or web.config) file, if it exists. If these proxy settings are going to be application-wide, then make sure you have the following in that file (create it if necessary):
<configuration>
<system.net>
<defaultProxy enabled="true" useDefaultCredentials="true">
</defaultProxy>
</system.net>
</configuration>
You won't need to have anything else in your code; all WebRequest instances will simply use the proxy.
If your proxy settings are not going to be application-wide, then make sure those settings are not in the .config file above, and be sure to set them in code as required.
This worked for me. Of course you will have to add the URL. The code snip-it was pulled from an app I made that sends XML Soap Requests and responses to one companies web-service that needed to be usable while on or off another companies Cisco Any-Connect network.
public HttpWebRequest CreateWebRequest()
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("url");
IWebProxy proxy = request.Proxy;
if (proxy != null)
{
string proxyuri = proxy.GetProxy(request.RequestUri).ToString();
request.UseDefaultCredentials = true;
request.Proxy = new WebProxy(proxyuri, false);
request.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
}
return request;
}
App.config file:
<system.net>
<defaultProxy enabled="true" useDefaultCredentials="true">
</defaultProxy>
</system.net>

WCF REST based GET request returing raw XML

What I am trying to accomplish is adding a GET method to my WCF REST based service and accessing it via the WebRequest class from a Silverlight 3 client application.
I am getting the error The remote server returned an error: NotFound. which, as I understand it, can be just a generic error for any 500 error encountered on the server.
WCF operation contract:
[OperationContract, WebGet(UriTemplate = "path/{id}")]
Stream Get(string id);
Operation implementation:
public Stream Get(string id)
{
WebOperationContext.Current.OutgoingResponse.ContentType = "application/xml; charset=utf-8";
return new MemoryStream(Encoding.UTF8.GetBytes("<xml><id>1</id><name>Some Name</name></xml>));
}
Client code that throws exception:
HttpWebRequest webRequest = WebRequest.CreateHttp("http://domain.com/my-service.svc/path/1");
webRequest.BeginGetResponse(
x =>
{
try
{
using (WebResponse webResponse = webRequest.EndGetResponse(x)) <--Exception thrown here
using (Stream stream = webResponse.GetResponseStream())
{
//do stuff here...eventually.
}
}
catch (Exception ex)
{
}
},
null);
I suspect that it has something to do with the return type and have also tried returning XmlElement to no avail. I am really stumped here, any ideas what I might be doing wrong?
Note that I can successfully hit the method via Fiddler and a web browser.
Try putting the code below into your web.config file(change the file name in the initializeData attribute appropriately.
If you are using full IIS, and not Casini or IIS Express (I use the latter), make sure to put the log file somewhere where your web application has write permissions). This will cause WCF to generate a fairly detailed log file. I've found the log to be pretty handy.
<system.diagnostics>
<sources>
<source name="System.ServiceModel"
switchValue="Information, ActivityTracing"
propagateActivity="true">
<listeners>
<add name="traceListener"
type="System.Diagnostics.XmlWriterTraceListener"
initializeData= "c:\temp\WEBTraces.log" />
</listeners>
</source>
</sources>
</system.diagnostics>
Here's another thing to check: Is domain.com exactly the same domain name as your silverlight app is running from (example -- is your SL app starting as localhost/xx and your web service call going to domain.com?
For security reasons, Silverlight will not make cross-domain web service calls unless the called domain grants it permission (same as Flash). If this is the case, you will need a clientaccesspolicy.xml file.
You can read about it here: http://weblogs.asp.net/jgalloway/archive/2008/12/12/silverlight-crossdomain-access-workarounds.aspx
There is a video here: http://www.silverlight.net/learn/data-networking/introduction-to-data-and-networking/how-to-use-cross-domain-policy-files-with-silverlight
There are some helpers here: http://timheuer.com/blog/archive/2008/04/06/silverlight-cross-domain-policy-file-snippet-intellisense.aspx
NotFound should mean 404 and not 500. A 404 error could be produced by a wrong URI.
Uri resturi = new Uri(String.Format("http://{0}:8080/MyService/", hostname)); // http
WebHttpBinding rest = new WebHttpBinding(WebHttpSecurityMode.TransportCredentialOnly); // WebHttpSecurityMode.Transport for ssl
host.AddServiceEndpoint(typeof(IMyService), rest, resturi);
In the code example above your service would be aviable via http://host:8080/MyService/path/1

Categories