Rectangle 27 36

To do this in Jersey you have the concept of WebApplicationException class. One method is to simply extend this class and all one of the methods to set the error text that is returned. In your case this would be:

import javax.ws.rs.*;
import javax.ws.rs.core.*;
import javax.ws.rs.core.Response.*;


public class UnauthorizedException extends WebApplicationException {

    /**
      * Create a HTTP 401 (Unauthorized) exception.
     */
     public UnauthorizedException() {
         super(Response.status(Status.UNAUTHORIZED).build());
     }

     /**
      * Create a HTTP 404 (Not Found) exception.
      * @param message the String that is the entity of the 404 response.
      */
     public UnauthorizedException(String message) {
         super(Response.status(Status.UNAUTHORIZED).entity(message).type("text/plain").build());
     }

}

Now in your code that implements the rest service you would simply throw a new exception of this type, passing in the text value in the constructor e.g.

throw new UnauthorizedException("Authorization Required");

That can create a class like this for each of your web exceptions and throw in a similar fashion.

This is also explained in the Jersey user guide - although the code is actually slightly incorrect:

Didn't the OP ask the way other than entity(message)?

Agree with @JinKwon, how is this different than 1) in OP's question?

java - JAX/Jersey Custom error code in Response - Stack Overflow

java http jersey response
Rectangle 27 609

Comprehensive list of Node.js/Express response methods and when they m...

res
http.ServerResponse
res.writeHead(statusCode)
writeHead
res.write(data)
res.end(data)

The error "Error: Can't set headers after they are sent." means that you're already in the Body or Finished state, but some function tried to set a header or statusCode. When you see this error, try to look for anything that tries to send a header after some of the body has already been written. For example, look for callbacks that are accidentally called twice, or any error that happens after the body is sent.

In your case, you called res.redirect(), which caused the response to become Finished. Then your code threw an error (res.req is null). and since the error happened within your actual function(req, res, next) (not within a callback), Connect was able to catch it and then tried to send a 500 error page. But since the headers were already sent, Node.js's setHeader threw the error that you saw.

Response must be in Head and remains in Head:

res.writeContinue()
res.statusCode = 404
res.setHeader(name, value)
res.getHeader(name)
res.removeHeader(name)
res.header(key[, val])
res.charset = 'utf-8'
res.contentType(type)
res.writeHead(statusCode, [reasonPhrase], [headers])
res.write(chunk, encoding='utf8')
res.end([data], [encoding])

Response can be in either Head/Body and remains in its current state:

res.addTrailers(headers)

Response must be in Head and becomes Finished:

return next([err])
function(req, res, next)
res.send(body|status[, headers|status[, status]])
res.attachment(filename)
res.sendfile(path[, options[, callback]])
res.json(obj[, headers|status[, status]])
res.redirect(url[, status])
res.cookie(name, val[, options])
res.clearCookie(name[, options])
res.render(view[, options[, fn]])
res.partial(view[, options])

also watch out for this classic mistake: res.redirect() doesn't stop statement execution... so return after it. Otherwise other code could be executed which could unintentiallly cause the famous header error. Thanx for the explanation!

return
next()

javascript - Error: Can't set headers after they are sent to the clien...

javascript node.js express
Rectangle 27 598

Comprehensive list of Node.js/Express response methods and when they m...

res
http.ServerResponse
res.writeHead(statusCode)
writeHead
res.write(data)
res.end(data)

The error "Error: Can't set headers after they are sent." means that you're already in the Body or Finished state, but some function tried to set a header or statusCode. When you see this error, try to look for anything that tries to send a header after some of the body has already been written. For example, look for callbacks that are accidentally called twice, or any error that happens after the body is sent.

In your case, you called res.redirect(), which caused the response to become Finished. Then your code threw an error (res.req is null). and since the error happened within your actual function(req, res, next) (not within a callback), Connect was able to catch it and then tried to send a 500 error page. But since the headers were already sent, Node.js's setHeader threw the error that you saw.

Response must be in Head and remains in Head:

res.writeContinue()
res.statusCode = 404
res.setHeader(name, value)
res.getHeader(name)
res.removeHeader(name)
res.header(key[, val])
res.charset = 'utf-8'
res.contentType(type)
res.writeHead(statusCode, [reasonPhrase], [headers])
res.write(chunk, encoding='utf8')
res.end([data], [encoding])

Response can be in either Head/Body and remains in its current state:

res.addTrailers(headers)

Response must be in Head and becomes Finished:

