问:
Android Wear Emulator Oreo FCM Messages not received

I'm trying to receive FCM notification on android wear emulator running on Android Oreo API 26.

I have properly registered the app on firebase, the firebase token is being printed on the log and the notification channel is also being created.

I'm using the firebase console to send the message, but it is not receiving on the wear. The console says 0 messages sent, 0 received. I'm sending the notification from the console under the same name, via the notification channel testing_channel.

Does it take time to receive on the wear?

Manifest declaration:

```<code><service
        android:name=".Services.NotificationInstanceService"
        android:enabled="true"
        android:exported="false">
        <intent-filter>
            <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
        </intent-filter>
    </service>
</code>```

Service Class:

```<code>public class NotificationInstanceService extends FirebaseInstanceIdService{

    @Override
    public void onTokenRefresh() {

        String refreshedToken = FirebaseInstanceId.getInstance().getToken() ;
        Log.i("TAG", "onTokenRefresh: " + refreshedToken);

    }
}
</code>```

AppController:

```<code>public class AppController extends Application{

    @Override
    public void onCreate() {
        super.onCreate();

        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {

            NotificationManager mNotificationManager =
                    (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

            String id = "testing_channel";
            CharSequence name = "Testing";
            String description = "This channel is primarily for testing";
            int importance = NotificationManager.IMPORTANCE_HIGH;
            NotificationChannel mChannel = null;
            mChannel = new NotificationChannel(id, name, importance);
            mChannel.setDescription(description);
            mChannel.enableLights(true);
            mChannel.setLightColor(Color.RED);
            mChannel.enableVibration(true);
            mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
            mNotificationManager.createNotificationChannel(mChannel);

            Log.i("TAG", "onCreate: NOTIFICATION CHANNEL CREATED" );

        }
    }
}
</code>```

答:
you should use the latest of AppCompat library currently 26.0.2

```<code>compile "com.android.support:appcompat-v7:26.0.+"
</code>```

In Android O it's a must to use a channel with your Notification Builder

below is a sample code its works for me:

```<code>// Sets an ID for the notification, so it can be updated.
</code>```

int notifyID = 1;
String CHANNEL_ID = "my_channel_01";// The id of the channel.

```<code>NotificationCompat notification =
    new NotificationCompat.Builder(this)
    .setSmallIcon(R.drawable.notification_icon)
    .setContentTitle("My notification")
    .setContentText("Hello World!")
    .setChannelId(CHANNEL_ID).build();

NotificationManager mNotificationManager =
        (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
   mNotificationManager.createNotificationChannel(mChannel);
}

// Issue the notification.

 mNotificationManager.notify(notifyID , notification);
</code>```

and use a "Google APIs" (any version) target to receive push notifications

Body:
I'm trying to receive FCM notification on android wear emulator running on Android Oreo API 26.

I have properly registered the app on firebase, the firebase token is being printed on the log and the notification channel is also being created.

I'm using the firebase console to send the message, but it is not receiving on the wear. The console says 0 messages sent, 0 received. I'm sending the notification from the console under the same name, via the notification channel testing_channel.

Does it take time to receive on the wear?

Manifest declaration:

<service
        android:name=".Services.NotificationInstanceService"
        android:enabled="true"
        android:exported="false">
        <intent-filter>
            <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
        </intent-filter>
    </service>

Service Class:

public class NotificationInstanceService extends FirebaseInstanceIdService{

    @Override
    public void onTokenRefresh() {

        String refreshedToken = FirebaseInstanceId.getInstance().getToken() ;
        Log.i("TAG", "onTokenRefresh: " + refreshedToken);

    }
}

AppController:

public class AppController extends Application{

    @Override
    public void onCreate() {
        super.onCreate();

        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {

            NotificationManager mNotificationManager =
                    (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

            String id = "testing_channel";
            CharSequence name = "Testing";
            String description = "This channel is primarily for testing";
            int importance = NotificationManager.IMPORTANCE_HIGH;
            NotificationChannel mChannel = null;
            mChannel = new NotificationChannel(id, name, importance);
            mChannel.setDescription(description);
            mChannel.enableLights(true);
            mChannel.setLightColor(Color.RED);
            mChannel.enableVibration(true);
            mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
            mNotificationManager.createNotificationChannel(mChannel);

            Log.i("TAG", "onCreate: NOTIFICATION CHANNEL CREATED" );

        }
    }
}

Body:
you should use the latest of AppCompat library currently 26.0.2

compile "com.android.support:appcompat-v7:26.0.+"

In Android O it's a must to use a channel with your Notification Builder

below is a sample code its works for me:

// Sets an ID for the notification, so it can be updated.

int notifyID = 1;
String CHANNEL_ID = "my_channel_01";// The id of the channel.

NotificationCompat notification =
    new NotificationCompat.Builder(this)
    .setSmallIcon(R.drawable.notification_icon)
    .setContentTitle("My notification")
    .setContentText("Hello World!")
    .setChannelId(CHANNEL_ID).build();

NotificationManager mNotificationManager =
        (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
   mNotificationManager.createNotificationChannel(mChannel);
}

// Issue the notification.