return next([err])
function(req, res, next)
res.send(body|status[, headers|status[, status]])
res.attachment(filename)
res.sendfile(path[, options[, callback]])
res.json(obj[, headers|status[, status]])
res.redirect(url[, status])
res.cookie(name, val[, options])
res.clearCookie(name[, options])
res.render(view[, options[, fn]])
res.partial(view[, options])

also watch out for this classic mistake: res.redirect() doesn't stop statement execution... so return after it. Otherwise other code could be executed which could unintentiallly cause the famous header error. Thanx for the explanation!

return
next()

javascript - Error: Can't set headers after they are sent to the clien...

javascript node.js express
Rectangle 27 11

The two methods are essentially functionally equivalent. http_response_code is basically a shorthand way of writing a http status header, with the added bonus that PHP will work out a suitable Reason Phrase to provide by matching your response code to one of the values in an enumeration it maintains within php-src/main/http_status_codes.h.

Note that this means your response code must match a response code that PHP knows about. You can't create your own response codes using this method, however you can using the header method. Note also that http_response_code is only available in PHP 5.4.0 and higher.

In summary - The differences between http_response_code and header for setting response codes:

If http_response_code(403); is used somewhere in a script, should it be followed by exit? Or does further execution get terminated implicitly by http_response_code(403);?

It doesn't terminate execution. So if you want to exit after setting the response code you'll have to explicitly exit.

PHP http_response_code(); versus header(); - Stack Overflow

php
Rectangle 27 4

  • No control over http response, headers, code, etc - all set by the framework in case of success or failure, return type is visible to run-time tools

You shouldn't have to use dynamic ever, if you need to return arbitrary responses from an action, you can use

  • Better control over the http response, but it will tie up the thread while executing the method, no definition for the output data type

The request thread will be kept up for the duration of the action yes. But if you do not use any async operations (DB Access, a network connection to another website/webservice or read/write files to database), using it is fine.

// Here no async operations are called, so Task is not necessary
public IActionResult Index(string name = _defaultName)
{
    if(!ModelState.IsValid)
    {
        return BadRequest(ModelState);
    }

    return Ok();
}
Task<IActionResult>
  • Better control over http response, will not tie up the thread while executing the method, but will spin off another thread to compute the result, and no definition for the output type

This assumption is just wrong. Using Task alone with true async operations (I/O operations like reading from filesystem, network connections or access to database) will NOT SPAWN a new thread. The operation will be started and the thread returned to the thread pool.

No new thread will be started instead. When the async operation completes, a thread will be taken from the thread pool and operation continues.

// No extra thread is called and the request thread is only 
// used in between "await" calls
public async Task<IActionResult> Get(string name = _defaultName)
{
    var result = await GetResultFromDatabase();

    return Ok(someModel);
}

Please read the Async Programming : Introduction to Async/Await on ASP.NET article on MSDN from Stephen Cleary. It is about ASP.NET MVC 5 (the old webstack, not the rewrite ASP.NET Core) but the principle still applies to ASP.NET Core.

If you have CPU bound operation (calculating some complicated math etc.), then do not start a new thread. This will mess up with how ASP.NET Core manages the thread pool and you will gain nothing, but will still have the overhead of context-switches and hence it will lower your performance instead of increasing it.

For CPU bound operation, simply runt hem synchronously on the request thread.

public IActionResult Get(string name = _defaultName)
{
    // Don't await or run CPU intensive stuff via Task.Run
    var result = SomeCpuIntensiveOperation();

    return Ok(result);
}

You can also mix CPU bound and async operations

public async Task<IActionResult> Get(string name = _defaultName)
{
    // runs async, no extra thread
    var valueFromDb = await GetValueFromDb();

    // Don't await or run CPU intensive stuff via Task.Run
    // runs sync, on request thread
    var result = SomeCpuIntensiveOperation(valueFromDb);

    return Ok(result);
}

I am wondering whether it makes sense without such downstream async dependencies to pursue async webapi methods and the resulting a tad weird looking code.

Generally, async scales better, when you have more requests than available threads in the thread pool. But most small sized applications never reach that state, especially when it's an learning exercise or a proof of concept.

It's very unlikely you hit that limit unless you have a high-traffic website which handles 100s or 1000s of requests per second.

Thank you for the feedback! "You shouldn't have to use dynamic ever" - it was not really a question about (not) using dynamic, unless you could share specific feedback on observed performance impact using dynamic in high-volume web/api apps. I am looking into poc for 10,000+ req/sec micro-services. Scalability is very important and ideally I am looking for a sound generic practice to recommend moving forward, e.g. use async Task<IActionResult> in use-cases a & b, and use IActionResult in use-cases d & e.

No idea about performance of dynamic, just test it. returning Dynamic or concrete type is same, in the end all of them will be wrapped around a IActionResult anyways. IActionResult is not only for http codes, but also for converting or processing the result stream. i.e. PhysicalFileResult will return a file as stream back to the client. As mentioned above, use IActionResult when you don't do async operations or cpu bound operations only.

Use Task<IActionResult> in all true async operations. Allocating/awaiting a task has a slight overhead (allocation of Task class and creation of a state machine when using await). In the end, you will have to do performance tests to decide it finally and it can't be answered here. The above explains how to use Task/async correctly in ASP.NET and ASP.NET Core. The most important correction of your assumption is that awaiting real Task do not spawn new thread and hence do not involve the "expensiveness" of starting a new thread!

c# - .net (dotnet) core webapi and async method - feedback wanted - St...

c# asynchronous asp.net-web-api asp.net-core .net-core
Rectangle 27 2

What's happening is that there is a preflight request (which is an OPTIONS request), made before the initial request. So you need an @OPTIONS endpoint to handle that request (i.e. set the response header). In your current code, you are trying to set it in the original requested endpoint response, where the OPTIONS request won't even reach.

A more common approach, instead of creating an @OPTIONS endpoint for each target, just use a Jersey filter as seen in this answer. The headers will get sent out for all request.

@OPTIONS
@Path("myfunction")
public Response cors() {
    return Response.ok()
        .header("Access-Control-Allow-Origin", "*")
        .header("Access-Control-Allow-Methods",
            "GET, POST, PUT, DELETE, OPTIONS, HEAD")
        // whatever other CORS headers
        .build();
}

thank you for information but as I'm beginner I could not understand your answer clearly, if you have time, could you explain it with simple words ? or could you show me where should I change ?

resourceConfig.getContainerResponseFilters().add(new CORSFilter());

By "target" I mean URI. If you only have one URI for the entire application, then just create an endpoint with the same URI annotated with @OPTIONS and return a empty OK response with the CORS headers. Otherwise if you have more than one URI that needs CORS support, better just use the filter

Your new problem is not related to CORS. You are now getting a 400 which is a different problem unrelated to CORS and it is a bad request on the client part. Please post a different question

javascript - How to get rid of No 'Access-Control-Allow-Origin' header...

javascript java json web-services
Rectangle 27 4

After some investigation, I found the final and the most easy way is to extend BaseRequestOptions which I prefer. The following are the ways I tried and give up for some reason: 1. extend BaseRequestOptions, and add dynamic headers in constructor(). It can not work if I login. It will be created once. So it is not dynamic. 2. extend Http. Same reason as above, I can not add dynamic headers in constructor(). And if I rewrite request(..) method, and set headers, like this:

request(url: string|Request, options?: RequestOptionsArgs): Observable<Response> {
 let token = localStorage.getItem(AppConstants.tokenName);
 if (typeof url === 'string') { // meaning we have to add the token to the options, not in url
  if (!options) {
    options = new RequestOptions({});
  }
  options.headers.set('Authorization', 'token_value');
 } else {
  url.headers.set('Authorization', 'token_value');
 }
 return super.request(url, options).catch(this.catchAuthError(this));
}

You just need to overwrite this method, but not every get/post/put methods.

3.And my preferred solution is extend BaseRequestOptions and overwrite merge() :

@Injectable()
export class AuthRequestOptions extends BaseRequestOptions {

 merge(options?: RequestOptionsArgs): RequestOptions {
  var newOptions = super.merge(options);
  let token = localStorage.getItem(AppConstants.tokenName);
  newOptions.headers.set(AppConstants.authHeaderName, token);
  return newOptions;
 }
}
merge()

Among all the answers given, this is the answer which took my attention since i have already gone for a solution which is based on extending BaseRequestOptions. However, sadly, this did not work for me. any possible reasons?

got it working. this solution is fine and I had a problem in my server. I had to do some configurations for CORS pre-flight requests. refer this link stackoverflow.com/a/43962690/3892439

How do you tie AuthRequestOptions into the rest of the app? I tried putting this in the providers section but it did not do anything.

RequestOptions
BaseRequestOptions

In my app, I just extend BaseRequestOptions, and it already extends RequestOptions. Then in app.module, you should set the providers: { provide: RequestOptions, useClass: AuthRequestOptions }

angular - Angular2 - set headers for every request - Stack Overflow

angular typescript http-headers
Rectangle 27 6