 mNotificationManager.notify(notifyID , notification);

and use a "Google APIs" (any version) target to receive push notifications


来源: stackexchange

问:
Zero should be accepted in the input type number but not Negative values
I am doing some validations for the input type.

```<code><input
    type="number"
    min="0"
    decimal-places=""
    ng-model="candidate.ctc"
    class="form-control ng-pristine ng-untouched ng-valid-min ng-invalid ng-invalid-required candidateCTCInputPosition"
    id="ctc"
    placeholder="CCTC"
    autocomplete="off"
    required="">
</code>```

Here, with this user is not able to take the 0 as an input, So, when user types the 0 then it is treating it as a false value.

So, user should not be able to type negative values using the keyups and also it should accept the 0. How can I achieve this?

答:
Here's a working solution:
http://jsfiddle.net/qoL16sup/

Directive:

```<code>decimalPlaces.$inject = ['$filter','$locale'];
function decimalPlaces($filter,$locale){
    return {
    require: 'ngModel',
    link: function(scope,element,attrs,ngModelCtrl){
        var groupSep = $locale.NUMBER_FORMATS.GROUP_SEP;
        var decimalSep = $locale.NUMBER_FORMATS.DECIMAL_SEP;
        var decimalPlaces = scope.$eval(attrs['decimalPlaces']) || 0;
        var pattern = decimalPlaces > 0 ?
            new RegExp('^\\d*(\\'+ decimalSep +')?[0-9]{0,' + decimalPlaces + '}$') : new RegExp('^\\d*$');

        element.bind('keypress',function(e){
          var lastChar = e.charCode!==0?String.fromCharCode(e.charCode):'';
          var selectionStart = element[0].selectionStart;
          var selectionEnd = element[0].selectionEnd;
          var newVal = element.val().slice(0,selectionStart) + lastChar + element.val().slice(selectionEnd);

          if(!pattern.test(newVal)){
            e.preventDefault();
          }
        });

      element.bind('blur',function(){
        var value = ngModelCtrl.$viewValue || ngModelCtrl.$modelValue;
        if (ngModelCtrl.$isEmpty(value)) return null;
        if(pattern.test(value)){
          element.val($filter('number')(value,decimalPlaces));
        }else{
          element.val('');
          ngModelCtrl.$setViewValue('');
          ngModelCtrl.$commitViewValue();
        }
      });

      element.bind('focus',function(){
        var value = ngModelCtrl.$modelValue || ngModelCtrl.$viewValue;
        if (ngModelCtrl.$isEmpty(value)) return null;
        element.val(value);
      });

      ngModelCtrl.$parsers.unshift(function(value){
        if (ngModelCtrl.$isEmpty(value)) return null;
        if(pattern.test(value)){
          value = parseFloat(value);
          if(decimalPlaces){
            value = value.toFixed(decimalPlaces);
          }else{
            value = Math.floor(value);
          }
          return parseFloat(value);
        }else{
          return null;
        }
      });

      if (angular.isDefined(attrs.min)) {
        var minVal = scope.$eval(attrs.min);
        ngModelCtrl.$validators.min = function(value) {
          return ngModelCtrl.$isEmpty(value) || angular.isUndefined(minVal) || value >= minVal;
        };
      }

      if (angular.isDefined(attrs.max)) {
        var maxVal = scope.$eval(attrs.max);
        ngModelCtrl.$validators.max = function(value) {
          return ngModelCtrl.$isEmpty(value) || angular.isUndefined(maxVal) || value <= maxVal;
        };
      }

    }
  }
}
</code>```

HTML:

```<code><form name="myForm" novalidate autocomplete="off">
<label>
  Decimal places = 0
  <input
    type="text"
    name="input1"
    decimal-places="0"
    ng-model="model.input1"
    autocomplete="off"
    required>
</label>
<br/> <br/>
<lable>
Decimal places = 2:
  <input
    type="text"
    name="input2"
    decimal-places="2"
    ng-model="model.input2"
    autocomplete="off"
    required>
</lable>

<br/> <br/>
<lable>
Decimal places = 2, min = 100, max = 10000:
  <input
    type="text"
    name="input3"
    decimal-places="2"
    min="100"
    max="10000"
    ng-model="model.input3"
    autocomplete="off"
    required>
</lable>
</form>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am doing some validations for the input type.

<input
    type="number"
    min="0"
    decimal-places=""
    ng-model="candidate.ctc"
    class="form-control ng-pristine ng-untouched ng-valid-min ng-invalid ng-invalid-required candidateCTCInputPosition"
    id="ctc"
    placeholder="CCTC"
    autocomplete="off"
    required="">

Here, with this user is not able to take the 0 as an input, So, when user types the 0 then it is treating it as a false value.

So, user should not be able to type negative values using the keyups and also it should accept the 0. How can I achieve this?

Body:
Here's a working solution:
http://jsfiddle.net/qoL16sup/

Directive:

decimalPlaces.$inject = ['$filter','$locale'];
function decimalPlaces($filter,$locale){
    return {
    require: 'ngModel',
    link: function(scope,element,attrs,ngModelCtrl){
        var groupSep = $locale.NUMBER_FORMATS.GROUP_SEP;
        var decimalSep = $locale.NUMBER_FORMATS.DECIMAL_SEP;
        var decimalPlaces = scope.$eval(attrs['decimalPlaces']) || 0;
        var pattern = decimalPlaces > 0 ?
            new RegExp('^\\d*(\\'+ decimalSep +')?[0-9]{0,' + decimalPlaces + '}$') : new RegExp('^\\d*$');

        element.bind('keypress',function(e){
          var lastChar = e.charCode!==0?String.fromCharCode(e.charCode):'';
          var selectionStart = element[0].selectionStart;
          var selectionEnd = element[0].selectionEnd;
          var newVal = element.val().slice(0,selectionStart) + lastChar + element.val().slice(selectionEnd);

          if(!pattern.test(newVal)){
            e.preventDefault();
          }
        });

      element.bind('blur',function(){
        var value = ngModelCtrl.$viewValue || ngModelCtrl.$modelValue;
        if (ngModelCtrl.$isEmpty(value)) return null;
        if(pattern.test(value)){
          element.val($filter('number')(value,decimalPlaces));
        }else{
          element.val('');
          ngModelCtrl.$setViewValue('');
          ngModelCtrl.$commitViewValue();
        }
      });

      element.bind('focus',function(){
        var value = ngModelCtrl.$modelValue || ngModelCtrl.$viewValue;
        if (ngModelCtrl.$isEmpty(value)) return null;
        element.val(value);
      });

      ngModelCtrl.$parsers.unshift(function(value){
        if (ngModelCtrl.$isEmpty(value)) return null;
        if(pattern.test(value)){
          value = parseFloat(value);
          if(decimalPlaces){
            value = value.toFixed(decimalPlaces);
          }else{
            value = Math.floor(value);
          }
          return parseFloat(value);
        }else{
          return null;
        }
      });

      if (angular.isDefined(attrs.min)) {
        var minVal = scope.$eval(attrs.min);
        ngModelCtrl.$validators.min = function(value) {
          return ngModelCtrl.$isEmpty(value) || angular.isUndefined(minVal) || value >= minVal;
        };
      }

      if (angular.isDefined(attrs.max)) {
        var maxVal = scope.$eval(attrs.max);
        ngModelCtrl.$validators.max = function(value) {
          return ngModelCtrl.$isEmpty(value) || angular.isUndefined(maxVal) || value <= maxVal;
        };
      }

    }
  }
}

HTML:

<form name="myForm" novalidate autocomplete="off">
<label>
  Decimal places = 0
  <input
    type="text"
    name="input1"
    decimal-places="0"
    ng-model="model.input1"
    autocomplete="off"
    required>
</label>
<br/> <br/>
<lable>
Decimal places = 2:
  <input
    type="text"
    name="input2"
    decimal-places="2"
    ng-model="model.input2"
    autocomplete="off"
    required>
</lable>

<br/> <br/>
<lable>
Decimal places = 2, min = 100, max = 10000:
  <input
    type="text"
    name="input3"
    decimal-places="2"
    min="100"
    max="10000"
    ng-model="model.input3"
    autocomplete="off"
    required>
</lable>
</form>


问:
Find all lines within a circle, for many circles. Optimization
I'm working on a program in which I need to find all lines which are in a circles located at some cartesian point of  some radius.

At the moment, for every circle, I am iterating over all the lines and checking if the line enters/contacts the circle at any point.

The code essentially looks like this.

```<code>for (int i = 0; i < num_circles; i++)
{
    for (int j = 0; j < num_lines; j++)
    {
        if(lineIntersectWithCircle(circle[i], lines[j]))
        {
            //Append line[j] to a list of lines intersecting with circle[i];

            //some code
        }
    }
}
</code>```

I've been thinking of many way to optimize this, but I'm having trouble.
I have sorted the circles by minimum Cartesian distance and sorted lines by maximum distance away. This way you can somewhat optimize, but it's quite minimal because once you reach the point where line[j].max > circle[i].min, you still have to iterate through all the rest of the lines.

I am fine with my intersection checking method, I just would like to minimize the amount of times I need to call it.

Is there a good way of doing this?

答:
As with anything it depends on your use case.  If you have a fixed number of lines or infrequently added, you may want to precompute some of the calculations needed to find out if any part of the line is within radius distance of the center of the circle

Starting with the equation for the shortest distance between a line and a point and comparing that distance is less than the radius of the circle:

```<code>//abs(Cx*(y1-y0)-Cy*(x1-x0)+x1*y0-y1*x0)/sqrt((y1-y0)*(y1-y0)+(x1-x0)*(x1-x0))<R
//pull out some constants and cache these as they are initialized
//int y10 = y1-y0, //add to the line struct
//  x10 = x1 -x0,
//  delta = x1*y0-y1*x0,
//  sides = (y10)*(y10)+(x10)*(x10);
//  R2 = R*R; //add to the circle struct
//now the equation factors down to
//abs(Cx*(y10)-Cy*(x10)+delta)/sqrt(sides)< R //replace constants
//abs(Cx*(y10)-Cy*(x10)+delta) < sqrt(sides) * R //remove division
//pow(Cx*(y10)-Cy*(x10)+delta , 2.0) < sides * R * R //remove sqrt()
//int tmp = Cx*(y10)-Cy*(x10)+delta //factor out pow data
//tmp * tmp < sides * R2 //remove pow() and use cache R squared
//now it is just a few cheap instructions
</code>```

Now the check should be just 4 integer multiplies, 2 add/subtract and a compare.

```<code>lineIntersectWithCircle(size_t circle, size_t line){
  struct circle C = circle_cache[circle]; //these may be separate arrays
  struct line L = line_cache[line];       //from your point data

  long tmp = C.x * L.y10 - C.y * L.x10 + L.delta;
  return (tmp*tmp < L.sides * C.R2);
}
</code>```

... but you may want to check my math - its been a while.  Also I assumed the points would be integers - change to float as needed - it should still be relatively fast.

If that isn't fast enough you can add additional data for the bounding boxes of the circle and line

```<code>bool lineIntersectWithCircle(size_t circle, size_t line){
  struct circle C = circle_cache[circle]; //these may be separate arrays
  struct line L = line_cache[line];       //from your point data

  //if the bounding boxes don't intersect neither does the line
  //this may not be _that_ helpful and you would need to:
  // figure out the bounding boxes for each line/circle
  // and cache additional data
  if (C.leftx > L.rightx || L.leftx > C.rightx) //a box is to the side
    return 0;
  if (C.topy < L.boty || L.topy < C.boty) //a box is below/above
    return 0;

  //the bounding boxes intersected so check exact calculation
  long tmp = C.x * L.y10 - C.y * L.x10 + L.delta;
  return (tmp*tmp < L.sides * C.R2);
}
</code>```

Body:
I'm working on a program in which I need to find all lines which are in a circles located at some cartesian point of  some radius.

At the moment, for every circle, I am iterating over all the lines and checking if the line enters/contacts the circle at any point.

The code essentially looks like this.

for (int i = 0; i < num_circles; i++)
{
    for (int j = 0; j < num_lines; j++)
    {
        if(lineIntersectWithCircle(circle[i], lines[j]))
        {
            //Append line[j] to a list of lines intersecting with circle[i];

            //some code
        }
    }
}

I've been thinking of many way to optimize this, but I'm having trouble.
I have sorted the circles by minimum Cartesian distance and sorted lines by maximum distance away. This way you can somewhat optimize, but it's quite minimal because once you reach the point where line[j].max > circle[i].min, you still have to iterate through all the rest of the lines.

I am fine with my intersection checking method, I just would like to minimize the amount of times I need to call it.

Is there a good way of doing this?

Body:
As with anything it depends on your use case.  If you have a fixed number of lines or infrequently added, you may want to precompute some of the calculations needed to find out if any part of the line is within radius distance of the center of the circle

Starting with the equation for the shortest distance between a line and a point and comparing that distance is less than the radius of the circle:

//abs(Cx*(y1-y0)-Cy*(x1-x0)+x1*y0-y1*x0)/sqrt((y1-y0)*(y1-y0)+(x1-x0)*(x1-x0))<R
//pull out some constants and cache these as they are initialized
//int y10 = y1-y0, //add to the line struct
//  x10 = x1 -x0,
//  delta = x1*y0-y1*x0,
//  sides = (y10)*(y10)+(x10)*(x10);
//  R2 = R*R; //add to the circle struct
//now the equation factors down to
//abs(Cx*(y10)-Cy*(x10)+delta)/sqrt(sides)< R //replace constants
//abs(Cx*(y10)-Cy*(x10)+delta) < sqrt(sides) * R //remove division
//pow(Cx*(y10)-Cy*(x10)+delta , 2.0) < sides * R * R //remove sqrt()
//int tmp = Cx*(y10)-Cy*(x10)+delta //factor out pow data
//tmp * tmp < sides * R2 //remove pow() and use cache R squared
//now it is just a few cheap instructions

Now the check should be just 4 integer multiplies, 2 add/subtract and a compare.

lineIntersectWithCircle(size_t circle, size_t line){
  struct circle C = circle_cache[circle]; //these may be separate arrays
  struct line L = line_cache[line];       //from your point data

  long tmp = C.x * L.y10 - C.y * L.x10 + L.delta;
  return (tmp*tmp < L.sides * C.R2);
}

... but you may want to check my math - its been a while.  Also I assumed the points would be integers - change to float as needed - it should still be relatively fast.

If that isn't fast enough you can add additional data for the bounding boxes of the circle and line

bool lineIntersectWithCircle(size_t circle, size_t line){
  struct circle C = circle_cache[circle]; //these may be separate arrays
  struct line L = line_cache[line];       //from your point data

  //if the bounding boxes don't intersect neither does the line
  //this may not be _that_ helpful and you would need to:
  // figure out the bounding boxes for each line/circle
  // and cache additional data
  if (C.leftx > L.rightx || L.leftx > C.rightx) //a box is to the side
    return 0;
  if (C.topy < L.boty || L.topy < C.boty) //a box is below/above
    return 0;

  //the bounding boxes intersected so check exact calculation
  long tmp = C.x * L.y10 - C.y * L.x10 + L.delta;
  return (tmp*tmp < L.sides * C.R2);
}


问:
Modbus read timeout error for JlibModbus Java Library
I am using jlibmodbus-1.2.8.4 Java Modbud Library for implementing Java 8 Application on Linux Ubuntu 14.04 LTS

And for serial communication I am using JSSC - Java Simple Serial Connector.

I am using USB to Serial Converter cable for serial connection to my machine.
I have used FTDI Drivers for my ubuntu as the converter cable that I am using is not providing Ubuntu drivers. So I have installed FTDI drivers for x86.

I have test application and it did worked for the first time perfectly and I am able to read/write registers with test MODBUS simulator. But after reboot I got serial read time out error and it had stopped working.

I have below questions:

Do I need to use USB to Serial Converter FTDI Drivers? or Ubuntu 14.04 LTS does not require it and it has built in support.

I have also did load usbserial module using sudo modprobe usbserial vendor=0xXXXXX product=0xXXXXX do I need to do it, also added it in /etc/modules?

In the latest release of "JlibModbus" 1.2.9.0 I get CRC check error and not the serial read time out error as previous version? I have verified Parity and Baud rate and no issue in these parameters but still CRC for reading Holding register fails?

Is there any other options of MODBUS RTU Master Java based Library? I have seen jamod and modbus4j but looks like then don't support RTU Master and I don't find any sample.

答:
I'm using the latest (1.2.9.1) of the JLibModbus library with a USB-to-Serial Converter. I'm using Moxa UPort 1150I and a Noname USB-to-RS485 converter.

Please turn the DEBUG mode on and show output.

Also, you can try using the j2mod library.


问:
How to convert smart card APDU command on java to c#?
I have Java code that works fine for reading data from an smart card:

```<code>byte[] dataSetEF12 = {0, -80, -110, 0, 0};
apdu = new CommandAPDU(dataSetEF12);
ResponseAPDU response = cardChannel.transmit(apdu);
byte[] data = response.getData();
</code>```

But I need this on c# & I write this:

```<code>apdu = new APDUCommand(0x00, 0xB0, 0x92, 0x00, null, 0x00);
APDUResponse response = cardReader.Transmit(command);
byte[] data = response.Data;
</code>```

But on c# response.Data equals to null

Anyone know what is my mistake
or what is the solution?

答:
Based on what status code which is returned from card, your problem maybe has several reasons:

SW = 61XX; You have to send GET_RESPONSE command to card.

SW = 9000; You have to Check you C# wrapper. (Maybe you have to set Le in command apdu)

SW = 6F00; Some thing wrong in your command or card

SW = anything else; You have to search it on the web.

Good luck

Body:
I have Java code that works fine for reading data from an smart card:

byte[] dataSetEF12 = {0, -80, -110, 0, 0};
apdu = new CommandAPDU(dataSetEF12);
ResponseAPDU response = cardChannel.transmit(apdu);
byte[] data = response.getData();

But I need this on c# & I write this:

apdu = new APDUCommand(0x00, 0xB0, 0x92, 0x00, null, 0x00);
APDUResponse response = cardReader.Transmit(command);
byte[] data = response.Data;

But on c# response.Data equals to null

Anyone know what is my mistake
or what is the solution?


问:
ASP.NET Core 2 API call is redirected (302)
I'm trying to migrate this project
https://github.com/asadsahi/AspNetCoreSpa from .net core 1.1 to 2.0 but have a problem after a successful login. After the login my GET api calls e. g. to https://localhost:44331/api/profile/test end up with a redirect (302) and I don't know why. I received a bearer token and it looks fine.

Request header format:
authorization: Bearer [token]

```<code>[Route("api/[controller]")]
public class ProfileController : BaseController
{
    private readonly UserManager<ApplicationUser> _userManager;
    private readonly ILogger _logger;

    public ProfileController(ILoggerFactory loggerFactory, UserManager<ApplicationUser> userManager)
    {
        _logger = loggerFactory.CreateLogger<ProfileController>();
        _userManager = userManager;
    }

    [HttpGet("test")]
    public async Task<IActionResult> Test()
    {
        return  Json(ModelState.GetModelErrors());
    }
}

[Authorize]
[ServiceFilter(typeof(ApiExceptionFilter))]
[ResponseCache(Location = ResponseCacheLocation.None, NoStore = true)]
public class BaseController : Controller
{
    public BaseController()
    {
    }
}
</code>```

Startup.cs:

```<code>public void ConfigureServices(IServiceCollection services)
{
    if (_hostingEnv.IsDevelopment())
    {
        services.AddSslCertificate(_hostingEnv);
    }
    else
    {
        services.Configure<MvcOptions>(o => o.Filters.Add(new RequireHttpsAttribute()));
    }
    services.AddOptions();
    services.AddCors();
    services.AddLogging();
    services.AddResponseCompression(options =>
    {
        options.MimeTypes = Helpers.DefaultMimeTypes;
    });

    services.AddAuthentication(sharedOptions =>
    {
        sharedOptions.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
        sharedOptions.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
        sharedOptions.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;

    }).AddJwtBearer(cfg =>
    {
        cfg.SaveToken = true;
        cfg.TokenValidationParameters = new TokenValidationParameters
        {
            ValidIssuer = Configuration["Authentication:BearerTokens:Issuer"],
            ValidAudience = Configuration["Authentication:BearerTokens:Audience"],
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Authentication:BearerTokens:Key"])),
            ValidateIssuerSigningKey = false,
            ValidateLifetime = true,
            ClockSkew = TimeSpan.Zero
        };
        cfg.Events = new JwtBearerEvents
        {

            OnAuthenticationFailed = context =>
            {
                var logger = context.HttpContext.RequestServices.GetRequiredService<ILoggerFactory>().CreateLogger(nameof(JwtBearerEvents));
                logger.LogError("Authentication failed.", context.Exception);
                return Task.CompletedTask;
            },

            OnMessageReceived = context =>
            {
                return Task.CompletedTask;
            },
            OnChallenge = context =>
            {
                var logger = context.HttpContext.RequestServices.GetRequiredService<ILoggerFactory>().CreateLogger(nameof(JwtBearerEvents));
                logger.LogError("OnChallenge error", context.Error, context.ErrorDescription);
                return Task.CompletedTask;
            }
        };
    });

    services.AddDbContext<ApplicationDbContext>(options =>
    {
        string useSqLite = Startup.Configuration["Data:useSqLite"];
        if (useSqLite.ToLower() == "true")
        {
            options.UseSqlite(Startup.Configuration["Data:SqlLiteConnectionString"]);
        }
        else
        {
            options.UseSqlServer(Startup.Configuration["Data:SqlServerConnectionString"]);
        }
        options.UseOpenIddict();
    });

    services.AddIdentity<ApplicationUser, ApplicationRole>()
        .AddEntityFrameworkStores<ApplicationDbContext>()
        .AddDefaultTokenProviders();

    //services.ConfigureApplicationCookie(options =>
    //{

    //    options.LoginPath = "/login";
    //    options.Events.OnRedirectToLogin = context =>
    //    {
    //        if (context.Request.Path.StartsWithSegments("/api") &&
    //            context.Response.StatusCode == (int)HttpStatusCode.OK)
    //        {
    //            context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
    //        }
    //        else
    //        {
    //            context.Response.Redirect(context.RedirectUri);
    //        }
    //        return Task.FromResult(0);
    //    };
    //});

    services.AddOAuthProviders();

    services.AddCustomOpenIddict();

    services.AddMemoryCache();

    services.RegisterCustomServices();

    services.AddAntiforgery(options => options.HeaderName = "X-XSRF-TOKEN");

    services.AddCustomizedMvc();

    // Node services are to execute any arbitrary nodejs code from .net
    services.AddNodeServices();

    services.AddSwaggerGen(c =>
    {
        c.SwaggerDoc("v1", new Info { Title = "AspNetCoreSpa", Version = "v1" });
    });
}

public void Configure(IApplicationBuilder app)
{
    app.AddDevMiddlewares();

    if (_hostingEnv.IsProduction())
    {
        app.UseResponseCompression();
    }

    app.SetupMigrations();

    app.UseXsrf();

    app.UseStaticFiles();

    app.UseAuthentication();

    app.UseMvc(routes =>
    {
        // http://stackoverflow.com/questions/25982095/using-googleoauth2authenticationoptions-got-a-redirect-uri-mismatch-error
        routes.MapRoute(name: "signin-google", template: "signin-google", defaults: new { controller = "Account", action = "ExternalLoginCallback" });

        routes.MapSpaFallbackRoute(
            name: "spa-fallback",
            defaults: new { controller = "Home", action = "Index" });
    });
}
</code>```

My IServiceCollection-Extensions:

```<code>public static IServiceCollection AddCustomizedMvc(this IServiceCollection services)
{
    services.AddMvc(options =>
    {
        options.Filters.Add(typeof(ModelValidationFilter));
    })
    .AddJsonOptions(options =>
    {
        options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
    });

    return services;
}

public static IServiceCollection AddOAuthProviders(this IServiceCollection services)
{
    services.AddAuthentication()
        .AddFacebook(o =>
        {
            o.AppId = Startup.Configuration["Authentication:Facebook:AppId"];
            o.AppSecret = Startup.Configuration["Authentication:Facebook:AppSecret"];
        });

    services.AddAuthentication()
        .AddGoogle(o =>
        {
            o.ClientId = Startup.Configuration["Authentication:Google:ClientId"];
            o.ClientSecret = Startup.Configuration["Authentication:Google:ClientSecret"];
        });
    services.AddAuthentication()
        .AddTwitter(o =>
        {
            o.ConsumerKey = Startup.Configuration["Authentication:Twitter:ConsumerKey"];
            o.ConsumerSecret = Startup.Configuration["Authentication:Twitter:ConsumerSecret"];
        });

    services.AddAuthentication()
        .AddMicrosoftAccount(o =>
        {
            o.ClientId= Startup.Configuration["Authentication:Microsoft:ClientId"];
            o.ClientSecret = Startup.Configuration["Authentication:Microsoft:ClientSecret"];
        });

    return services;
}

public static IServiceCollection AddCustomOpenIddict(this IServiceCollection services)
{

    // Configure Identity to use the same JWT claims as OpenIddict instead
    // of the legacy WS-Federation claims it uses by default (ClaimTypes),
    // which saves you from doing the mapping in your authorization controller.
    services.Configure<IdentityOptions>(options =>
    {
        options.ClaimsIdentity.UserNameClaimType = OpenIdConnectConstants.Claims.Name;
        options.ClaimsIdentity.UserIdClaimType = OpenIdConnectConstants.Claims.Subject;
        options.ClaimsIdentity.RoleClaimType = OpenIdConnectConstants.Claims.Role;

    });

    // Register the OpenIddict services.
    services.AddOpenIddict()
        // Register the Entity Framework stores.
        .AddEntityFrameworkCoreStores<ApplicationDbContext>()

        // Register the ASP.NET Core MVC binder used by OpenIddict.
        // Note: if you don't call this method, you won't be able to
        // bind OpenIdConnectRequest or OpenIdConnectResponse parameters.
        .AddMvcBinders()

        // Enable the token endpoint.
        .EnableTokenEndpoint("/connect/token")

        // Enable the password and the refresh token flows.
        .AllowPasswordFlow()
        .AllowRefreshTokenFlow()

        // During development, you can disable the HTTPS requirement.
        .DisableHttpsRequirement()

        // Register a new ephemeral key, that is discarded when the application
        // shuts down. Tokens signed using this key are automatically invalidated.
        // This method should only be used during development.
        .AddEphemeralSigningKey();

    // On production, using a X.509 certificate stored in the machine store is recommended.
    // You can generate a self-signed certificate using Pluralsight's self-cert utility:
    // https://s3.amazonaws.com/pluralsight-free/keith-brown/samples/SelfCert.zip
    //
    // services.AddOpenIddict()
    //     .AddSigningCertificate("7D2A741FE34CC2C7369237A5F2078988E17A6A75");
    //
    // Alternatively, you can also store the certificate as an embedded .pfx resource
    // directly in this assembly or in a file published alongside this project:
    //
    // services.AddOpenIddict()
    //     .AddSigningCertificate(
    //          assembly: typeof(Startup).GetTypeInfo().Assembly,
    //          resource: "AuthorizationServer.Certificate.pfx",
    //          password: "OpenIddict");

    return services;
}

public static IServiceCollection AddCustomDbContext(this IServiceCollection services)
{
    // Add framework services.

    return services;
}

public static IServiceCollection RegisterCustomServices(this IServiceCollection services)
{
    // New instance every time, only configuration class needs so its ok
    services.Configure<SmsSettings>(options => Startup.Configuration.GetSection("SmsSettingsTwillio").Bind(options));
    services.AddTransient<UserResolverService>();
    services.AddTransient<IEmailSender, EmailSender>();
    services.AddTransient<ISmsSender, SmsSender>();
    services.AddScoped<ApiExceptionFilter>();
    return services;
}
</code>```

Here my packages:

```<code><ItemGroup>
<PackageReference Include="AspNet.Security.OAuth.Introspection" Version="2.0.0-*" />
<PackageReference Include="AspNet.Security.OAuth.Validation" Version="2.0.0-*" />
<PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.Cookies" Version="2.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="2.0.0" />
<PackageReference Include="Microsoft.AspNetCore.AzureAppServicesIntegration" Version="2.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Diagnostics" Version="2.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore" Version="2.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="2.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc" Version="2.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Cors" Version="2.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Antiforgery" Version="2.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Authorization" Version="2.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.Google" Version="2.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.Facebook" Version="2.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.MicrosoftAccount" Version="2.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.Twitter" Version="2.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Server.IISIntegration" Version="2.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Server.Kestrel" Version="2.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Server.Kestrel.Https" Version="2.0.0" />
<PackageReference Include="Microsoft.AspNetCore.StaticFiles" Version="2.0.0" />
<PackageReference Include="Microsoft.Extensions.Caching.Memory" Version="2.0.0" />
<PackageReference Include="Microsoft.AspNetCore.ResponseCompression" Version="2.0.0" />
<PackageReference Include="Microsoft.AspNetCore.WebSockets" Version="2.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="2.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="2.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="2.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="2.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.UserSecrets" Version="2.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="2.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="2.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="2.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="2.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="2.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Http.Abstractions" Version="2.0.0" />
<PackageReference Include="Microsoft.AspNetCore.AngularServices" Version="1.1.0-beta-000002" />
<PackageReference Include="AspNet.Security.OAuth.GitHub" Version="1.0.0-beta3-final" />
<PackageReference Include="AspNet.Security.OAuth.LinkedIn" Version="1.0.0-beta3-final" />
<PackageReference Include="OpenIddict" Version="2.0.0-*" />
<PackageReference Include="OpenIddict.EntityFrameworkCore" Version="2.0.0-*" />
<PackageReference Include="OpenIddict.Mvc" Version="2.0.0-*" />
<PackageReference Include="SendGrid" Version="9.9.0" />
<PackageReference Include="MailKit" Version="1.18.0" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="1.0.0" />
<PackageReference Include="Swashbuckle.AspNetCore.SwaggerUI" Version="1.0.0" />
<PackageReference Include="Twilio" Version="5.6.3" />
<PackageReference Include="Stripe.net" Version="10.4.0" />
<PackageReference Include="Newtonsoft.Json" Version="10.0.3" />
<PackageReference Include="Webpack" Version="4.0.0" />
<PackageReference Include="Serilog" Version="2.5.0" />
<PackageReference Include="Serilog.Extensions.Logging" Version="2.0.2" />
<PackageReference Include="Serilog.Sinks.Seq" Version="3.3.3" />
<PackageReference Include="Bogus" Version="17.0.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="2.0.0">
  <PrivateAssets>All</PrivateAssets>
</PackageReference>
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="2.0.0">
  <PrivateAssets>All</PrivateAssets>
</PackageReference>