@Provider
public class CORSResponseFilter implements ContainerResponseFilter{

@Override
public ContainerResponse filter(ContainerRequest request,
        ContainerResponse response) {

    String[] allowDomain = {"http://localhost:9000","https://my.domain.com"};
    Set<String> allowedOrigins = new HashSet<String>(Arrays.asList (allowDomain));                  

    String originHeader = request.getHeaderValue("Origin");

    if(allowedOrigins.contains(originHeader)) {
        response.getHttpHeaders().add("Access-Control-Allow-Origin", originHeader);

        response.getHttpHeaders().add("Access-Control-Allow-Headers",
                "origin, content-type, accept, authorization");
        response.getHttpHeaders().add("Access-Control-Allow-Credentials", "true");
        response.getHttpHeaders().add("Access-Control-Allow-Methods",
                "GET, POST, PUT, DELETE, OPTIONS, HEAD");
    }

    return response;
}

}

The Above Link is Expired, can you add new one, or update answer with more details, Thanks

http - Access-Control-Allow-Origin Multiple Origin Domains? - Stack Ov...

http .htaccess xmlhttprequest cross-domain
Rectangle 27 6

@Provider
public class CORSResponseFilter implements ContainerResponseFilter{

@Override
public ContainerResponse filter(ContainerRequest request,
        ContainerResponse response) {

    String[] allowDomain = {"http://localhost:9000","https://my.domain.com"};
    Set<String> allowedOrigins = new HashSet<String>(Arrays.asList (allowDomain));                  

    String originHeader = request.getHeaderValue("Origin");

    if(allowedOrigins.contains(originHeader)) {
        response.getHttpHeaders().add("Access-Control-Allow-Origin", originHeader);

        response.getHttpHeaders().add("Access-Control-Allow-Headers",
                "origin, content-type, accept, authorization");
        response.getHttpHeaders().add("Access-Control-Allow-Credentials", "true");
        response.getHttpHeaders().add("Access-Control-Allow-Methods",
                "GET, POST, PUT, DELETE, OPTIONS, HEAD");
    }

    return response;
}

}

The Above Link is Expired, can you add new one, or update answer with more details, Thanks

http - Access-Control-Allow-Origin Multiple Origin Domains? - Stack Ov...

http .htaccess xmlhttprequest cross-domain
Rectangle 27 6

@Provider
public class CORSResponseFilter implements ContainerResponseFilter{

@Override
public ContainerResponse filter(ContainerRequest request,
        ContainerResponse response) {

    String[] allowDomain = {"http://localhost:9000","https://my.domain.com"};
    Set<String> allowedOrigins = new HashSet<String>(Arrays.asList (allowDomain));                  

    String originHeader = request.getHeaderValue("Origin");

    if(allowedOrigins.contains(originHeader)) {
        response.getHttpHeaders().add("Access-Control-Allow-Origin", originHeader);

        response.getHttpHeaders().add("Access-Control-Allow-Headers",
                "origin, content-type, accept, authorization");
        response.getHttpHeaders().add("Access-Control-Allow-Credentials", "true");
        response.getHttpHeaders().add("Access-Control-Allow-Methods",
                "GET, POST, PUT, DELETE, OPTIONS, HEAD");
    }

    return response;
}

}

The Above Link is Expired, can you add new one, or update answer with more details, Thanks

http - Access-Control-Allow-Origin Multiple Origin Domains? - Stack Ov...

http .htaccess xmlhttprequest cross-domain
Rectangle 27 6

@Provider
public class CORSResponseFilter implements ContainerResponseFilter{

@Override
public ContainerResponse filter(ContainerRequest request,
        ContainerResponse response) {

    String[] allowDomain = {"http://localhost:9000","https://my.domain.com"};
    Set<String> allowedOrigins = new HashSet<String>(Arrays.asList (allowDomain));                  

    String originHeader = request.getHeaderValue("Origin");

    if(allowedOrigins.contains(originHeader)) {
        response.getHttpHeaders().add("Access-Control-Allow-Origin", originHeader);

        response.getHttpHeaders().add("Access-Control-Allow-Headers",
                "origin, content-type, accept, authorization");
        response.getHttpHeaders().add("Access-Control-Allow-Credentials", "true");
        response.getHttpHeaders().add("Access-Control-Allow-Methods",
                "GET, POST, PUT, DELETE, OPTIONS, HEAD");
    }

    return response;
}

}

The Above Link is Expired, can you add new one, or update answer with more details, Thanks

http - Access-Control-Allow-Origin Multiple Origin Domains? - Stack Ov...

http .htaccess xmlhttprequest cross-domain
Rectangle 27 1

Before configuring anything in express app, use the following(exactly the same) to set header of response for cross-domain :

app.use(function(req, res, next) {
res.header('Access-Control-Allow-Credentials', true);
res.header('Access-Control-Allow-Origin', req.headers.origin);
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.header('Access-Control-Allow-Headers', 'X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept');
if ('OPTIONS' == req.method) {
     res.send(200);
 } else {
     next();
 }
});

could you explain what is the meaning of the sintax line by line? and what if I dont use it?

Make a secure oauth API with passport.js and express.js (node.js) - St...

node.js api express oauth passport.js
Rectangle 27 5

You can create a test flow with an HTTP Inbound Endpoint and a test:component for setting the payload, and add the flow file to your test configuration files. However, I prefer to use the Confluex Mock HTTP API to test applications with HTTP Outbound Endpoints. It sets up a mock HTTP server at localhost, where you can respond to different calls with specified data and response codes, so you can run all kinds of failure scenarios as well. Set up the mock server in a @Before annotated method in your FunctionalTestCase class and stop it in the @After method, so it will be available for the test methods.

unit testing - Junit Test to test Http Outbound endpoint in Mule Flow ...

unit-testing mule junit4 esb mule-studio
Rectangle 27 2

Error responses that LWP generates internally will have the "Client-Warning" header set to the value "Internal response". If you need to differentiate these internal responses from responses that a remote server actually generates, you need to test this header value.

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

LWP::UserAgent - determining source of response code - PERL Modules - ...

perl perl-module
Rectangle 27 1

You will need to set 'Access-Control-Allow-Origin' and 'Access-Control-Allow-Methods' in you response headers:

<?php
 header('Access-Control-Allow-Origin: *');
 header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
?>

In lavarel is possible to set up the headers in all responses in found the code below in this gist https://gist.github.com/eweap/1df3b1662a500857133a:

<?php namespace App\Http\Middleware;
use Closure;

use Illuminate\Contracts\Routing\Middleware;
use Illuminate\Http\Response;

class CORS implements Middleware {

 /**
  * Handle an incoming request.
  *
  * @param \Illuminate\Http\Request $request
  * @param \Closure $next
  * @return mixed
  */
 public function handle($request, Closure $next)
 {
  return $next($request)->header('Access-Control-Allow-Origin' , '*')
          ->header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT, DELETE')
          ->header('Access-Control-Allow-Headers', 'Content-Type, Accept, Authorization, X-Requested-With');
 }
}

Where exactly do I need to specify it? I have got barryvdh/laravel-cors installed since I thought there might be a cors problem.

Could you please try return response()->header('Access-Control-Allow-Origin', '*')->header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS'); ant the end of your methods

I still have got the same problem. That I get back a token like expected but when asking what token session has got it tells me that I have no token in my session. To clarify the new token is written to my DB but when I trigger a new checkLogin request it says that I have no token in my session.

I just noticed that I only get back a token in Firefox. In Chrome it tells me "XMLHttpRequest cannot load. No 'Access-Control-Allow-Origin'...

Hi sebi55 I updated my answer, The reason you get that in Chrome is caused by the headers not set properly.

session - AngularJS and Laravel - CORS - Stack Overflow

angularjs session laravel cors laravel-5
Rectangle 27 2

You're correctly setting CORS headers in your OPTIONS preflight response, but you also need to set Access-Control-Allow-Origin (either to your origin or *) on your actual GET response. The GET response should respond with the same CORS headers, regardless of whether there was a preflight response or not. This means that it must send the appropriate CORS headers, but it does not need to send anything except for Access-Control-Allow-Origin. (If other non-simple components like non-simple verbs or headers are involved, they will be allowed or denied in the preflight; the actual GET response does not need to worry about them.)

The Enable CORS site has a CORS testing tool to help you see the headers involved in a request that you specify. I've used that tool to set up a test similar to your case (GET with non-simple Content-Type header). If we examine the results of that test (careful -- the steps are presented little bit out of order, but they're all there), we see a preflight response:

Access-Control-Allow-Methods: POST, GET, PUT, DELETE, OPTIONS
...
Access-Control-Allow-Origin: http://client.cors-api.appspot.com
Access-Control-Allow-Headers: X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept

And the final CORS response:

Content-Length: 0
Content-Type: application/json
Access-Control-Allow-Origin: http://client.cors-api.appspot.com
Cache-Control: no-cache

As you can see, the GET response also has a Access-Control-Allow-Origin header and no other CORS headers. If you have any further uncertainties, feel free to tweak the settings on that tool to run a wide range of other test cases.

Finally! None of the tutorials or information I read online mentioned anything about including the headers for the GET request as well as the OPTIONS request.

ajax - Access-Control-Allow-Origin in preflight response doesn't enabl...