  <PackageReference Include="Microsoft.AspNetCore.Mvc.Razor.ViewCompilation" Version="2.0.0" PrivateAssets="All" />
  </ItemGroup>

  <ItemGroup>
<DotNetCliToolReference Include="Microsoft.DotNet.Watcher.Tools" Version="2.0.0" />
<DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="2.0.0" />
<DotNetCliToolReference Include="Microsoft.Extensions.SecretManager.Tools" Version="2.0.0" />
<DotNetCliToolReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="2.0.0" />
  </ItemGroup>
</code>```

Here are my logs:

```<code>info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
  Request starting HTTP/1.1 GET http://localhost:44331/api/profile/test
application/json; charset=UTF-8
info: Microsoft.AspNetCore.Authorization.DefaultAuthorizationService[2]
  Authorization failed for user: (null).
info: Microsoft.AspNetCore.Authorization.DefaultAuthorizationService[2]
  Authorization failed for user: (null).
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[3]
  Authorization failed for the request at filter
'Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter'.
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[3]
  Authorization failed for the request at filter
'Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter'.
info: Microsoft.AspNetCore.Mvc.ChallengeResult[1]
  Executing ChallengeResult with authentication schemes ().
info: Microsoft.AspNetCore.Mvc.ChallengeResult[1]
  Executing ChallengeResult with authentication schemes ().
info:
Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationHandler[12]
  AuthenticationScheme: Identity.Application was challenged.
info:
Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationHandler[12]
  AuthenticationScheme: Identity.Application was challenged.
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[2]
  Executed action
AspNetCoreSpa.Server.Controllers.api.ProfileController.Test (AspNetCoreSpa)
in 43.3105ms
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[2]
  Executed action
AspNetCoreSpa.Server.Controllers.api.ProfileController.Test (AspNetCoreSpa)
in 43.3105ms
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
  Request finished in 67.4133ms 302
infoinfo: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
  Request finished in 67.4133ms 302
: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
  Request starting HTTP/1.1 GET http://localhost:44331/Account/Login?
ReturnUrl=%2Fapi%2Fprofile%2Ftest application/json; charset=UTF-8
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
  Request starting HTTP/1.1 GET http://localhost:44331/Account/Login?
ReturnUrl=%2Fapi%2Fprofile%2Ftest application/json; charset=UTF-8
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[1]
  Executing action method
AspNetCoreSpa.Server.Controllers.HomeController.Index (AspNetCoreSpa) with
arguments ((null)) - ModelState is Valid
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[1]
  Executing action method
AspNetCoreSpa.Server.Controllers.HomeController.Index (AspNetCoreSpa) with
arguments ((null)) - ModelState is Valid
info: Microsoft.AspNetCore.Mvc.ViewFeatures.Internal.ViewResultExecutor[1]
  Executing ViewResult, running view at path /Views/Home/Index.cshtml.
info: Microsoft.AspNetCore.Mvc.ViewFeatures.Internal.ViewResultExecutor[1]
  Executing ViewResult, running view at path /Views/Home/Index.cshtml.
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[2]
  Executed action AspNetCoreSpa.Server.Controllers.HomeController.Index
(AspNetCoreSpa) in 13.2746ms
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[2]
  Executed action AspNetCoreSpa.Server.Controllers.HomeController.Index
(AspNetCoreSpa) in 13.2746ms
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
  Request finished in 79.2352ms 200 text/html; charset=utf-8
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
  Request finished in 79.2352ms 200 text/html; charset=utf-8
</code>```

I wonder about the following line:

Authorization failed for user: (null)

Already found this Authorization failed for user: (null)
but there is no answer yet and I think it's a .NET Core 1 issue.

答:
For me, it was related to Cross-Origin Resource Sharing (CORS). I have an API in an App Service in Azure with CORS enabled. I got the 302 to disappear when I added the callers of the API to the list of allowed origins.

I had to do this even though I  had already added these origins in my aspnet core startup code.

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to migrate this project
https://github.com/asadsahi/AspNetCoreSpa from .net core 1.1 to 2.0 but have a problem after a successful login. After the login my GET api calls e. g. to https://localhost:44331/api/profile/test end up with a redirect (302) and I don't know why. I received a bearer token and it looks fine.

Request header format:
authorization: Bearer [token]

[Route("api/[controller]")]
public class ProfileController : BaseController
{
    private readonly UserManager<ApplicationUser> _userManager;
    private readonly ILogger _logger;

    public ProfileController(ILoggerFactory loggerFactory, UserManager<ApplicationUser> userManager)
    {
        _logger = loggerFactory.CreateLogger<ProfileController>();
        _userManager = userManager;
    }

    [HttpGet("test")]
    public async Task<IActionResult> Test()
    {
        return  Json(ModelState.GetModelErrors());
    }
}

[Authorize]
[ServiceFilter(typeof(ApiExceptionFilter))]
[ResponseCache(Location = ResponseCacheLocation.None, NoStore = true)]
public class BaseController : Controller
{
    public BaseController()
    {
    }
}

Startup.cs:

public void ConfigureServices(IServiceCollection services)
{
    if (_hostingEnv.IsDevelopment())
    {
        services.AddSslCertificate(_hostingEnv);
    }
    else
    {
        services.Configure<MvcOptions>(o => o.Filters.Add(new RequireHttpsAttribute()));
    }
    services.AddOptions();
    services.AddCors();
    services.AddLogging();
    services.AddResponseCompression(options =>
    {
        options.MimeTypes = Helpers.DefaultMimeTypes;
    });

    services.AddAuthentication(sharedOptions =>
    {
        sharedOptions.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
        sharedOptions.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
        sharedOptions.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;

    }).AddJwtBearer(cfg =>
    {
        cfg.SaveToken = true;
        cfg.TokenValidationParameters = new TokenValidationParameters
        {
            ValidIssuer = Configuration["Authentication:BearerTokens:Issuer"],
            ValidAudience = Configuration["Authentication:BearerTokens:Audience"],
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Authentication:BearerTokens:Key"])),
            ValidateIssuerSigningKey = false,
            ValidateLifetime = true,
            ClockSkew = TimeSpan.Zero
        };
        cfg.Events = new JwtBearerEvents
        {

            OnAuthenticationFailed = context =>
            {
                var logger = context.HttpContext.RequestServices.GetRequiredService<ILoggerFactory>().CreateLogger(nameof(JwtBearerEvents));
                logger.LogError("Authentication failed.", context.Exception);
                return Task.CompletedTask;
            },

            OnMessageReceived = context =>
            {
                return Task.CompletedTask;
            },
            OnChallenge = context =>
            {
                var logger = context.HttpContext.RequestServices.GetRequiredService<ILoggerFactory>().CreateLogger(nameof(JwtBearerEvents));
                logger.LogError("OnChallenge error", context.Error, context.ErrorDescription);
                return Task.CompletedTask;
            }
        };
    });

    services.AddDbContext<ApplicationDbContext>(options =>
    {
        string useSqLite = Startup.Configuration["Data:useSqLite"];
        if (useSqLite.ToLower() == "true")
        {
            options.UseSqlite(Startup.Configuration["Data:SqlLiteConnectionString"]);
        }
        else
        {
            options.UseSqlServer(Startup.Configuration["Data:SqlServerConnectionString"]);
        }
        options.UseOpenIddict();
    });

    services.AddIdentity<ApplicationUser, ApplicationRole>()
        .AddEntityFrameworkStores<ApplicationDbContext>()
        .AddDefaultTokenProviders();

    //services.ConfigureApplicationCookie(options =>
    //{

    //    options.LoginPath = "/login";
    //    options.Events.OnRedirectToLogin = context =>
    //    {
    //        if (context.Request.Path.StartsWithSegments("/api") &&
    //            context.Response.StatusCode == (int)HttpStatusCode.OK)
    //        {
    //            context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
    //        }
    //        else
    //        {
    //            context.Response.Redirect(context.RedirectUri);
    //        }
    //        return Task.FromResult(0);
    //    };
    //});

    services.AddOAuthProviders();

    services.AddCustomOpenIddict();

    services.AddMemoryCache();

    services.RegisterCustomServices();

    services.AddAntiforgery(options => options.HeaderName = "X-XSRF-TOKEN");

    services.AddCustomizedMvc();

    // Node services are to execute any arbitrary nodejs code from .net
    services.AddNodeServices();

    services.AddSwaggerGen(c =>
    {
        c.SwaggerDoc("v1", new Info { Title = "AspNetCoreSpa", Version = "v1" });
    });
}

public void Configure(IApplicationBuilder app)
{
    app.AddDevMiddlewares();

    if (_hostingEnv.IsProduction())
    {
        app.UseResponseCompression();
    }

    app.SetupMigrations();

    app.UseXsrf();

    app.UseStaticFiles();

    app.UseAuthentication();

    app.UseMvc(routes =>
    {
        // http://stackoverflow.com/questions/25982095/using-googleoauth2authenticationoptions-got-a-redirect-uri-mismatch-error
        routes.MapRoute(name: "signin-google", template: "signin-google", defaults: new { controller = "Account", action = "ExternalLoginCallback" });

        routes.MapSpaFallbackRoute(
            name: "spa-fallback",
            defaults: new { controller = "Home", action = "Index" });
    });
}

My IServiceCollection-Extensions:

public static IServiceCollection AddCustomizedMvc(this IServiceCollection services)
{
    services.AddMvc(options =>
    {
        options.Filters.Add(typeof(ModelValidationFilter));
    })
    .AddJsonOptions(options =>
    {
        options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
    });

    return services;
}

public static IServiceCollection AddOAuthProviders(this IServiceCollection services)
{
    services.AddAuthentication()
        .AddFacebook(o =>
        {
            o.AppId = Startup.Configuration["Authentication:Facebook:AppId"];
            o.AppSecret = Startup.Configuration["Authentication:Facebook:AppSecret"];
        });

    services.AddAuthentication()
        .AddGoogle(o =>
        {
            o.ClientId = Startup.Configuration["Authentication:Google:ClientId"];
            o.ClientSecret = Startup.Configuration["Authentication:Google:ClientSecret"];
        });
    services.AddAuthentication()
        .AddTwitter(o =>
        {
            o.ConsumerKey = Startup.Configuration["Authentication:Twitter:ConsumerKey"];
            o.ConsumerSecret = Startup.Configuration["Authentication:Twitter:ConsumerSecret"];
        });

    services.AddAuthentication()
        .AddMicrosoftAccount(o =>
        {
            o.ClientId= Startup.Configuration["Authentication:Microsoft:ClientId"];
            o.ClientSecret = Startup.Configuration["Authentication:Microsoft:ClientSecret"];
        });

    return services;
}

public static IServiceCollection AddCustomOpenIddict(this IServiceCollection services)
{

    // Configure Identity to use the same JWT claims as OpenIddict instead
    // of the legacy WS-Federation claims it uses by default (ClaimTypes),
    // which saves you from doing the mapping in your authorization controller.
    services.Configure<IdentityOptions>(options =>
    {
        options.ClaimsIdentity.UserNameClaimType = OpenIdConnectConstants.Claims.Name;
        options.ClaimsIdentity.UserIdClaimType = OpenIdConnectConstants.Claims.Subject;
        options.ClaimsIdentity.RoleClaimType = OpenIdConnectConstants.Claims.Role;

    });

    // Register the OpenIddict services.
    services.AddOpenIddict()
        // Register the Entity Framework stores.
        .AddEntityFrameworkCoreStores<ApplicationDbContext>()

        // Register the ASP.NET Core MVC binder used by OpenIddict.
        // Note: if you don't call this method, you won't be able to
        // bind OpenIdConnectRequest or OpenIdConnectResponse parameters.
        .AddMvcBinders()

        // Enable the token endpoint.
        .EnableTokenEndpoint("/connect/token")

        // Enable the password and the refresh token flows.
        .AllowPasswordFlow()
        .AllowRefreshTokenFlow()

        // During development, you can disable the HTTPS requirement.
        .DisableHttpsRequirement()

        // Register a new ephemeral key, that is discarded when the application
        // shuts down. Tokens signed using this key are automatically invalidated.
        // This method should only be used during development.
        .AddEphemeralSigningKey();

    // On production, using a X.509 certificate stored in the machine store is recommended.
    // You can generate a self-signed certificate using Pluralsight's self-cert utility:
    // https://s3.amazonaws.com/pluralsight-free/keith-brown/samples/SelfCert.zip
    //
    // services.AddOpenIddict()
    //     .AddSigningCertificate("7D2A741FE34CC2C7369237A5F2078988E17A6A75");
    //
    // Alternatively, you can also store the certificate as an embedded .pfx resource
    // directly in this assembly or in a file published alongside this project:
    //
    // services.AddOpenIddict()
    //     .AddSigningCertificate(
    //          assembly: typeof(Startup).GetTypeInfo().Assembly,
    //          resource: "AuthorizationServer.Certificate.pfx",
    //          password: "OpenIddict");

    return services;
}

public static IServiceCollection AddCustomDbContext(this IServiceCollection services)
{
    // Add framework services.

    return services;
}

public static IServiceCollection RegisterCustomServices(this IServiceCollection services)
{
    // New instance every time, only configuration class needs so its ok
    services.Configure<SmsSettings>(options => Startup.Configuration.GetSection("SmsSettingsTwillio").Bind(options));
    services.AddTransient<UserResolverService>();
    services.AddTransient<IEmailSender, EmailSender>();
    services.AddTransient<ISmsSender, SmsSender>();
    services.AddScoped<ApiExceptionFilter>();
    return services;
}

Here my packages:

<ItemGroup>
<PackageReference Include="AspNet.Security.OAuth.Introspection" Version="2.0.0-*" />
<PackageReference Include="AspNet.Security.OAuth.Validation" Version="2.0.0-*" />
<PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.Cookies" Version="2.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="2.0.0" />
<PackageReference Include="Microsoft.AspNetCore.AzureAppServicesIntegration" Version="2.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Diagnostics" Version="2.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore" Version="2.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="2.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc" Version="2.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Cors" Version="2.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Antiforgery" Version="2.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Authorization" Version="2.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.Google" Version="2.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.Facebook" Version="2.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.MicrosoftAccount" Version="2.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.Twitter" Version="2.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Server.IISIntegration" Version="2.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Server.Kestrel" Version="2.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Server.Kestrel.Https" Version="2.0.0" />
<PackageReference Include="Microsoft.AspNetCore.StaticFiles" Version="2.0.0" />
<PackageReference Include="Microsoft.Extensions.Caching.Memory" Version="2.0.0" />
<PackageReference Include="Microsoft.AspNetCore.ResponseCompression" Version="2.0.0" />
<PackageReference Include="Microsoft.AspNetCore.WebSockets" Version="2.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="2.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="2.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="2.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="2.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.UserSecrets" Version="2.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="2.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="2.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="2.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="2.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="2.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Http.Abstractions" Version="2.0.0" />
<PackageReference Include="Microsoft.AspNetCore.AngularServices" Version="1.1.0-beta-000002" />
<PackageReference Include="AspNet.Security.OAuth.GitHub" Version="1.0.0-beta3-final" />
<PackageReference Include="AspNet.Security.OAuth.LinkedIn" Version="1.0.0-beta3-final" />
<PackageReference Include="OpenIddict" Version="2.0.0-*" />
<PackageReference Include="OpenIddict.EntityFrameworkCore" Version="2.0.0-*" />
<PackageReference Include="OpenIddict.Mvc" Version="2.0.0-*" />
<PackageReference Include="SendGrid" Version="9.9.0" />
<PackageReference Include="MailKit" Version="1.18.0" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="1.0.0" />
<PackageReference Include="Swashbuckle.AspNetCore.SwaggerUI" Version="1.0.0" />
<PackageReference Include="Twilio" Version="5.6.3" />
<PackageReference Include="Stripe.net" Version="10.4.0" />
<PackageReference Include="Newtonsoft.Json" Version="10.0.3" />
<PackageReference Include="Webpack" Version="4.0.0" />
<PackageReference Include="Serilog" Version="2.5.0" />
<PackageReference Include="Serilog.Extensions.Logging" Version="2.0.2" />
<PackageReference Include="Serilog.Sinks.Seq" Version="3.3.3" />
<PackageReference Include="Bogus" Version="17.0.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="2.0.0">
  <PrivateAssets>All</PrivateAssets>
</PackageReference>
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="2.0.0">
  <PrivateAssets>All</PrivateAssets>
</PackageReference>

  <PackageReference Include="Microsoft.AspNetCore.Mvc.Razor.ViewCompilation" Version="2.0.0" PrivateAssets="All" />
  </ItemGroup>

  <ItemGroup>
<DotNetCliToolReference Include="Microsoft.DotNet.Watcher.Tools" Version="2.0.0" />
<DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="2.0.0" />
<DotNetCliToolReference Include="Microsoft.Extensions.SecretManager.Tools" Version="2.0.0" />
<DotNetCliToolReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="2.0.0" />
  </ItemGroup>

Here are my logs:

info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
  Request starting HTTP/1.1 GET http://localhost:44331/api/profile/test
application/json; charset=UTF-8
info: Microsoft.AspNetCore.Authorization.DefaultAuthorizationService[2]
  Authorization failed for user: (null).
info: Microsoft.AspNetCore.Authorization.DefaultAuthorizationService[2]
  Authorization failed for user: (null).
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[3]
  Authorization failed for the request at filter
'Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter'.
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[3]
  Authorization failed for the request at filter
'Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter'.
info: Microsoft.AspNetCore.Mvc.ChallengeResult[1]
  Executing ChallengeResult with authentication schemes ().
info: Microsoft.AspNetCore.Mvc.ChallengeResult[1]
  Executing ChallengeResult with authentication schemes ().
info:
Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationHandler[12]
  AuthenticationScheme: Identity.Application was challenged.
info:
Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationHandler[12]
  AuthenticationScheme: Identity.Application was challenged.
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[2]
  Executed action
AspNetCoreSpa.Server.Controllers.api.ProfileController.Test (AspNetCoreSpa)
in 43.3105ms
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[2]
  Executed action
AspNetCoreSpa.Server.Controllers.api.ProfileController.Test (AspNetCoreSpa)
in 43.3105ms
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
  Request finished in 67.4133ms 302
infoinfo: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
  Request finished in 67.4133ms 302
: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
  Request starting HTTP/1.1 GET http://localhost:44331/Account/Login?
ReturnUrl=%2Fapi%2Fprofile%2Ftest application/json; charset=UTF-8
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
  Request starting HTTP/1.1 GET http://localhost:44331/Account/Login?
ReturnUrl=%2Fapi%2Fprofile%2Ftest application/json; charset=UTF-8
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[1]
  Executing action method
AspNetCoreSpa.Server.Controllers.HomeController.Index (AspNetCoreSpa) with
arguments ((null)) - ModelState is Valid
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[1]
  Executing action method
AspNetCoreSpa.Server.Controllers.HomeController.Index (AspNetCoreSpa) with
arguments ((null)) - ModelState is Valid
info: Microsoft.AspNetCore.Mvc.ViewFeatures.Internal.ViewResultExecutor[1]
  Executing ViewResult, running view at path /Views/Home/Index.cshtml.
info: Microsoft.AspNetCore.Mvc.ViewFeatures.Internal.ViewResultExecutor[1]
  Executing ViewResult, running view at path /Views/Home/Index.cshtml.
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[2]
  Executed action AspNetCoreSpa.Server.Controllers.HomeController.Index
(AspNetCoreSpa) in 13.2746ms
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[2]
  Executed action AspNetCoreSpa.Server.Controllers.HomeController.Index
(AspNetCoreSpa) in 13.2746ms
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
  Request finished in 79.2352ms 200 text/html; charset=utf-8
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
  Request finished in 79.2352ms 200 text/html; charset=utf-8

I wonder about the following line:

Authorization failed for user: (null)

Already found this Authorization failed for user: (null)
but there is no answer yet and I think it's a .NET Core 1 issue.


问:
How does a wrapper work for JsonUtility
So I've been looking to convert my Json array into an array of objects in Unity. I've found my solution from a 2 yeard old thread without explanation but I'm curious as to how it actually works.

If I use Visual Studio to look for the definition of FromJson it shows me this

public static T FromJson<T>(string json);

As I understand is that FromJson asks for an object to be filled, I give the class MyWrapper but besides telling MyWrapper that he contains a list of Question I never ask it to create a new item in the list. So how does it actually fill the list?

C#

```<code>MyWrapper wrappedQuestions = JsonUtility.FromJson<MyWrapper>(jsonString);

[Serializable]
public class MyWrapper
{
    public List<Question> questions;
}

[Serializable]
public class Question
{
    public int questionType;
    public string questionString;
    public int questionAnswer;
}
</code>```

Json

```<code>{
    "questions": [
      {
        "questionType":  1,
        "questionString": "4^2",
        "questionAnswer": 16
      },
      {
        "questionType":  2,
        "questionString": "√(25)",
        "questionAnswer": 5
      }
    ]
}
</code>```

I'm still a beginner programmer so I hope I'am able to ask such questions here.

答:
As JSON stands for Javascript Object Notation, JSON objects (strings) follow a pattern. For any string to parsed and converted to the object, it has to be a valid JSON. It has certain rules/syntax,

for example

[ ] is  for array/list,

{ } is for objects

and every object can contain key-value pairs (separated by colon :) to represent variables along with their values

```<code>{ "Key" : "Value" }
</code>```

Now JSON parser is aware of these rules so it can check if any string is valid JSON.

What does it need to know to convert a JSON into a class object?

The class type you provide here :

```<code>JsonUtility.FromJson<MyWrapper>(jsonString);
</code>```

is MyWrapper.

It should have the same structure as your jsonString.

Let's break down your jsonString to map it with the class structure:

This represents a MyWrapper object. which contains only one property called questions, which is an empty list.

```<code>{
    "questions": [ ]
}
</code>```

if questions have any element in it, it would be of type Question we can write it as following in JSON:

```<code>{
    "questionType":  1,  // int value
    "questionString": "4^2", // string value
    "questionAnswer": 16 // int value
}
</code>```

now if questions have more than one elements they would be separated by a comma:

```<code>"questions": [
  {
    "questionType":  1,
    "questionString": "4^2",
    "questionAnswer": 16
  },
  {
    "questionType":  2,
    "questionString": "√(25)",
    "questionAnswer": 4
  },
  ...
]
</code>```

JSON parser is aware of all these rules so by looking at class structure it can parse the string and create an object of the stated class provided that JSON is valid and class structure matches with JSON structure.

That's all I could say about this, hope you got the basic understanding.

Title: How does a wrapper work for JsonUtility

Body:
So I've been looking to convert my Json array into an array of objects in Unity. I've found my solution from a 2 yeard old thread without explanation but I'm curious as to how it actually works.

If I use Visual Studio to look for the definition of FromJson it shows me this

public static T FromJson<T>(string json);

As I understand is that FromJson asks for an object to be filled, I give the class MyWrapper but besides telling MyWrapper that he contains a list of Question I never ask it to create a new item in the list. So how does it actually fill the list?

C#

MyWrapper wrappedQuestions = JsonUtility.FromJson<MyWrapper>(jsonString);

[Serializable]
public class MyWrapper
{
    public List<Question> questions;
}

[Serializable]
public class Question
{
    public int questionType;
    public string questionString;
    public int questionAnswer;
}

Json

{
    "questions": [
      {
        "questionType":  1,
        "questionString": "4^2",
        "questionAnswer": 16
      },
      {
        "questionType":  2,
        "questionString": "√(25)",
        "questionAnswer": 5
      }
    ]
}

I'm still a beginner programmer so I hope I'am able to ask such questions here.

Body:
As JSON stands for Javascript Object Notation, JSON objects (strings) follow a pattern. For any string to parsed and converted to the object, it has to be a valid JSON. It has certain rules/syntax,

for example

[ ] is  for array/list,

{ } is for objects

and every object can contain key-value pairs (separated by colon :) to represent variables along with their values

{ "Key" : "Value" }

Now JSON parser is aware of these rules so it can check if any string is valid JSON.

What does it need to know to convert a JSON into a class object?

The class type you provide here :

JsonUtility.FromJson<MyWrapper>(jsonString);

is MyWrapper.

It should have the same structure as your jsonString.

Let's break down your jsonString to map it with the class structure:

This represents a MyWrapper object. which contains only one property called questions, which is an empty list.

{
    "questions": [ ]
}

if questions have any element in it, it would be of type Question we can write it as following in JSON:

{
    "questionType":  1,  // int value
    "questionString": "4^2", // string value
    "questionAnswer": 16 // int value
}

now if questions have more than one elements they would be separated by a comma:

"questions": [
  {
    "questionType":  1,
    "questionString": "4^2",
    "questionAnswer": 16
  },
  {
    "questionType":  2,
    "questionString": "√(25)",
    "questionAnswer": 4
  },
  ...
]

JSON parser is aware of all these rules so by looking at class structure it can parse the string and create an object of the stated class provided that JSON is valid and class structure matches with JSON structure.

That's all I could say about this, hope you got the basic understanding.


问:
How to change timezone on docker private registry running container?
How can I change timezone/time on my running docker private registry container

Host OS: CentOS 7
Docker Version:

```<code>Server:
Version:      17.09.0-ce
API version:  1.32 (minimum version 1.12)
Go version:   go1.8.3
Git commit:   afdb6d4
Built:        Tue Sep 26 22:42:49 2017
OS/Arch:      linux/amd64
Experimental: false
</code>```

Docker registry image: registry:2 ID: a07e3f32a779

Tried execute on container:

    export TZ=Europe/Warsaw
    ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone

but without any result for real time.

Same solution works on another containers without any problems.

Any Ideas?

Edit:

Recreated container with compose like this:

```<code>apache:
  image: "httpd:2.4"
  hostname: deleted
  restart: always
  environment:
    - TZ=Europe/Warsaw
  ports:
    - 5043:5043
  links:
    - registry:registry
  volumes:
    - /opt/docker-registry-bundle/auth:/usr/local/apache2/conf
    - /etc/timezone:/etc/timezone:ro

registry:
  image: registry:2
  restart: always
  environment:
    - TZ=Europe/Warsaw
  ports:
    - 127.0.0.1:5000:5000
  volumes:
    - /opt/docker-registry-bundle/registry-data:/var/lib/registry
    - /etc/timezone:/etc/timezone:ro
</code>```

On apache container time is ok.
On registry container still doesn't work.

答:
The following should work when executed inside container:</p>

```<code>echo "Europe/Warsaw" > /etc/timezone
dpkg-reconfigure -f noninteractive tzdata
</code>```

Body:
How can I change timezone/time on my running docker private registry container

Host OS: CentOS 7
Docker Version:

Server:
Version:      17.09.0-ce
API version:  1.32 (minimum version 1.12)
Go version:   go1.8.3
Git commit:   afdb6d4
Built:        Tue Sep 26 22:42:49 2017
OS/Arch:      linux/amd64
Experimental: false

Docker registry image: registry:2 ID: a07e3f32a779

Tried execute on container:

    export TZ=Europe/Warsaw
    ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone

but without any result for real time.

Same solution works on another containers without any problems.

Any Ideas?

Edit:

Recreated container with compose like this:

apache:
  image: "httpd:2.4"
  hostname: deleted
  restart: always
  environment:
    - TZ=Europe/Warsaw
  ports:
    - 5043:5043
  links:
    - registry:registry
  volumes:
    - /opt/docker-registry-bundle/auth:/usr/local/apache2/conf
    - /etc/timezone:/etc/timezone:ro

registry:
  image: registry:2
  restart: always
  environment:
    - TZ=Europe/Warsaw
  ports:
    - 127.0.0.1:5000:5000
  volumes:
    - /opt/docker-registry-bundle/registry-data:/var/lib/registry
    - /etc/timezone:/etc/timezone:ro

On apache container time is ok.
On registry container still doesn't work.

Body:
The following should work when executed inside container:

echo "Europe/Warsaw" > /etc/timezone
dpkg-reconfigure -f noninteractive tzdata


问:
how to convert list<enum> to string. I need save string in database not number(enum) in C#
its my enum

```<code>public enum Employee_roles
{
    admin,
    controller,
    planner,
    stockkeeper,
    client,
    bpengineer,
    superintendent,
    seniorengineer,
    procurementmanager,
    hseadmin,
    hseclient,
    rawadmin,
}
</code>```

this model class

```<code>public class access_right
{

    public string id { get; set; }
    public string model { get; set; }
    [JsonConverter(typeof(StringEnumConverter))]
    public method method { get; set; }
    [JsonConverter(typeof(StringEnumConverter))]
    public List<Employee_roles> roles { get; set; }
    public List<string> email { get; set; }
    [JsonConverter(typeof(StringEnumConverter))]
    public access_type access { get; set; }

}
</code>```

**roles property is List. if it's not list no problem [JsonConverter(typeof(StringEnumConverter))] this method working. But List how to convert please help me **

答:
If you want to save for example your roles as strings, you can use the JsonPropertyAttribute.ItemConverterType property like so:</p>

```<code>[JsonProperty (ItemConverterType = typeof(StringEnumConverter))]
public List<Employee_roles> roles { get; set; }
</code>```

Body:
its my enum

public enum Employee_roles
{
    admin,
    controller,
    planner,
    stockkeeper,
    client,
    bpengineer,
    superintendent,
    seniorengineer,
    procurementmanager,
    hseadmin,
    hseclient,
    rawadmin,
}

this model class

public class access_right
{

    public string id { get; set; }
    public string model { get; set; }
    [JsonConverter(typeof(StringEnumConverter))]
    public method method { get; set; }
    [JsonConverter(typeof(StringEnumConverter))]
    public List<Employee_roles> roles { get; set; }
    public List<string> email { get; set; }
    [JsonConverter(typeof(StringEnumConverter))]
    public access_type access { get; set; }

}

**roles property is List. if it's not list no problem [JsonConverter(typeof(StringEnumConverter))] this method working. But List how to convert please help me **

Body:
If you want to save for example your roles as strings, you can use the JsonPropertyAttribute.ItemConverterType property like so:

[JsonProperty (ItemConverterType = typeof(StringEnumConverter))]
public List<Employee_roles> roles { get; set; }


问:
Get last modified file without enumerating all files
In c#, given a folder path, is there a way to get the last modified file without getting all files?
I need to quickly find folders that have been updated after a certain time and if the file that was last modified is before the time, i want to skip the folder entirely.
I noticed that folder's last modified time does not get updated when one of its file get updated so this approach does't work.</p>

答:
Try this.

```<code>DirectoryInfo di = new DirectoryInfo("strPath");
DateTime dt = di.LastWriteTime;
</code>```

Then you should use

```<code>Directory.EnumerateFiles(strPath, "*.*", SearchOption.TopDirectoryOnly);
</code>```

Then loop the above collection and get FileInfo() for each file.

I don't see a way how can you get the modified date of a file w/o getting reference to FileInfo() on that file.

I don't think FileInfo will get this file as far as I know.

ContentLicense: CC BY-SA 2.5

Body:
Try this.

DirectoryInfo di = new DirectoryInfo("strPath");
DateTime dt = di.LastWriteTime;

Then you should use

Directory.EnumerateFiles(strPath, "*.*", SearchOption.TopDirectoryOnly);

Then loop the above collection and get FileInfo() for each file.

I don't see a way how can you get the modified date of a file w/o getting reference to FileInfo() on that file.

I don't think FileInfo will get this file as far as I know.


问:
FPDF error: Some data has already been output, can't send PDF file on 000webhost
I am using FPDF class to generate a pdf on my website. Everything worked well until last few weeks when I started getting error:

```<code>FPDF error: Some data has already been output, can't send PDF file
</code>```

During last few weeks haven't change anything in my code and I have also checked for any output execpt the fpdf (including unecessary space before php, disabled BOM signature etc.)

I have my website on 000webhost.com so I have also disabled the analytic code at the end of the page, but the pdf still doesn't work. The only trace I have left is misterious "" in a source code (I can see it when checking source code in Chrome browser).

I cant get to work even this simple example:

```<code><?php
require('fpdf.php');
$pdf = new FPDF();
$pdf->AddPage()
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>
</code>```

Is there a way to disable any other output on web page by php? or does someone use fpdf on 000webhost?

答:
I putted this to fix this problem in the beggining (ob_clean) doesn't change PDF structure:</p>

```<code>require('fpdf/fpdf.php');
ob_clean();
</code>```

Body:
I am using FPDF class to generate a pdf on my website. Everything worked well until last few weeks when I started getting error:

FPDF error: Some data has already been output, can't send PDF file

During last few weeks haven't change anything in my code and I have also checked for any output execpt the fpdf (including unecessary space before php, disabled BOM signature etc.)

I have my website on 000webhost.com so I have also disabled the analytic code at the end of the page, but the pdf still doesn't work. The only trace I have left is misterious "" in a source code (I can see it when checking source code in Chrome browser).

I cant get to work even this simple example:

<?php
require('fpdf.php');
$pdf = new FPDF();
$pdf->AddPage()
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>

Is there a way to disable any other output on web page by php? or does someone use fpdf on 000webhost?

Body:
I putted this to fix this problem in the beggining (ob_clean) doesn't change PDF structure:

require('fpdf/fpdf.php');
ob_clean();


问:
How to update vba code in multiple excel macro-enabled files?
I have a bunch of excel files with same VBA code in all of them. They were created/cloned from a single file(template file) and then stored with some data in it. So I would like to update the VBA code in all the excel files including template file (an empty excel file with no data in it). Is there a way to do the same in a single shot using python script or something.</p>

答: You can do it in VBA if the files have had the "Trust Access to the VBA project object model" option set on. http://www.cpearson.com/excel/vbe.aspx</p>


问:
Convolutional Neural Network using TensorFlow
I'm building a CNN model using Tensorflow, without the use of any frontend APIs such as Keras. I'm creating a VGG-16 model and using the pre-trained weights, and want to fine tune the last layers to serve my purpose.

Following the tutorial here, http://cv-tricks.com/tensorflow-tutorial/training-convolutional-neural-network-for-image-classification/
I re-created the training script and modified as per my requirements. However, my training does not happen and the training accuracy is stuck at 50.00% and validation accuracy is forming a pattern repeating the numbers.
Attached is the screenshot of the same.

I have been stuck on this for days now and can't seem to find the error. Any help is appreciated.

The code is pretty long and hence here is the gist file for the same

答:
Your cross entropy is wrong, you are comparing your logits with the softmax of your logits.

This:

```<code>cross_entropy = tf.nn.softmax_cross_entropy_with_logits(logits=layer_fc2,
                                                    labels=y_pred)
</code>```

Should be:

```<code>cross_entropy = tf.nn.softmax_cross_entropy_with_logits(logits=layer_fc2,
                                                    labels=y_true)
</code>```

Some things to note. I would not train on some data point and then evaluate on the same datapoint. Your training accuracy is probably going to be biased by doing so. Another point to note ist that tf.argmax(tf.softmax(logits)) is the same as tf.argmax(logits).

Body:
Your cross entropy is wrong, you are comparing your logits with the softmax of your logits.

This:

cross_entropy = tf.nn.softmax_cross_entropy_with_logits(logits=layer_fc2,
                                                    labels=y_pred)

Should be:

cross_entropy = tf.nn.softmax_cross_entropy_with_logits(logits=layer_fc2,
                                                    labels=y_true)

Some things to note. I would not train on some data point and then evaluate on the same datapoint. Your training accuracy is probably going to be biased by doing so. Another point to note ist that tf.argmax(tf.softmax(logits)) is the same as tf.argmax(logits).


问:
YII2 Kartik - ExportMenu Export data with checked item only
I include Kartik yii2 ExportMenu plugin and its working fine for all data export but now I want to export only selected rows which is checked on grid.

```<code><?php
  $gridColumns = [
      ['class' => 'yii\grid\SerialColumn'],
      'username',
      'email',
      [
         'label' => Yii::t('app','User Access'),
         'value' => function($model){
              if($model->access_level == 1) { return 'Read/Write/Import/Export'; }
              if($model->access_level == 2) { return 'Read/Write'; }
              if($model->access_level == 3) { return 'Read'; }
            }
      ],
      'fullname',
      // [
      //    'label' => Yii::t('app','Status'),
      //    'value' => function($model){
      //         if($model->status == 10) { return 'Active'; }
      //         if($model->status == 0) { return 'Inactive'; }
      //       }
      // ],
      [
     'attribute' => 'created_at',
     'format' => ['date' , 'php:d/m/Y'],
     'label' => Yii::t('app','Created On'),
     'headerOptions' => ['style' => 'width:12%;'],
      ],
      [
         'attribute' => 'updated_at',
         'format' => ['date' , 'php:d/m/Y'],
         'label' => Yii::t('app','Modified On'),
         'headerOptions' => ['style' => 'width:12%;'],
      ],
      // 'updated_by',
      [
         'attribute' => 'updated_by',
         'label' => Yii::t('app','Modified By'),
         'headerOptions' => ['style' => 'width:12%;'],
        'value' => 'user.username',
        //  'value' => function($model){
        //       return $model->user->username;
        // }
      ],

      // ['class' => 'yii\grid\ActionColumn'],
  ];
      echo ExportMenu::widget([
               'dataProvider' => $dataProvider,
               'columns' => $gridColumns,
               'target' => ExportMenu::TARGET_BLANK,
               'showConfirmAlert' => false,
               'filename' => 'Users',
               'dropdownOptions' => [
                'label' => 'Export',
                'class' => 'btn btn-info',
                'export' => true,
                'toolbar'=>[
                '{export}',
                '{toggleData}'
                ]
              ],
               'exportConfig'=>[
               ExportMenu::FORMAT_HTML=>false,
               ExportMenu::FORMAT_TEXT=>false,
               ExportMenu::FORMAT_PDF=>false,
               ExportMenu::FORMAT_EXCEL=>false,
               ],
          ]);?>
</code>```

Can anyone please help me to export data which is checked only .
If you need any other information related code please ask.
Thanks.

答:
Add a column to your columns onfiguration with this param:

```<code>[
    'class' => 'kartik\grid\CheckboxColumn',
    'headerOptions' => ['class' => 'kartik-sheet-style'],
],
</code>```

And after you need to write your own code that will filter the data provider to return only selected rows in export menu. So your grid view data provider and export menu data provider will become different and you need to control the export menu data provider via the selected rows of grid view.

For get selected rows of GriView in JS you can to this:

```<code>var keys = $('#grid').yiiGridView('getSelectedRows');
// keys is an array consisting of the keys associated with the selected rows
</code>```

For more info visit: Data widgets Yii2

Body:
I include Kartik yii2 ExportMenu plugin and its working fine for all data export but now I want to export only selected rows which is checked on grid.

<?php
  $gridColumns = [
      ['class' => 'yii\grid\SerialColumn'],
      'username',
      'email',
      [
         'label' => Yii::t('app','User Access'),
         'value' => function($model){
              if($model->access_level == 1) { return 'Read/Write/Import/Export'; }
              if($model->access_level == 2) { return 'Read/Write'; }
              if($model->access_level == 3) { return 'Read'; }
            }
      ],
      'fullname',
      // [
      //    'label' => Yii::t('app','Status'),
      //    'value' => function($model){
      //         if($model->status == 10) { return 'Active'; }
      //         if($model->status == 0) { return 'Inactive'; }
      //       }
      // ],
      [
     'attribute' => 'created_at',
     'format' => ['date' , 'php:d/m/Y'],
     'label' => Yii::t('app','Created On'),
     'headerOptions' => ['style' => 'width:12%;'],
      ],
      [
         'attribute' => 'updated_at',
         'format' => ['date' , 'php:d/m/Y'],
         'label' => Yii::t('app','Modified On'),
         'headerOptions' => ['style' => 'width:12%;'],
      ],
      // 'updated_by',
      [
         'attribute' => 'updated_by',
         'label' => Yii::t('app','Modified By'),
         'headerOptions' => ['style' => 'width:12%;'],
        'value' => 'user.username',
        //  'value' => function($model){
        //       return $model->user->username;
        // }
      ],

      // ['class' => 'yii\grid\ActionColumn'],
  ];
      echo ExportMenu::widget([
               'dataProvider' => $dataProvider,
               'columns' => $gridColumns,
               'target' => ExportMenu::TARGET_BLANK,
               'showConfirmAlert' => false,
               'filename' => 'Users',
               'dropdownOptions' => [
                'label' => 'Export',
                'class' => 'btn btn-info',
                'export' => true,
                'toolbar'=>[
                '{export}',
                '{toggleData}'
                ]
              ],
               'exportConfig'=>[
               ExportMenu::FORMAT_HTML=>false,
               ExportMenu::FORMAT_TEXT=>false,
               ExportMenu::FORMAT_PDF=>false,
               ExportMenu::FORMAT_EXCEL=>false,
               ],
          ]);?>

Can anyone please help me to export data which is checked only .
If you need any other information related code please ask.
Thanks.

Body:
Add a column to your columns onfiguration with this param:

[
    'class' => 'kartik\grid\CheckboxColumn',
    'headerOptions' => ['class' => 'kartik-sheet-style'],
],

And after you need to write your own code that will filter the data provider to return only selected rows in export menu. So your grid view data provider and export menu data provider will become different and you need to control the export menu data provider via the selected rows of grid view.

For get selected rows of GriView in JS you can to this:

var keys = $('#grid').yiiGridView('getSelectedRows');
// keys is an array consisting of the keys associated with the selected rows

For more info visit: Data widgets Yii2


问:
What are some good sql databases for home Vista computer?
I have been trying for a long time to get SQL Server Express on my computer to practice my C#/SQL with and I still haven't gotten it to work.

Are there other programs I can use to setup an SQL database to practice with?  If so, which are the best ones for Vista?

EDIT:
To be clear I am not new to SQL programming, I just haven't done any in a while and want to stay fresh.  So I would like something that has most of the features of forms of SQL I would use professionally.

答: MySQL or Postgresql are both full fledged DB's and good for education/experimentation. You can also check out Oracles free version.</p>

OwnerDisplayName: GordonG

LastEditorDisplayName: GordonG

OwnerDisplayName: Fredrik Jansson


问:
C# static vs instance methods
I'm risking it this might be a newb question but here goes. I'm tempted to add a method to a class that could possible have thousands and thousands of instances in memory at a given time. Now, the other option is creating a static class with a static method, and just create the [static] method there, instead of an instance method in the class. Something like so:

This:

```<code>public static class PetOwner
{
    public static void RenamePet(Pet pet, string newName)
    {
        pet.Name = newName;
    }
}
</code>```

Instead of this:

```<code>public class Pet
{
    public string Name { get; set; }

    public void Rename(string newName)
    {
        this.Name = newName;
    }
}
</code>```

I'm just wondering if the static class alternative would take considerably less memory.

Thanks!

答: It doesn't make a difference, methods (static or instance) are only loaded once into memory and JIted, they don't consume more memory just because they are instance methods.</p>

Title: C# static vs instance methods

Body:
I'm risking it this might be a newb question but here goes. I'm tempted to add a method to a class that could possible have thousands and thousands of instances in memory at a given time. Now, the other option is creating a static class with a static method, and just create the [static] method there, instead of an instance method in the class. Something like so:

This:

public static class PetOwner
{
    public static void RenamePet(Pet pet, string newName)
    {
        pet.Name = newName;
    }
}

Instead of this:

public class Pet
{
    public string Name { get; set; }

    public void Rename(string newName)
    {
        this.Name = newName;
    }
}

I'm just wondering if the static class alternative would take considerably less memory.

Thanks!