ajax node.js cors
Rectangle 27 2

I recently update my laravel-cors package so you might want to check it again. But setting the Access-Control-Allow-Origin: * header directly (with the response object) also works, it just doesn't check for allowed hosts, headers and methods etc.

A more Laravel way of setting the header would be to define a Route filter and modify the response there.

Route::filter('access-control', function($route, $request, $response)
{
    $response->headers->set('Access-Control-Allow-Origin', '*');
});

Then you can set the afterFilter in your Controller, or attach it to a group of routes in your routes.php file.

public function __construct()
{
    $this->afterFilter('access-control');
}

or apply it when it matches a pattern:

Route::when('api/*', 'access-control');

I would avoid using the header() function directly. Also, you are setting the headers both in Nginx and in Laravel, one would suffice.

nginx - Laravel angularJS CORS using barryvdh/laravel-cors - Stack Ove...

angularjs nginx laravel cors
Rectangle 27 19

The usage of Extending Encoders and Serializers (see http://msdn.microsoft.com/en-us/library/ms733092.aspx) or other methods of Extending WCF like usage of DataContractSerializerOperationBehavior is very interesting, but for your special problem there are easier solution ways.

If you already use Message type to return the results an use WCF4 you can do something like following:

public Message UpdateCity(string code, City city)
{
    MyResponseDataClass message = CreateMyResponse();
    // use JSON.NET to serialize the response data
    string myResponseBody = JsonConvert.Serialize(message);
    return WebOperationContext.Current.CreateTextResponse (myResponseBody,
                "application/json; charset=utf-8",
                Encoding.UTF8);
}
HttpStatusCode.Unauthorized
HttpStatusCode.Conflict
HttpStatusCode.Created
WebOperationContext.Current.OutgoingResponse.StatusCode
Stream
Message
CreateStreamResponse
CreateTextResponse

Oleg, many thanks, it works like a charm by returning Stream type, it stops Microsft serializer. I am aware of DataContractSerializerOperationBehavior, but it takes me to inheret my own Serializer from XmlObjectSerializer which is not an easy task. Your proposal is much simpler and straight forward, Thank you once more.

How does that handle deserializing the incoming City object?

From that link, it looks like UpdateCity would have to take a Message parameter to be able to deserialize with JSON.NET. Is that correct? Any way around it?

I know it's old, but solved my issue with TimeSpan and DateTime formats.

How to set Json.Net as the default serializer for WCF REST service - S...

wcf json rest .net-4.0 json.net
Rectangle 27 19

The usage of Extending Encoders and Serializers (see http://msdn.microsoft.com/en-us/library/ms733092.aspx) or other methods of Extending WCF like usage of DataContractSerializerOperationBehavior is very interesting, but for your special problem there are easier solution ways.

If you already use Message type to return the results an use WCF4 you can do something like following:

public Message UpdateCity(string code, City city)
{
    MyResponseDataClass message = CreateMyResponse();
    // use JSON.NET to serialize the response data
    string myResponseBody = JsonConvert.Serialize(message);
    return WebOperationContext.Current.CreateTextResponse (myResponseBody,
                "application/json; charset=utf-8",
                Encoding.UTF8);
}
HttpStatusCode.Unauthorized
HttpStatusCode.Conflict
HttpStatusCode.Created
WebOperationContext.Current.OutgoingResponse.StatusCode
Stream
Message
CreateStreamResponse
CreateTextResponse

Oleg, many thanks, it works like a charm by returning Stream type, it stops Microsft serializer. I am aware of DataContractSerializerOperationBehavior, but it takes me to inheret my own Serializer from XmlObjectSerializer which is not an easy task. Your proposal is much simpler and straight forward, Thank you once more.

How does that handle deserializing the incoming City object?

From that link, it looks like UpdateCity would have to take a Message parameter to be able to deserialize with JSON.NET. Is that correct? Any way around it?

I know it's old, but solved my issue with TimeSpan and DateTime formats.

How to set Json.Net as the default serializer for WCF REST service - S...

wcf json rest .net-4.0 json.net
Rectangle 27 2

Logout and Login

public class MainActivity extends FragmentActivity {
    String TAG="MainActivity";
    private static final String PERMISSION = "publish_actions";

    //private static final String PERMISSION = "email";

    private final String PENDING_ACTION_BUNDLE_KEY = "pending_action";

    private Button postStatusUpdateButton;
    private LoginButton loginButton;
    private ProfilePictureView profilePictureView;
    private TextView greeting;
    private PendingAction pendingAction = PendingAction.NONE;
    private GraphUser user;
    private GraphPlace place;
    private List<GraphUser> tags;
    private boolean canPresentShareDialog;

    Button LogoutButton,Pro;

/*  private static final List<String> PERMISSION = Arrays.asList(
            "email","publish_actions");*/


    private enum PendingAction
    {
        NONE, POST_STATUS_UPDATE
    }

    private UiLifecycleHelper uiHelper;

    private Session.StatusCallback callback = new Session.StatusCallback() {
        @Override
        public void call(Session session, SessionState state,
                Exception exception) 
        {
            onSessionStateChange(session, state, exception);
        }
    };

    private FacebookDialog.Callback dialogCallback = new FacebookDialog.Callback() {
        @Override
        public void onError(FacebookDialog.PendingCall pendingCall,
                Exception error, Bundle data) {
            Log.d(TAG, String.format("Error: %s", error.toString()));
        }

        @Override
        public void onComplete(FacebookDialog.PendingCall pendingCall,
                Bundle data) {
            Log.d(TAG, "Success!");
        }
    };



    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        uiHelper = new UiLifecycleHelper(this, callback);
        uiHelper.onCreate(savedInstanceState);
        // Can we present the share dialog for regular links?
        canPresentShareDialog = FacebookDialog.canPresentShareDialog(this,FacebookDialog.ShareDialogFeature.SHARE_DIALOG);

        if (savedInstanceState != null) {
            String name = savedInstanceState.getString(PENDING_ACTION_BUNDLE_KEY);
            pendingAction = PendingAction.valueOf(name);
        }

        setContentView(R.layout.activity_main);



        loginButton = (LoginButton) findViewById(R.id.login_button);
        loginButton.setUserInfoChangedCallback(new LoginButton.UserInfoChangedCallback() 
        {
                    @Override
                    public void onUserInfoFetched(GraphUser user) 
                    {
                        MainActivity.this.user = user;
                        updateUI();
                        // It's possible that we were waiting for this.user to
                        // be populated in order to post a status update.
                        handlePendingAction();


                    }
                });

        profilePictureView = (ProfilePictureView) findViewById(R.id.profilePicture);
        greeting = (TextView) findViewById(R.id.greeting);

        postStatusUpdateButton = (Button) findViewById(R.id.postStatusUpdateButton);
        postStatusUpdateButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                performPublish(PendingAction.POST_STATUS_UPDATE,canPresentShareDialog);
            }
        });

          LogoutButton=(Button)findViewById(R.id.LogoutButton);
          LogoutButton.setOnClickListener(new View.OnClickListener() 
          {

            @Override
            public void onClick(View v)
            {

                //callFacebookLogout(session);
                Logout();

            }
        });

    }

    //override lifecycle methods so that UiLifecycleHelper know about state of the activity
    @Override
    protected void onResume() {
        super.onResume();
        uiHelper.onResume();
        updateUI();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        uiHelper.onSaveInstanceState(outState);
        outState.putString(PENDING_ACTION_BUNDLE_KEY, pendingAction.name());
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        uiHelper.onActivityResult(requestCode, resultCode, data, dialogCallback);
    }

    @Override
    public void onPause() {
        super.onPause();
        uiHelper.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        uiHelper.onDestroy();
    }

    private void onSessionStateChange(Session session, SessionState state,Exception exception) 
    {
        if (state.isOpened()) {
            Toast.makeText(getApplicationContext(), "User logged in...", Toast.LENGTH_SHORT).show();

            getUserData(session,state);



        } else if (state.isClosed()) {
            Toast.makeText(getApplicationContext(), "User logged out...", Toast.LENGTH_SHORT).show();
        }
        if (pendingAction != PendingAction.NONE
                && (exception instanceof FacebookOperationCanceledException 
                || exception instanceof FacebookAuthorizationException)) {
            new AlertDialog.Builder(MainActivity.this)//if permission is not granted
                    .setTitle(R.string.cancelled)
                    .setMessage(R.string.permission_not_granted)
                    .setPositiveButton(R.string.ok, null).show();
            pendingAction = PendingAction.NONE;
        } else if (state == SessionState.OPENED_TOKEN_UPDATED) {
            handlePendingAction();
        }
        updateUI();
    }

    private void updateUI() 
    {
        Session session = Session.getActiveSession();
        boolean enableButtons = (session != null && session.isOpened());

        postStatusUpdateButton.setEnabled(enableButtons
                || canPresentShareDialog);

        if (enableButtons && user != null) 
        {
            profilePictureView.setProfileId(user.getId());
            greeting.setText(getString(R.string.hello_user, user.getFirstName()));



        } else {
            profilePictureView.setProfileId(null);
            greeting.setText(null);
        }


    }

    @SuppressWarnings("incomplete-switch")
    private void handlePendingAction() {
        PendingAction previouslyPendingAction = pendingAction;
        // These actions may re-set pendingAction if they are still pending, but we assume they
        // will succeed.
        pendingAction = PendingAction.NONE;

        switch (previouslyPendingAction) {
        case POST_STATUS_UPDATE:
            postStatusUpdate();
            break;
        }
    }

    private interface GraphObjectWithId extends GraphObject {
        String getId();
    }

    private void showPublishResult(String message, GraphObject result,
            FacebookRequestError error) {
        String title = null;
        String alertMessage = null;
        if (error == null) {
            title = getString(R.string.success);
            String id = result.cast(GraphObjectWithId.class).getId();
            alertMessage = getString(R.string.successfully_posted_post,
                    message, id);
        } else {
            title = getString(R.string.error);
            alertMessage = error.getErrorMessage();
        }

        new AlertDialog.Builder(this).setTitle(title).setMessage(alertMessage)
                .setPositiveButton(R.string.ok, null).show();
    }

    // create sample post to update on facebook
    private FacebookDialog.ShareDialogBuilder createShareDialogBuilderForLink() {
        return new FacebookDialog.ShareDialogBuilder(this)
                .setName("Hello Facebook")
                .setDescription("this is sample post from androidSRC.net to demonstrate facebook login in your android application")
                .setLink("http://androidsrc.net/");
    }

    private void postStatusUpdate() {
        if (canPresentShareDialog) {
            FacebookDialog shareDialog = createShareDialogBuilderForLink().build();
            uiHelper.trackPendingDialogCall(shareDialog.present());
        } else if (user != null && hasPublishPermission()) {
            final String message = getString(R.string.status_update,
                    user.getFirstName(), (new Date().toString()));
            Request request = Request.newStatusUpdateRequest(
                    Session.getActiveSession(), message, place, tags,
                    new Request.Callback() {
                        @Override
                        public void onCompleted(Response response) {
                            showPublishResult(message,
                                    response.getGraphObject(),
                                    response.getError());
                        }
                    });
            request.executeAsync();
        } else {
            pendingAction = PendingAction.POST_STATUS_UPDATE;
        }
    }

    //check if app has permission to publish on facebook
    private boolean hasPublishPermission() {
        Session session = Session.getActiveSession();
        return session != null && session.getPermissions().contains("publish_actions")&&session.getPermissions().contains("email");
    }

    private void performPublish(PendingAction action, boolean allowNoSession) {
        Session session = Session.getActiveSession();
        if (session != null) {
            pendingAction = action;
            if (hasPublishPermission()) {
                // We can do the action right away.
                handlePendingAction();
                return;
            } else if (session.isOpened()) {
                // We need to get new permissions, then complete the action when
                // we get called back.
                session.requestNewPublishPermissions(new Session.NewPermissionsRequest(
                        this, PERMISSION));
                return;
            }
        }

        if (allowNoSession) {
            pendingAction = action;
            handlePendingAction();
        }
    }

    public void Logout()
    {
        if (Session.getActiveSession() != null) 
        {
            Session.getActiveSession().closeAndClearTokenInformation();
            Toast.makeText(getApplicationContext(), "logged out...", Toast.LENGTH_SHORT).show();
        }

        Session.setActiveSession(null);
    }




    private void getUserData(Session session, SessionState state)
    {
        if (state.isOpened())
        {
            Request.newMeRequest(session, new Request.GraphUserCallback()
            {
                @Override
                public void onCompleted(GraphUser user, Response response)
                {
                    if (response != null)
                    {
                        try
                        {
                            String name = user.getName();
                            // If you asked for email permission
                            String email = (String) user.getProperty("email");
                           // Log.e(LOG_TAG, "Name: " + name + " Email: " + email);

                            Toast.makeText(getApplicationContext(), "Name: " + name + " Email: " + email, Toast.LENGTH_SHORT).show();
                        }
                        catch (Exception e)
                        {
                            e.printStackTrace();
                            //Log.d(LOG_TAG, "Exception e");
                        }

                    }
                }
            }).executeAsync();
        }
    }
public void Logout()
        {
            if (Session.getActiveSession() != null) 
            {
                Session.getActiveSession().closeAndClearTokenInformation();
                Toast.makeText(getApplicationContext(), "logged out...", Toast.LENGTH_SHORT).show();
            }

            Session.setActiveSession(null);
        }

Facebook SDK 3.0 Logout Not Working in android Application from any ot...

android facebook facebook-login facebook-android-sdk