问:
How to enable CORS in ASP.net Core WebAPI
What I am trying to do

I have a backend ASP.Net Core Web API hosted on an Azure Free Plan (Add default security headers in .Net Core).

I also have a Client Website which I want to make consume that API. The Client Application will not be hosted on Azure, but rather will be hosted on Github Pages or on another Web Hosting Service that I have access to. Because of this the domain names won't line up.

Looking into this, I need to enable CORS on the Web API side, however I have tried just about everything for several hours now and it is refusing to work.

How I have the Client Setup
Its just a simple client written in React.js. I'm calling the APIs through AJAX in Jquery. The React site works so I know its not that. The Jquery API call works as I confirmed in Attempt 1. Here is how I make the calls

```<code>    var apiUrl = "http://andrewgodfroyportfolioapi.azurewebsites.net/api/Authentication";
    //alert(username + "|" + password + "|" + apiUrl);
    $.ajax({
        url: apiUrl,
        type: "POST",
        data: {
            username: username,
            password: password
        },
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (response) {
            var authenticatedUser = JSON.parse(response);
            //alert("Data Loaded: " + authenticatedUser);
            if (onComplete != null) {
                onComplete(authenticatedUser);
            }
        },
        error: function (xhr, status, error) {
            //alert(xhr.responseText);
            if (onComplete != null) {
                onComplete(xhr.responseText);
            }
        }
    });
</code>```

What I have tried

Attempt 1 - The 'proper' way

https://learn.microsoft.com/en-us/aspnet/core/security/cors

I have followed this tutorial on the Microsoft Website to a T, trying all 3 options of enabling it Globally in the Startup.cs, Setting it up on every controller and Trying it on every Action.

Following this method, the Cross Domain works, but only on a single Action on a single controller (POST to the AccountController). For everything else, the Microsoft.AspNetCore.Cors middleware refuses to set the headers.

I installed Microsoft.AspNetCore.Cors through NUGET and the version is 1.1.2

Here is how I have it setup in Startup.cs

```<code>    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        // Add Cors
        services.AddCors(o => o.AddPolicy("MyPolicy", builder =>
        {
            builder.AllowAnyOrigin()
                   .AllowAnyMethod()
                   .AllowAnyHeader();
        }));

        // Add framework services.
        services.AddMvc();
        services.Configure<MvcOptions>(options =>
        {
            options.Filters.Add(new CorsAuthorizationFilterFactory("MyPolicy"));
        });

        ...
        ...
        ...
    }

    // This method gets called by the runtime. Use this method to configure
    //the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env,
    ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();

        // Enable Cors
        app.UseCors("MyPolicy");

        //app.UseMvcWithDefaultRoute();
        app.UseMvc();

        ...
        ...
        ...
    }
</code>```

As you can see, I am doing everything as told. I add Cors before MVC both times, and when that didn't work I attempted putting [EnableCors("MyPolicy")] on every controller as so

```<code>[Route("api/[controller]")]
[EnableCors("MyPolicy")]
public class AdminController : Controller
</code>```

Attempt 2 - Brute Forcing it

https://andrewlock.net/adding-default-security-headers-in-asp-net-core/

After several hours of trying on the previous attempt, I figured I would try to bruteforce it by trying to set the headers manually, forcing them to run on every response. I did this following this tutorial on how to manually add headers to every response.

These are the headers I added

```<code>.AddCustomHeader("Access-Control-Allow-Origin", "*")
.AddCustomHeader("Access-Control-Allow-Methods", "*")
.AddCustomHeader("Access-Control-Allow-Headers", "*")
.AddCustomHeader("Access-Control-Max-Age", "86400")
</code>```

These are other headers I tried which failed

```<code>.AddCustomHeader("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE")
.AddCustomHeader("Access-Control-Allow-Headers", "content-type, accept, X-PINGOTHER")
.AddCustomHeader("Access-Control-Allow-Headers", "X-PINGOTHER, Host, User-Agent, Accept, Accept: application/json, application/json, Accept-Language, Accept-Encoding, Access-Control-Request-Method, Access-Control-Request-Headers, Origin, Connection, Content-Type, Content-Type: application/json, Authorization, Connection, Origin, Referer")
</code>```

With this method, the Cross Site headers are being properly applied and they show up in my developer console and in Postman. The problem however is that while it passes the Access-Control-Allow-Origin check, the webbrowser throws a hissy fit on (I believe) Access-Control-Allow-Headers stating 415 (Unsupported Media Type)

So the brute force method doesn't work either

Finally

Has anyone gotten this to work and could lend a hand, or just be able to point me in the right direction?

EDIT

So to get the API calls to go through, I had to stop using JQuery and switch to a Pure Javascript XMLHttpRequest format.

Attempt 1

I managed to get the Microsoft.AspNetCore.Cors to work by following MindingData's answer, except within the Configure Method putting the app.UseCors before app.UseMvc.

In addition, when mixed with the Javascript API Solution options.AllowAnyOrigin() for wildcard support began to work as well.

Attempt 2

So I have managed to get Attempt 2 (brute forcing it) to work... with the only exception that the Wildcard for Access-Control-Allow-Origin doesn't work and as such I have to manually set the domains that have access to it.

Its obviously not ideal since I just want this WebAPI to be wide opened to everyone, but it atleast works for me on a separate site, which means it's a start

```<code>app.UseSecurityHeadersMiddleware(new SecurityHeadersBuilder()
    .AddDefaultSecurePolicy()
    .AddCustomHeader("Access-Control-Allow-Origin", "http://localhost:3000")
    .AddCustomHeader("Access-Control-Allow-Methods", "OPTIONS, GET, POST, PUT, PATCH, DELETE")
    .AddCustomHeader("Access-Control-Allow-Headers", "X-PINGOTHER, Content-Type, Authorization"));
</code>```

答: Just to add to answer here, if you are using app.UseHttpsRedirection(), and you are hitting not SSL port consider commenting out this.

Body:
What I am trying to do

I have a backend ASP.Net Core Web API hosted on an Azure Free Plan (Add default security headers in .Net Core).

I also have a Client Website which I want to make consume that API. The Client Application will not be hosted on Azure, but rather will be hosted on Github Pages or on another Web Hosting Service that I have access to. Because of this the domain names won't line up.

Looking into this, I need to enable CORS on the Web API side, however I have tried just about everything for several hours now and it is refusing to work.

How I have the Client Setup
Its just a simple client written in React.js. I'm calling the APIs through AJAX in Jquery. The React site works so I know its not that. The Jquery API call works as I confirmed in Attempt 1. Here is how I make the calls

    var apiUrl = "http://andrewgodfroyportfolioapi.azurewebsites.net/api/Authentication";
    //alert(username + "|" + password + "|" + apiUrl);
    $.ajax({
        url: apiUrl,
        type: "POST",
        data: {
            username: username,
            password: password
        },
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (response) {
            var authenticatedUser = JSON.parse(response);
            //alert("Data Loaded: " + authenticatedUser);
            if (onComplete != null) {
                onComplete(authenticatedUser);
            }
        },
        error: function (xhr, status, error) {
            //alert(xhr.responseText);
            if (onComplete != null) {
                onComplete(xhr.responseText);
            }
        }
    });

What I have tried

Attempt 1 - The 'proper' way

https://learn.microsoft.com/en-us/aspnet/core/security/cors

I have followed this tutorial on the Microsoft Website to a T, trying all 3 options of enabling it Globally in the Startup.cs, Setting it up on every controller and Trying it on every Action.

Following this method, the Cross Domain works, but only on a single Action on a single controller (POST to the AccountController). For everything else, the Microsoft.AspNetCore.Cors middleware refuses to set the headers.

I installed Microsoft.AspNetCore.Cors through NUGET and the version is 1.1.2

Here is how I have it setup in Startup.cs

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        // Add Cors
        services.AddCors(o => o.AddPolicy("MyPolicy", builder =>
        {
            builder.AllowAnyOrigin()
                   .AllowAnyMethod()
                   .AllowAnyHeader();
        }));

        // Add framework services.
        services.AddMvc();
        services.Configure<MvcOptions>(options =>
        {
            options.Filters.Add(new CorsAuthorizationFilterFactory("MyPolicy"));
        });

        ...
        ...
        ...
    }

    // This method gets called by the runtime. Use this method to configure
    //the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env,
    ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();

        // Enable Cors
        app.UseCors("MyPolicy");

        //app.UseMvcWithDefaultRoute();
        app.UseMvc();

        ...
        ...
        ...
    }

As you can see, I am doing everything as told. I add Cors before MVC both times, and when that didn't work I attempted putting [EnableCors("MyPolicy")] on every controller as so

[Route("api/[controller]")]
[EnableCors("MyPolicy")]
public class AdminController : Controller

Attempt 2 - Brute Forcing it

https://andrewlock.net/adding-default-security-headers-in-asp-net-core/

After several hours of trying on the previous attempt, I figured I would try to bruteforce it by trying to set the headers manually, forcing them to run on every response. I did this following this tutorial on how to manually add headers to every response.

These are the headers I added

.AddCustomHeader("Access-Control-Allow-Origin", "*")
.AddCustomHeader("Access-Control-Allow-Methods", "*")
.AddCustomHeader("Access-Control-Allow-Headers", "*")
.AddCustomHeader("Access-Control-Max-Age", "86400")

These are other headers I tried which failed

.AddCustomHeader("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE")
.AddCustomHeader("Access-Control-Allow-Headers", "content-type, accept, X-PINGOTHER")
.AddCustomHeader("Access-Control-Allow-Headers", "X-PINGOTHER, Host, User-Agent, Accept, Accept: application/json, application/json, Accept-Language, Accept-Encoding, Access-Control-Request-Method, Access-Control-Request-Headers, Origin, Connection, Content-Type, Content-Type: application/json, Authorization, Connection, Origin, Referer")

With this method, the Cross Site headers are being properly applied and they show up in my developer console and in Postman. The problem however is that while it passes the Access-Control-Allow-Origin check, the webbrowser throws a hissy fit on (I believe) Access-Control-Allow-Headers stating 415 (Unsupported Media Type)

So the brute force method doesn't work either

Finally

Has anyone gotten this to work and could lend a hand, or just be able to point me in the right direction?

EDIT

So to get the API calls to go through, I had to stop using JQuery and switch to a Pure Javascript XMLHttpRequest format.

Attempt 1

I managed to get the Microsoft.AspNetCore.Cors to work by following MindingData's answer, except within the Configure Method putting the app.UseCors before app.UseMvc.

In addition, when mixed with the Javascript API Solution options.AllowAnyOrigin() for wildcard support began to work as well.

Attempt 2

So I have managed to get Attempt 2 (brute forcing it) to work... with the only exception that the Wildcard for Access-Control-Allow-Origin doesn't work and as such I have to manually set the domains that have access to it.

Its obviously not ideal since I just want this WebAPI to be wide opened to everyone, but it atleast works for me on a separate site, which means it's a start

app.UseSecurityHeadersMiddleware(new SecurityHeadersBuilder()
    .AddDefaultSecurePolicy()
    .AddCustomHeader("Access-Control-Allow-Origin", "http://localhost:3000")
    .AddCustomHeader("Access-Control-Allow-Methods", "OPTIONS, GET, POST, PUT, PATCH, DELETE")
    .AddCustomHeader("Access-Control-Allow-Headers", "X-PINGOTHER, Content-Type, Authorization"));


来源: stackexchange

问:
What service principle does Azure DevOps pipeline jobs run under?
I have a Azure DevOps pipeline that has a integration test task.  When the task runs the test needs access to a particular Azure KeyVault.  I need to give the principle under which the job is running in DevOps access to the KeyVault.  However, I'm a little confused which principle the job is running under.

I tried the following, however it did not make any difference:

In the Azure DevOps website I went to: Project Settings -> Service Connections -> Manage service principle.  This then loads a page in the Azure portal for the principle. I've taken that principle and granted them read access in the KeyVaut service, however the test is still failing with the same error.

Is there another principle that is actually running the job (i.e. I'm looking in the wrong place) or is there something else I haven't thought of?

For reference this is the error I get back (I replaced the GUID for security reasons):

```<code>Microsoft.Azure.Services.AppAuthentication.AzureServiceTokenProviderException : Parameters: Connection String: [No connection string specified], Resource: https://vault.azure.net, Authority: https://login.windows.net/<SOME_GUID>. Exception Message: Tried the following 3 methods to get an access token, but none of them worked.
Parameters: Connection String: [No connection string specified], Resource: https://vault.azure.net, Authority: https://login.windows.net/<SOME_GUID>. Exception Message: Tried to get token using Managed Service Identity. Access token could not be acquired. Received a non-retryable error. MSI ResponseCode: BadRequest, Response: {"error":"invalid_request","error_description":"Identity not found"}
Parameters: Connection String: [No connection string specified], Resource: https://vault.azure.net, Authority: https://login.windows.net/<SOME_GUID>. Exception Message: Tried to get token using Visual Studio. Access token could not be acquired. Environment variable LOCALAPPDATA not set.
Parameters: Connection String: [No connection string specified], Resource: https://vault.azure.net, Authority: https://login.windows.net/<SOME_GUID>. Exception Message: Tried to get token using Azure CLI. Access token could not be acquired. Please run 'az login' to setup account.
</code>```

答:
The test code cannot access to the service connection you created, if the service connection is not associated to your pipeline within the tasks.

1,As workaround you can try executing your test using commands in Azure Cli task. See below: Set the azureSubscription to the service connection you created. Azure Cli task will connect to your azure subscription using the authentication in the service connection. And the test will run in the current context of azure cli.  See Authenticating with Azure CLI for more information.

```<code>- task: AzureCLI@2
  displayName: Azure CLI
  inputs:
    azureSubscription: <Name of the Azure service connection>
    scriptLocation: inlineScript
    scriptType: pscore
    inlineScript: |
      dotnet test

</code>```

2,You can also Use a shared secret credential to sign into Azure AD. Refer to below steps:

Provide a connectionString to AzureServiceTokenProvider constructor as below:

var azureServiceTokenProvider = new AzureServiceTokenProvider("connectionString=#{keyVaultEndpoint}#;RunAs=App;AppId=#{appId}#;TenantId=#{tenantId}#;AppKey=#{clientSecret}#")

Define keyVaultEndpoint,appId,tenantId,clientSecret variables in your pipeline.

Add replace token task to replace below {AppId}, {TenantId}, and {ClientSecret} in the connectionString with the variables' value in the pipeline.

3,You can also try creating a self-hosted agent on your local machine. And run your pipeline against this oself-hosted agent. Since the tests run fine locally, it should be fine too on the self-hosted agent on your local machine.

Hope above helps!

ContentLicense: CC BY-SA 4.0

Body:
I have a Azure DevOps pipeline that has a integration test task.  When the task runs the test needs access to a particular Azure KeyVault.  I need to give the principle under which the job is running in DevOps access to the KeyVault.  However, I'm a little confused which principle the job is running under.

I tried the following, however it did not make any difference:

In the Azure DevOps website I went to: Project Settings -> Service Connections -> Manage service principle.  This then loads a page in the Azure portal for the principle. I've taken that principle and granted them read access in the KeyVaut service, however the test is still failing with the same error.

Is there another principle that is actually running the job (i.e. I'm looking in the wrong place) or is there something else I haven't thought of?

For reference this is the error I get back (I replaced the GUID for security reasons):

Microsoft.Azure.Services.AppAuthentication.AzureServiceTokenProviderException : Parameters: Connection String: [No connection string specified], Resource: https://vault.azure.net, Authority: https://login.windows.net/<SOME_GUID>. Exception Message: Tried the following 3 methods to get an access token, but none of them worked.
Parameters: Connection String: [No connection string specified], Resource: https://vault.azure.net, Authority: https://login.windows.net/<SOME_GUID>. Exception Message: Tried to get token using Managed Service Identity. Access token could not be acquired. Received a non-retryable error. MSI ResponseCode: BadRequest, Response: {"error":"invalid_request","error_description":"Identity not found"}
Parameters: Connection String: [No connection string specified], Resource: https://vault.azure.net, Authority: https://login.windows.net/<SOME_GUID>. Exception Message: Tried to get token using Visual Studio. Access token could not be acquired. Environment variable LOCALAPPDATA not set.
Parameters: Connection String: [No connection string specified], Resource: https://vault.azure.net, Authority: https://login.windows.net/<SOME_GUID>. Exception Message: Tried to get token using Azure CLI. Access token could not be acquired. Please run 'az login' to setup account.

Body:
The test code cannot access to the service connection you created, if the service connection is not associated to your pipeline within the tasks.

1,As workaround you can try executing your test using commands in Azure Cli task. See below: Set the azureSubscription to the service connection you created. Azure Cli task will connect to your azure subscription using the authentication in the service connection. And the test will run in the current context of azure cli.  See Authenticating with Azure CLI for more information.

- task: AzureCLI@2
  displayName: Azure CLI
  inputs:
    azureSubscription: <Name of the Azure service connection>
    scriptLocation: inlineScript
    scriptType: pscore
    inlineScript: |
      dotnet test

2,You can also Use a shared secret credential to sign into Azure AD. Refer to below steps:

Provide a connectionString to AzureServiceTokenProvider constructor as below:

var azureServiceTokenProvider = new AzureServiceTokenProvider("connectionString=#{keyVaultEndpoint}#;RunAs=App;AppId=#{appId}#;TenantId=#{tenantId}#;AppKey=#{clientSecret}#")

Define keyVaultEndpoint,appId,tenantId,clientSecret variables in your pipeline.

Add replace token task to replace below {AppId}, {TenantId}, and {ClientSecret} in the connectionString with the variables' value in the pipeline.

3,You can also try creating a self-hosted agent on your local machine. And run your pipeline against this oself-hosted agent. Since the tests run fine locally, it should be fine too on the self-hosted agent on your local machine.

Hope above helps!


问:
How to send via my iphone application a planned emails and without launching the email application?
I know how to send email from my application by launching the iPhone Mail application, then return to my app. But I have two concerns:

1 / My first concern is how my application can send emails without opening the mail application?

So I will inform the user that the email has been sent successfully or failure on failure of transmission.

2 / My second concern is to make sending mail programmed (in scheduled task) as in the case of UILocalNotification.

I have not found a solution, I try to avoid knowing the solution that uses open source classes for sending mail via SMTP, because I want my application uses the configuration of the iphone and mail ask the user to configure where the mail is not configured.

Thank you in advance for your help.

答:
You can use MailCore or similar alternatives.

You cannot do that with your app in the background. It's not the same as UILocalNotification as it requires user's approval before the app can do anything about that notification.

ContentLicense: CC BY-SA 3.0


问:
AccessDeniedException: User: arn:aws:iam::xxxxxxx:root is not authorized to perform: lambda:UpdateFunctionCode
Sorry for this lengthy post! I have tried my best to keep it as short as possible but wanted to put all information I have to explain the situation clearly.

My issue is related to AWS Lambda function deployment using JOVO CLI.

Every time I am trying to deploy the skill function from my local to Lambda, I am getting the following error block. I don't know how to resolve it.

$ jovo deploy -t lambda --ask-profile officialProfile

```<code>AccessDeniedException: User: arn:aws:iam::xxxxxxxxx:root is not authorized to perform: lambda:UpdateFunctionCode on resource: arn:aws:lambda:us-east-1:109918021270:function:sampleProjectNotes
</code>```

But I can get both $ jovo get alexaSkill --skill-id <Skill ID> --ask-profile officialProfile and $jovo deploy --ask-profile officialProfile (without any additional parameter) command to run without any issue.

For deploying the code from local, I created an ASK profile by logging in as IAM user. Here are the steps I followed:

ask init -p officialProfile

Logged in with IAM user credential (Email and password) created by my employer

Got the success message saying that the profile has been created

After doing some research, I created a policy under aws console and added the following JSON to it.

```<code>{
    "Version": "2012-10-17",
    "Statement": {
        "Effect": "Allow",
        "Action": [
            "iam:CreateRole",
            "iam:GetRole",
            "iam:AttachRolePolicy",
            "iam:PassRole",
            "lambda:AddPermission",
            "lambda:CreateFunction",
            "lambda:GetFunction",
            "lambda:UpdateFunctionCode",
            "lambda:UpdateFunctionConfiguration",
            "lambda:ListFunctions",
            "logs:FilterLogEvents",
            "logs:getLogEvents",
            "logs:describeLogStreams"
        ],
        "Resource": "*"
    }
}
</code>```

Then added the following Permissions to my IAM user:

AWSLambdaFullAccess

AWSCodeDeployRoleForLamda

and the above Policy I created earlier

But nothing is working. I am still getting the same error while deploying the code to Lambda.

My senior said that maybe the problem is that I am trying to access AWS as the root user and I need to use my user's ARN. I am unable to understand how to use or configure it.

I received an email invite which I am using to log in to Alexa console for building the skill.
And when I created the ASK profile, I logged in using the same email address and password. Is this a root account?

Meanwhile, I have found this article. AWS Access Key ID and AWS Secret Access Key are with me as well. But would like to be sure about what I am doing because there is already an ASK profile I created and if that would cause any further issue.

I was building skills from my personal AWS root account till now. This is the first time I am using an IAM user account.

UPDATE:

According to @Paradigm's instruction, when I tried ask deploy, the following error appeared:

```<code>Get Lambda ARN arn:aws:lambda:us-east-1:xxxxxxxx:function:sampleProjectNotes failure for custom/NA.
AccessDeniedException: User: arn:aws:iam::xxxxxxxx:root is not authorized to perform: lambda:GetFunction on resource: arn:aws:lambda:us-east-1:xxxxxxxx:function:sampleProjectNotes
</code>```

答:
It looks like your ASK CLI is using the AWS credentials for your personal account and not your company account.

You would need to run the "ask configure" command to set up the AWS credentials correctly for your officialProfile.

```<code>$ ask configure --profile officialProfile --aws-setup
</code>```

Body:
Sorry for this lengthy post! I have tried my best to keep it as short as possible but wanted to put all information I have to explain the situation clearly.

My issue is related to AWS Lambda function deployment using JOVO CLI.

Every time I am trying to deploy the skill function from my local to Lambda, I am getting the following error block. I don't know how to resolve it.

$ jovo deploy -t lambda --ask-profile officialProfile

AccessDeniedException: User: arn:aws:iam::xxxxxxxxx:root is not authorized to perform: lambda:UpdateFunctionCode on resource: arn:aws:lambda:us-east-1:109918021270:function:sampleProjectNotes

But I can get both $ jovo get alexaSkill --skill-id <Skill ID> --ask-profile officialProfile and $jovo deploy --ask-profile officialProfile (without any additional parameter) command to run without any issue.

For deploying the code from local, I created an ASK profile by logging in as IAM user. Here are the steps I followed:

ask init -p officialProfile

Logged in with IAM user credential (Email and password) created by my employer

Got the success message saying that the profile has been created

After doing some research, I created a policy under aws console and added the following JSON to it.

{
    "Version": "2012-10-17",
    "Statement": {
        "Effect": "Allow",
        "Action": [
            "iam:CreateRole",
            "iam:GetRole",
            "iam:AttachRolePolicy",
            "iam:PassRole",
            "lambda:AddPermission",
            "lambda:CreateFunction",
            "lambda:GetFunction",
            "lambda:UpdateFunctionCode",
            "lambda:UpdateFunctionConfiguration",
            "lambda:ListFunctions",
            "logs:FilterLogEvents",
            "logs:getLogEvents",
            "logs:describeLogStreams"
        ],
        "Resource": "*"
    }
}

Then added the following Permissions to my IAM user:

AWSLambdaFullAccess

AWSCodeDeployRoleForLamda

and the above Policy I created earlier

But nothing is working. I am still getting the same error while deploying the code to Lambda.

My senior said that maybe the problem is that I am trying to access AWS as the root user and I need to use my user's ARN. I am unable to understand how to use or configure it.

I received an email invite which I am using to log in to Alexa console for building the skill.
And when I created the ASK profile, I logged in using the same email address and password. Is this a root account?

Meanwhile, I have found this article. AWS Access Key ID and AWS Secret Access Key are with me as well. But would like to be sure about what I am doing because there is already an ASK profile I created and if that would cause any further issue.

I was building skills from my personal AWS root account till now. This is the first time I am using an IAM user account.

UPDATE:

According to @Paradigm's instruction, when I tried ask deploy, the following error appeared:

Get Lambda ARN arn:aws:lambda:us-east-1:xxxxxxxx:function:sampleProjectNotes failure for custom/NA.
AccessDeniedException: User: arn:aws:iam::xxxxxxxx:root is not authorized to perform: lambda:GetFunction on resource: arn:aws:lambda:us-east-1:xxxxxxxx:function:sampleProjectNotes

Body:
It looks like your ASK CLI is using the AWS credentials for your personal account and not your company account.

You would need to run the "ask configure" command to set up the AWS credentials correctly for your officialProfile.

$ ask configure --profile officialProfile --aws-setup


问:
Class Not Found in PHP Laravel 6.x when another class extends
I always get the class not found exception in php laravel 6 when i create a class and extend a parent class named A which is located in the same directory.

However, another child class that is located in same directory could extend class A successfully.

In addition, i couldn't also instantiate the class A due to class not found exception in another .php file.

Please help me on this.
Thanks in an advance.

Parent class: myContext

```<code><?php
namespace config\models;

class myContext {
    public static $conn;
    ...
}
</code>```

Class myUser: extension is fine.

```<code><?php
namespace config\models;

class myUser extends myContext {
   private $name;
   ...
}
</code>```

Class oauth: extension returns myContext class not found.

```<code><?php
namespace config\models;

class oauth extends myContext {
    private $user;
}
</code>```

Instantiate the class - returns class not found.

```<code><?php

use config\models\myContext as context;

$cont = new context();
</code>```

答: You try to add this line of code in the composer.json file, then execute the composer dumpautoload command on the command line

Body:
I always get the class not found exception in php laravel 6 when i create a class and extend a parent class named A which is located in the same directory.

However, another child class that is located in same directory could extend class A successfully.

In addition, i couldn't also instantiate the class A due to class not found exception in another .php file.

Please help me on this.
Thanks in an advance.

Parent class: myContext

<?php
namespace config\models;

class myContext {
    public static $conn;
    ...
}

Class myUser: extension is fine.

<?php
namespace config\models;

class myUser extends myContext {
   private $name;
   ...
}

Class oauth: extension returns myContext class not found.

<?php
namespace config\models;

class oauth extends myContext {
    private $user;
}

Instantiate the class - returns class not found.

<?php

use config\models\myContext as context;

$cont = new context();


问:
Handle either a list or single integer as an argument
A function should select rows in a table based on the row name (column 2 in this case). It should be able to take either a single name or a list of names as arguments and handle them correctly.

This is what I have now, but ideally there wouldn't be this duplicated code and something like exceptions would be used intelligently to choose the right way to handle the input argument:

```<code>def select_rows(to_select):
    # For a list
    for row in range(0, table.numRows()):
        if _table.item(row, 1).text() in to_select:
            table.selectRow(row)
    # For a single integer
    for row in range(0, table.numRows()):
        if _table.item(row, 1).text() == to_select:
            table.selectRow(row)
</code>```

答:
A bit less general but concise, using numpy:

```<code>numpy.unique()
</code>```

handles that automatically by keeping only the unique values of an array-like or scalar, and returns a list of the unique values, or of the scalar.

```<code>import numpy as np

def select_rows(to_select):
   to_select = np.unique(to_select)

   for row in range(0, table.numRows()):
       if _table.item(row, 1).text() in to_select:
           table.selectRow(row)
</code>```

ContentLicense: CC BY-SA 2.5

Body:
A function should select rows in a table based on the row name (column 2 in this case). It should be able to take either a single name or a list of names as arguments and handle them correctly.

This is what I have now, but ideally there wouldn't be this duplicated code and something like exceptions would be used intelligently to choose the right way to handle the input argument:

def select_rows(to_select):
    # For a list
    for row in range(0, table.numRows()):
        if _table.item(row, 1).text() in to_select:
            table.selectRow(row)
    # For a single integer
    for row in range(0, table.numRows()):
        if _table.item(row, 1).text() == to_select:
            table.selectRow(row)

Body:
A bit less general but concise, using numpy:

numpy.unique()

handles that automatically by keeping only the unique values of an array-like or scalar, and returns a list of the unique values, or of the scalar.

import numpy as np

def select_rows(to_select):
   to_select = np.unique(to_select)

   for row in range(0, table.numRows()):
       if _table.item(row, 1).text() in to_select:
           table.selectRow(row)


问:
wcf wsdualhttpbinding timeout problem
Please help me!!!

I am trying to build an application which uses callbacks contracts.My app work fine both the client and the server on the same machine, but when i try to access the service from other machine i got an exception timeout(the operation din not complete within the allotted timeout).The client reads some values throw the service from the database which is on the server.I don't know where is my mistake.I have tried to put the client in a virtual machine, and the service(and database) on the real machine.

Here is my Server config file:

```<code>            <binding name="TrainService" closeTimeout="00:02:00" openTimeout="00:02:00"
                receiveTimeout="00:10:00" sendTimeout="00:02:00" bypassProxyOnLocal="false"
                transactionFlow="false" hostNameComparisonMode="StrongWildcard"
                maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
                messageEncoding="Text" textEncoding="utf-8" useDefaultWebProxy="true">
                <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
                    maxBytesPerRead="4096" maxNameTableCharCount="16384" />
                <reliableSession ordered="true" inactivityTimeout="00:10:00" />
                <security mode="None">
                    <message clientCredentialType="None" negotiateServiceCredential="true"
                        algorithmSuite="Default" />
                </security>
            </binding>
        </wsDualHttpBinding>
        <wsHttpBinding>
            <binding name="WSHttpBinding_ITrainService" closeTimeout="00:02:00"
                openTimeout="00:02:00" receiveTimeout="00:10:00" sendTimeout="00:02:00"
                bypassProxyOnLocal="false" transactionFlow="false" hostNameComparisonMode="StrongWildcard"
                maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
                messageEncoding="Text" textEncoding="utf-8" useDefaultWebProxy="true"
                allowCookies="false">
                <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
                    maxBytesPerRead="4096" maxNameTableCharCount="16384" />
                <reliableSession ordered="true" inactivityTimeout="00:10:00"
                    enabled="false" />
                <security mode="None">
                    <transport clientCredentialType="None" proxyCredentialType="None"
                        realm="" />
                    <message clientCredentialType="None" negotiateServiceCredential="true"
                        algorithmSuite="Default" />
                </security>
            </binding>
        </wsHttpBinding>
    </bindings>
  <client>
    <endpoint address="http://localhost:8732/Design_Time_Addresses/WCFandEFService/TrainService/"
      binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_ITrainService"
      contract="TrainServiceRef.ITrainService" name="WSHttpBinding_ITrainService">
      <identity>
        <dns value="localhost" />
      </identity>
    </endpoint>
    <endpoint address="net.tcp://localhost:8080/TcpService" binding="netTcpBinding"
      contract="TrainServiceRef.ITrainService" name="NetTcpBinding_ITrainService" />
    <endpoint address="http://localhost:8082/InterlockingService/Host/line"
      binding="wsDualHttpBinding" bindingConfiguration="LineService"
      contract="InterlockingServiceReference.ILineService" name="LineService">
      <identity>
        <userPrincipalName value="Romina-PC\Romina" />
      </identity>
    </endpoint>

    <endpoint address="http://localhost:8082/InterlockingService/Host/trains"
      binding="wsDualHttpBinding" bindingConfiguration="TrainService"
      contract="InterlockingServiceReference.ITrainService" name="TrainService">
      <identity>
        <userPrincipalName value="Romina-PC\Romina" />
      </identity>
    </endpoint>

  </client>

</system.serviceModel>
</code>```

My client config file:

                        -->

```<code>            <binding name="TrainService" closeTimeout="00:01:00" openTimeout="00:01:00"
                receiveTimeout="00:10:00" sendTimeout="00:01:00" bypassProxyOnLocal="false"
                transactionFlow="false" hostNameComparisonMode="StrongWildcard"
                maxBufferPoolSize="52428800" maxReceivedMessageSize="6553600"
                messageEncoding="Text" textEncoding="utf-8" useDefaultWebProxy="true">
                <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="1638400"
                    maxBytesPerRead="4096" maxNameTableCharCount="1638400" />
                <reliableSession ordered="true" inactivityTimeout="00:10:00" />
                <security mode="None">
                    <!--<message clientCredentialType="None" negotiateServiceCredential="true"
                        algorithmSuite="Default" />-->
                </security>
            </binding>
        </wsDualHttpBinding>
    </bindings>
    <client>
        <endpoint address="http://localhost:8082/InterlockingService/Host/line"
            binding="wsDualHttpBinding" bindingConfiguration="LineService"
            contract="InterlockingServiceRef.ILineService" name="LineService">
            <identity>
                <userPrincipalName value="Romina-PC\Romina" />
            </identity>
        </endpoint>

        <endpoint address="http://localhost:8082/InterlockingService/Host/trains"
            binding="wsDualHttpBinding" bindingConfiguration="TrainService"
            contract="InterlockingServiceRef.ITrainService" name="TrainService">
            <identity>
                <userPrincipalName value="Romina-PC\Romina" />
            </identity>
        </endpoint>
    </client>
</system.serviceModel>
</code>```

Thank you.

Those are the contracts: public interface ITrainServiceCallBack
    {
        [OperationContract (IsOneWay=true)]
        void OnTrainChangeState(TrainData train);
    }

```<code>//[ServiceContract(Name = "LineService", CallbackContract = typeof(ILineServiceCallBack))]
[ServiceContract(CallbackContract = typeof(ITrainServiceCallBack))]
public interface ITrainService
{
    [OperationContract]
    TrainData GetTrainData(string trainName);

    [OperationContract]
    bool ChangeTrainState_bool(ref TrainData train);

    [OperationContract]
    void ChangeTrainState(ref Trains_Detail train);
    [OperationContract]
    bool SubscribeToTrainChangeEvent();

    [OperationContract]
    bool UnSubscribeFromTrainChangeEvent();
    [OperationContract]
    TrainData TranslateTrainEntityToTrainData(Trains_Detail trainEntity);

    [OperationContract]
    IEnumerable<Trains_Detail> GetTrains();

    [OperationContract]
    IEnumerable<Trains_Detail> GetTrains_ByStation(int Statie_plecare, int Statie_sosire);
}
</code>```

Method implementation:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.Data;

namespace WCFandEFService
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "ProductService" in both code and config file together.
    //[ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Multiple)]

```<code>public partial class InterlockingService : ITrainService
{

    static List<ITrainServiceCallBack> subscribers_train = new List<ITrainServiceCallBack>();

    public bool TrainExists(string nrTren, InterlockingEntities database)
    {
        // Check to see whether the specified product exists in the database
        int numTrain = (from t in database.Trains_Details
                       where string.Equals(t.Nr_tren, nrTren)
                       select t).Count();

        return numTrain > 0;

    }

    public TrainData TranslateTrainEntityToTrainData(Trains_Detail trainEntity)
    {
        TrainData train = new TrainData();

        train.nrTren=trainEntity.Nr_tren;
        train.ora_Plecare= trainEntity.Ora_plecare;
        train.ora_Sosire=trainEntity.Ora_sosire;
        train.statie_Plecare=trainEntity.Statie_plecare;
        train.statie_Sosire=trainEntity.Statie_sosire;
        train.rang=trainEntity.Rang;
        train.observatii=trainEntity.Observatii;
        train.RowVersion=trainEntity.RowVersion;

        return train;

    }

    #region ILineService Members

    public IEnumerable<Trains_Detail> GetTrains()
    {
        InterlockingEntities context = new InterlockingEntities();

        IEnumerable<Trains_Detail> result =
                (from t in context.Trains_Details
                 //where l.Station == station
                 select t);
        return result;

    }

     public IEnumerable<Trains_Detail> GetTrains_ByStation(int Statie_plecare,int Statie_sosire)
    {
        InterlockingEntities context = new InterlockingEntities();

        IEnumerable<Trains_Detail> result =
                (from t in context.Trains_Details
                 where t.Statie_plecare==Statie_plecare && t.Statie_sosire==Statie_sosire
                 select t);
        return result;

    }

    public TrainData GetTrainData(string trainNr)
    {
        InterlockingEntities context = new InterlockingEntities();
        Trains_Detail trainInDB =
             (from t
              in context.Trains_Details
              where String.Compare(t.Nr_tren, trainNr) == 0
              select t).FirstOrDefault();
        if (trainInDB == null)
        {

            throw new Exception("No line cu numele " + trainInDB.Nr_tren);

        }

        context.Detach(trainInDB);
        return TranslateTrainEntityToTrainData(trainInDB);
    }

    public bool ChangeTrainState_bool(ref TrainData train)
    {
        InterlockingEntities context = new InterlockingEntities();
        String trainName = train.nrTren;
        //int lineStation = line.station;
        Trains_Detail trainInDB =
             (from t
              in context.Trains_Details
              where String.Compare(t.Nr_tren, trainName) == 0
              select t).FirstOrDefault();

        if (trainInDB == null)
        {
            throw new Exception("No train cu numele " + trainInDB.Nr_tren);
        }

        context.Detach(trainInDB);

        trainInDB.Nr_tren = train.nrTren;
        trainInDB.Ora_plecare=train.ora_Plecare;
        trainInDB.Ora_sosire=train.ora_Sosire;
        trainInDB.Statie_plecare=train.statie_Plecare;
        trainInDB.Statie_sosire=train.statie_Sosire;
        trainInDB.Rang=train.rang;

        trainInDB.RowVersion = train.RowVersion;

        context.Attach(trainInDB);

        context.ObjectStateManager.ChangeObjectState(trainInDB, System.Data.EntityState.Modified);
        context.SaveChanges();
        train.RowVersion = trainInDB.RowVersion;
        context.Dispose();
        raiseTrainChangeState(TranslateTrainEntityToTrainData(trainInDB));
        return true;
    }

    public void ChangeTrainState(ref Trains_Detail train)
    {
        using (var context = new InterlockingEntities())
        {
            context.Attach(train);
            context.ObjectStateManager.ChangeObjectState(train, EntityState.Modified);
            context.SaveChanges();
        }
    }
   }

    public bool SubscribeToTrainChangeEvent()
    {
        try
        {
            ITrainServiceCallBack callback = OperationContext.Current.GetCallbackChannel<ITrainServiceCallBack>();

            if (!subscribers_train.Contains(callback))
            {
                subscribers_train.Add(callback);
            }
            return true;
        }
        catch (Exception)
        {

            return false;
        }

    }

    public bool UnSubscribeFromTrainChangeEvent()
    {
        try
        {
            ITrainServiceCallBack callback = OperationContext.Current.GetCallbackChannel<ITrainServiceCallBack>();
            subscribers_train.Remove(callback);

            return true;
        }
        catch (Exception)
        {
            return false;
        }
    }

    #endregion

    private void raiseTrainChangeState(TrainData train)
    {
        subscribers_train.AsParallel().ForAll(callback =>
        {
            if (((ICommunicationObject)callback).State == CommunicationState.Opened)
            {
                callback.OnTrainChangeState(train);

            }
            else
            {
                subscribers_train.Remove(callback);
            }
        });
    }

}
</code>```

}

答:
Check if you have marked your operation contract as one way. Its usual to get a timeout in dual http binding where people fail to mark the contract as one way.

```<code>[OperationContract(IsOneWay = true)]
</code>```

EDIT

Please place the following line in the service contract's behavior.

```<code>[ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Multiple)]
</code>```

For our reference, consider posting your service contract structure and the operation contract's implementation.

Title: wcf wsdualhttpbinding timeout problem

Body:
Please help me!!!

I am trying to build an application which uses callbacks contracts.My app work fine both the client and the server on the same machine, but when i try to access the service from other machine i got an exception timeout(the operation din not complete within the allotted timeout).The client reads some values throw the service from the database which is on the server.I don't know where is my mistake.I have tried to put the client in a virtual machine, and the service(and database) on the real machine.

Here is my Server config file:

            <binding name="TrainService" closeTimeout="00:02:00" openTimeout="00:02:00"
                receiveTimeout="00:10:00" sendTimeout="00:02:00" bypassProxyOnLocal="false"
                transactionFlow="false" hostNameComparisonMode="StrongWildcard"
                maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
                messageEncoding="Text" textEncoding="utf-8" useDefaultWebProxy="true">
                <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
                    maxBytesPerRead="4096" maxNameTableCharCount="16384" />
                <reliableSession ordered="true" inactivityTimeout="00:10:00" />
                <security mode="None">
                    <message clientCredentialType="None" negotiateServiceCredential="true"
                        algorithmSuite="Default" />
                </security>
            </binding>
        </wsDualHttpBinding>
        <wsHttpBinding>
            <binding name="WSHttpBinding_ITrainService" closeTimeout="00:02:00"
                openTimeout="00:02:00" receiveTimeout="00:10:00" sendTimeout="00:02:00"
                bypassProxyOnLocal="false" transactionFlow="false" hostNameComparisonMode="StrongWildcard"
                maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
                messageEncoding="Text" textEncoding="utf-8" useDefaultWebProxy="true"
                allowCookies="false">
                <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
                    maxBytesPerRead="4096" maxNameTableCharCount="16384" />
                <reliableSession ordered="true" inactivityTimeout="00:10:00"
                    enabled="false" />
                <security mode="None">
                    <transport clientCredentialType="None" proxyCredentialType="None"
                        realm="" />
                    <message clientCredentialType="None" negotiateServiceCredential="true"
                        algorithmSuite="Default" />
                </security>
            </binding>
        </wsHttpBinding>
    </bindings>
  <client>
    <endpoint address="http://localhost:8732/Design_Time_Addresses/WCFandEFService/TrainService/"
      binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_ITrainService"
      contract="TrainServiceRef.ITrainService" name="WSHttpBinding_ITrainService">
      <identity>
        <dns value="localhost" />
      </identity>
    </endpoint>
    <endpoint address="net.tcp://localhost:8080/TcpService" binding="netTcpBinding"
      contract="TrainServiceRef.ITrainService" name="NetTcpBinding_ITrainService" />
    <endpoint address="http://localhost:8082/InterlockingService/Host/line"
      binding="wsDualHttpBinding" bindingConfiguration="LineService"
      contract="InterlockingServiceReference.ILineService" name="LineService">
      <identity>
        <userPrincipalName value="Romina-PC\Romina" />
      </identity>
    </endpoint>

    <endpoint address="http://localhost:8082/InterlockingService/Host/trains"
      binding="wsDualHttpBinding" bindingConfiguration="TrainService"
      contract="InterlockingServiceReference.ITrainService" name="TrainService">
      <identity>
        <userPrincipalName value="Romina-PC\Romina" />
      </identity>
    </endpoint>

  </client>

</system.serviceModel>

My client config file:

                        -->

            <binding name="TrainService" closeTimeout="00:01:00" openTimeout="00:01:00"
                receiveTimeout="00:10:00" sendTimeout="00:01:00" bypassProxyOnLocal="false"
                transactionFlow="false" hostNameComparisonMode="StrongWildcard"
                maxBufferPoolSize="52428800" maxReceivedMessageSize="6553600"
                messageEncoding="Text" textEncoding="utf-8" useDefaultWebProxy="true">
                <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="1638400"
                    maxBytesPerRead="4096" maxNameTableCharCount="1638400" />
                <reliableSession ordered="true" inactivityTimeout="00:10:00" />
                <security mode="None">

                </security>
            </binding>
        </wsDualHttpBinding>
    </bindings>
    <client>
        <endpoint address="http://localhost:8082/InterlockingService/Host/line"
            binding="wsDualHttpBinding" bindingConfiguration="LineService"
            contract="InterlockingServiceRef.ILineService" name="LineService">
            <identity>
                <userPrincipalName value="Romina-PC\Romina" />
            </identity>
        </endpoint>

        <endpoint address="http://localhost:8082/InterlockingService/Host/trains"
            binding="wsDualHttpBinding" bindingConfiguration="TrainService"
            contract="InterlockingServiceRef.ITrainService" name="TrainService">
            <identity>
                <userPrincipalName value="Romina-PC\Romina" />
            </identity>
        </endpoint>
    </client>
</system.serviceModel>

Thank you.

Those are the contracts: public interface ITrainServiceCallBack
    {
        [OperationContract (IsOneWay=true)]
        void OnTrainChangeState(TrainData train);
    }

//[ServiceContract(Name = "LineService", CallbackContract = typeof(ILineServiceCallBack))]
[ServiceContract(CallbackContract = typeof(ITrainServiceCallBack))]
public interface ITrainService
{
    [OperationContract]
    TrainData GetTrainData(string trainName);

    [OperationContract]
    bool ChangeTrainState_bool(ref TrainData train);

    [OperationContract]
    void ChangeTrainState(ref Trains_Detail train);
    [OperationContract]
    bool SubscribeToTrainChangeEvent();

    [OperationContract]
    bool UnSubscribeFromTrainChangeEvent();
    [OperationContract]
    TrainData TranslateTrainEntityToTrainData(Trains_Detail trainEntity);

    [OperationContract]
    IEnumerable<Trains_Detail> GetTrains();

    [OperationContract]
    IEnumerable<Trains_Detail> GetTrains_ByStation(int Statie_plecare, int Statie_sosire);
}

Method implementation:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.Data;

namespace WCFandEFService
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "ProductService" in both code and config file together.
    //[ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Multiple)]

public partial class InterlockingService : ITrainService
{

    static List<ITrainServiceCallBack> subscribers_train = new List<ITrainServiceCallBack>();

    public bool TrainExists(string nrTren, InterlockingEntities database)
    {
        // Check to see whether the specified product exists in the database
        int numTrain = (from t in database.Trains_Details
                       where string.Equals(t.Nr_tren, nrTren)
                       select t).Count();

        return numTrain > 0;

    }

    public TrainData TranslateTrainEntityToTrainData(Trains_Detail trainEntity)
    {
        TrainData train = new TrainData();

        train.nrTren=trainEntity.Nr_tren;
        train.ora_Plecare= trainEntity.Ora_plecare;
        train.ora_Sosire=trainEntity.Ora_sosire;
        train.statie_Plecare=trainEntity.Statie_plecare;
        train.statie_Sosire=trainEntity.Statie_sosire;
        train.rang=trainEntity.Rang;
        train.observatii=trainEntity.Observatii;
        train.RowVersion=trainEntity.RowVersion;

        return train;

    }

    #region ILineService Members

    public IEnumerable<Trains_Detail> GetTrains()
    {
        InterlockingEntities context = new InterlockingEntities();

        IEnumerable<Trains_Detail> result =
                (from t in context.Trains_Details
                 //where l.Station == station
                 select t);
        return result;

    }

     public IEnumerable<Trains_Detail> GetTrains_ByStation(int Statie_plecare,int Statie_sosire)
    {
        InterlockingEntities context = new InterlockingEntities();

        IEnumerable<Trains_Detail> result =
                (from t in context.Trains_Details
                 where t.Statie_plecare==Statie_plecare && t.Statie_sosire==Statie_sosire
                 select t);
        return result;

    }

    public TrainData GetTrainData(string trainNr)
    {
        InterlockingEntities context = new InterlockingEntities();
        Trains_Detail trainInDB =
             (from t
              in context.Trains_Details
              where String.Compare(t.Nr_tren, trainNr) == 0
              select t).FirstOrDefault();
        if (trainInDB == null)
        {

            throw new Exception("No line cu numele " + trainInDB.Nr_tren);

        }

        context.Detach(trainInDB);
        return TranslateTrainEntityToTrainData(trainInDB);
    }

    public bool ChangeTrainState_bool(ref TrainData train)
    {
        InterlockingEntities context = new InterlockingEntities();
        String trainName = train.nrTren;
        //int lineStation = line.station;
        Trains_Detail trainInDB =
             (from t
              in context.Trains_Details
              where String.Compare(t.Nr_tren, trainName) == 0
              select t).FirstOrDefault();

        if (trainInDB == null)
        {
            throw new Exception("No train cu numele " + trainInDB.Nr_tren);
        }

        context.Detach(trainInDB);

        trainInDB.Nr_tren = train.nrTren;
        trainInDB.Ora_plecare=train.ora_Plecare;
        trainInDB.Ora_sosire=train.ora_Sosire;
        trainInDB.Statie_plecare=train.statie_Plecare;
        trainInDB.Statie_sosire=train.statie_Sosire;
        trainInDB.Rang=train.rang;

        trainInDB.RowVersion = train.RowVersion;

        context.Attach(trainInDB);

        context.ObjectStateManager.ChangeObjectState(trainInDB, System.Data.EntityState.Modified);
        context.SaveChanges();
        train.RowVersion = trainInDB.RowVersion;
        context.Dispose();
        raiseTrainChangeState(TranslateTrainEntityToTrainData(trainInDB));
        return true;
    }

    public void ChangeTrainState(ref Trains_Detail train)
    {
        using (var context = new InterlockingEntities())
        {
            context.Attach(train);
            context.ObjectStateManager.ChangeObjectState(train, EntityState.Modified);
            context.SaveChanges();
        }
    }
   }

    public bool SubscribeToTrainChangeEvent()
    {
        try
        {
            ITrainServiceCallBack callback = OperationContext.Current.GetCallbackChannel<ITrainServiceCallBack>();

            if (!subscribers_train.Contains(callback))
            {
                subscribers_train.Add(callback);
            }
            return true;
        }
        catch (Exception)
        {

            return false;
        }

    }

    public bool UnSubscribeFromTrainChangeEvent()
    {
        try
        {
            ITrainServiceCallBack callback = OperationContext.Current.GetCallbackChannel<ITrainServiceCallBack>();
            subscribers_train.Remove(callback);

            return true;
        }
        catch (Exception)
        {
            return false;
        }
    }

    #endregion

    private void raiseTrainChangeState(TrainData train)
    {
        subscribers_train.AsParallel().ForAll(callback =>
        {
            if (((ICommunicationObject)callback).State == CommunicationState.Opened)
            {
                callback.OnTrainChangeState(train);

            }
            else
            {
                subscribers_train.Remove(callback);
            }
        });
    }

}

}

Body:
Check if you have marked your operation contract as one way. Its usual to get a timeout in dual http binding where people fail to mark the contract as one way.

[OperationContract(IsOneWay = true)]

EDIT

Please place the following line in the service contract's behavior.

[ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Multiple)]

For our reference, consider posting your service contract structure and the operation contract's implementation.


问:
Postgresql - adding hostname / port to commandline
I have migrated from 9.6 to 12 and no longer using socket connection.

So now to execute pgsql commands (Linux command-line) I have to add two parameters:

```<code>-h 127.0.0.1 -p 5432
</code>```

All works well then. Problem is I have dozen of scripts on few environments so now I have to correct all of those.

I wonder if there is any setting / system variable I can set to instruct PostgreSQL to connect to local host / port - so I don't need to correct all of my scripts ?

答:
Yes, you can use environment variables PGHOST and PGPORT.

See https://www.postgresql.org/docs/current/libpq-envars.html

Body:
I have migrated from 9.6 to 12 and no longer using socket connection.

So now to execute pgsql commands (Linux command-line) I have to add two parameters:

-h 127.0.0.1 -p 5432

All works well then. Problem is I have dozen of scripts on few environments so now I have to correct all of those.

I wonder if there is any setting / system variable I can set to instruct PostgreSQL to connect to local host / port - so I don't need to correct all of my scripts ?


问:
Unable to Push to Azure Registry with docker-maven-plugin
I've followed this tutorial:
https://www.baeldung.com/spring-boot-azure

However, although I set the credentials in settings.xml for maven, I still get this error:

```<code>[WARNING] Failed to push apiefrontdoor.azurecr.io/apiefrontdoor, retrying in 10 seconds (5/5).
[INFO] Pushing apiefrontdoor.azurecr.io/apiefrontdoor
The push refers to repository [apiefrontdoor.azurecr.io/apiefrontdoor]
c7f1d24c6c55: Preparing
a46d8ce138df: Preparing
42fd82c87bc8: Preparing
ceaf9e1ebef5: Preparing
9b9b7f3d56a0: Preparing
f1b5933fe4b5: Waiting
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  04:36 min
[INFO] Finished at: 2020-06-02T18:24:11-07:00
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal com.spotify:docker-maven-plugin:1.2.2:build (default-cli) on project apiefrontdoor: Exception caught: unauthorized: authentication required -> [Help 1]
org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal com.spotify:docker-maven-plugin:1.2.2:build (default-cli) on project apiefrontdoor: Exception caught
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:215)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:156)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:148)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:117)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:81)
    at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build (SingleThreadedBuilder.java:56)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute (LifecycleStarter.java:128)
    at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:305)
    at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:192)
    at org.apache.maven.DefaultMaven.execute (DefaultMaven.java:105)
    at org.apache.maven.cli.MavenCli.execute (MavenCli.java:957)
    at org.apache.maven.cli.MavenCli.doMain (MavenCli.java:289)
    at org.apache.maven.cli.MavenCli.main (MavenCli.java:193)
    at sun.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke (Method.java:498)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced (Launcher.java:282)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch (Launcher.java:225)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode (Launcher.java:406)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main (Launcher.java:347)
Caused by: org.apache.maven.plugin.MojoExecutionException: Exception caught
    at com.spotify.docker.AbstractDockerMojo.execute (AbstractDockerMojo.java:151)
    at com.spotify.docker.BuildMojo.execute (BuildMojo.java:329)
    at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo (DefaultBuildPluginManager.java:137)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:210)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:156)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:148)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:117)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:81)
    at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build (SingleThreadedBuilder.java:56)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute (LifecycleStarter.java:128)
    at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:305)
    at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:192)
    at org.apache.maven.DefaultMaven.execute (DefaultMaven.java:105)
    at org.apache.maven.cli.MavenCli.execute (MavenCli.java:957)
    at org.apache.maven.cli.MavenCli.doMain (MavenCli.java:289)
    at org.apache.maven.cli.MavenCli.main (MavenCli.java:193)
    at sun.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke (Method.java:498)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced (Launcher.java:282)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch (Launcher.java:225)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode (Launcher.java:406)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main (Launcher.java:347)
Caused by: com.spotify.docker.client.exceptions.DockerException: unauthorized: authentication required
    at com.spotify.docker.client.AnsiProgressHandler.progress (AnsiProgressHandler.java:55)
    at com.spotify.docker.Utils$DigestExtractingProgressHandler.progress (Utils.java:191)
    at com.spotify.docker.client.ProgressStream.tail (ProgressStream.java:77)
    at com.spotify.docker.client.DefaultDockerClient$ResponseTailReader.call (DefaultDockerClient.java:2754)
    at com.spotify.docker.client.DefaultDockerClient$ResponseTailReader.call (DefaultDockerClient.java:2738)
    at java.util.concurrent.FutureTask.run (FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker (ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run (ThreadPoolExecutor.java:624)
    at java.lang.Thread.run (Thread.java:748)
[ERROR]
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException
</code>```

Here is my pom.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.0.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.apieproject</groupId>
    <artifactId>apiefrontdoor</artifactId>
    <version>0.0.1</version>
    <name>frontdoor</name>
    <description>APIE Project Landing Project</description>

    <properties>
       <jib-maven-plugin.version>2.3.0</jib-maven-plugin.version>
       <azure.containerRegistry>apiefrontdoor</azure.containerRegistry>
       <docker.image.prefix>apiefrontdoor.azurecr.io</docker.image.prefix>
       <java.version>1.8</java.version>
    </properties>

    <dependencies>
        ....
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
              <artifactId>jib-maven-plugin</artifactId>
              <groupId>com.google.cloud.tools</groupId>
              <version>${jib-maven-plugin.version}</version>
              <configuration>
                 <from>
                     <image>mcr.microsoft.com/java/jre:8-zulu-alpine</image>
                 </from>
                 <to>
                     <image>${docker.image.prefix}/${project.artifactId}</image>
                 </to>
              </configuration>
            </plugin>
            <plugin>
               <groupId>com.microsoft.azure</groupId>
               <artifactId>azure-webapp-maven-plugin</artifactId>
               <version>1.9.1</version>
               <configuration>
                  <authentication>
                     <serverId>azure-auth</serverId>
                  </authentication>
                  <resourceGroup>apieproject</resourceGroup>
                  <appName>apiefrontdoor</appName>
                  <region>Central US</region>
                  <containerSettings>
                     <imageName>${docker.image.prefix}/${project.artifactId}</imageName>
                  </containerSettings>
                  <appServicePlanName>ASP-apieproject-ae27 (P1v2: 1)</appServicePlanName>
                  <appSettings>
                     <property>
                        <name>PORT</name>
                        <value>8080</value>
                     </property>
                  </appSettings>
                 </configuration>
            </plugin>
            <plugin>
                <groupId>com.spotify</groupId>
                <artifactId>docker-maven-plugin</artifactId>
                <version>1.2.2</version>
                <configuration>
                    <useMavenSettingsForAuth>true</useMavenSettingsForAuth>
                    <imageName>${docker.image.prefix}/${project.artifactId}</imageName>
                    <serverId>${azure.containerRegistry}</serverId>
                    <registryUrl>https://${docker.image.prefix}</registryUrl>
                    <dockerDirectory>docker</dockerDirectory>
                    <resources>
                        <resource>
                            <targetPath>/</targetPath>
                            <directory>${project.build.directory}</directory>
                            <include>${project.build.finalName}.jar</include>
                        </resource>
                    </resources>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

</code>```

And here is my settings.xml

```<code><servers>

    <server>
     <id>azure-auth</id>
      <configuration>
         <client>my-client</client>
         <tenant>my-tenant</tenant>
         <key>my-key</key>
         <environment>AZURE</environment>
      </configuration>
   </server>
   <server>
        <id>apiefrontdoor</id>
        <username>my-username</username>
        <password>my-password</password>
    </server>
  </servers>

</code>```

I can independently login to the Azure Container Registry using 'docker login' so that's not a credential issue. But although the project builds successfully, I can't push it to the same registry. Please assist.

答: Most probably, the problem is the id in the server for settings.xml file and docker.image.prefix in pom.xml file. It shoudld exactly match. Read example from url to know more about it.</p>

Body:
I've followed this tutorial:
https://www.baeldung.com/spring-boot-azure

However, although I set the credentials in settings.xml for maven, I still get this error:

[WARNING] Failed to push apiefrontdoor.azurecr.io/apiefrontdoor, retrying in 10 seconds (5/5).
[INFO] Pushing apiefrontdoor.azurecr.io/apiefrontdoor
The push refers to repository [apiefrontdoor.azurecr.io/apiefrontdoor]
c7f1d24c6c55: Preparing
a46d8ce138df: Preparing
42fd82c87bc8: Preparing
ceaf9e1ebef5: Preparing
9b9b7f3d56a0: Preparing
f1b5933fe4b5: Waiting
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  04:36 min
[INFO] Finished at: 2020-06-02T18:24:11-07:00
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal com.spotify:docker-maven-plugin:1.2.2:build (default-cli) on project apiefrontdoor: Exception caught: unauthorized: authentication required -> [Help 1]
org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal com.spotify:docker-maven-plugin:1.2.2:build (default-cli) on project apiefrontdoor: Exception caught
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:215)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:156)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:148)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:117)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:81)
    at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build (SingleThreadedBuilder.java:56)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute (LifecycleStarter.java:128)
    at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:305)
    at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:192)
    at org.apache.maven.DefaultMaven.execute (DefaultMaven.java:105)
    at org.apache.maven.cli.MavenCli.execute (MavenCli.java:957)
    at org.apache.maven.cli.MavenCli.doMain (MavenCli.java:289)
    at org.apache.maven.cli.MavenCli.main (MavenCli.java:193)
    at sun.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke (Method.java:498)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced (Launcher.java:282)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch (Launcher.java:225)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode (Launcher.java:406)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main (Launcher.java:347)
Caused by: org.apache.maven.plugin.MojoExecutionException: Exception caught
    at com.spotify.docker.AbstractDockerMojo.execute (AbstractDockerMojo.java:151)
    at com.spotify.docker.BuildMojo.execute (BuildMojo.java:329)
    at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo (DefaultBuildPluginManager.java:137)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:210)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:156)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:148)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:117)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:81)
    at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build (SingleThreadedBuilder.java:56)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute (LifecycleStarter.java:128)
    at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:305)
    at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:192)
    at org.apache.maven.DefaultMaven.execute (DefaultMaven.java:105)
    at org.apache.maven.cli.MavenCli.execute (MavenCli.java:957)
    at org.apache.maven.cli.MavenCli.doMain (MavenCli.java:289)
    at org.apache.maven.cli.MavenCli.main (MavenCli.java:193)
    at sun.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke (Method.java:498)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced (Launcher.java:282)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch (Launcher.java:225)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode (Launcher.java:406)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main (Launcher.java:347)
Caused by: com.spotify.docker.client.exceptions.DockerException: unauthorized: authentication required
    at com.spotify.docker.client.AnsiProgressHandler.progress (AnsiProgressHandler.java:55)
    at com.spotify.docker.Utils$DigestExtractingProgressHandler.progress (Utils.java:191)
    at com.spotify.docker.client.ProgressStream.tail (ProgressStream.java:77)
    at com.spotify.docker.client.DefaultDockerClient$ResponseTailReader.call (DefaultDockerClient.java:2754)
    at com.spotify.docker.client.DefaultDockerClient$ResponseTailReader.call (DefaultDockerClient.java:2738)
    at java.util.concurrent.FutureTask.run (FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker (ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run (ThreadPoolExecutor.java:624)
    at java.lang.Thread.run (Thread.java:748)
[ERROR]
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException

Here is my pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.0.RELEASE</version>
        <relativePath/>
    </parent>
    <groupId>com.apieproject</groupId>
    <artifactId>apiefrontdoor</artifactId>
    <version>0.0.1</version>
    <name>frontdoor</name>
    <description>APIE Project Landing Project</description>

    <properties>
       <jib-maven-plugin.version>2.3.0</jib-maven-plugin.version>
       <azure.containerRegistry>apiefrontdoor</azure.containerRegistry>
       <docker.image.prefix>apiefrontdoor.azurecr.io</docker.image.prefix>
       <java.version>1.8</java.version>
    </properties>

    <dependencies>
        ....
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
              <artifactId>jib-maven-plugin</artifactId>
              <groupId>com.google.cloud.tools</groupId>
              <version>${jib-maven-plugin.version}</version>
              <configuration>
                 <from>
                     <image>mcr.microsoft.com/java/jre:8-zulu-alpine</image>
                 </from>
                 <to>
                     <image>${docker.image.prefix}/${project.artifactId}</image>
                 </to>
              </configuration>
            </plugin>
            <plugin>
               <groupId>com.microsoft.azure</groupId>
               <artifactId>azure-webapp-maven-plugin</artifactId>
               <version>1.9.1</version>
               <configuration>
                  <authentication>
                     <serverId>azure-auth</serverId>
                  </authentication>
                  <resourceGroup>apieproject</resourceGroup>
                  <appName>apiefrontdoor</appName>
                  <region>Central US</region>
                  <containerSettings>
                     <imageName>${docker.image.prefix}/${project.artifactId}</imageName>
                  </containerSettings>
                  <appServicePlanName>ASP-apieproject-ae27 (P1v2: 1)</appServicePlanName>
                  <appSettings>
                     <property>
                        <name>PORT</name>
                        <value>8080</value>
                     </property>
                  </appSettings>
                 </configuration>
            </plugin>
            <plugin>
                <groupId>com.spotify</groupId>
                <artifactId>docker-maven-plugin</artifactId>
                <version>1.2.2</version>
                <configuration>
                    <useMavenSettingsForAuth>true</useMavenSettingsForAuth>
                    <imageName>${docker.image.prefix}/${project.artifactId}</imageName>
                    <serverId>${azure.containerRegistry}</serverId>
                    <registryUrl>https://${docker.image.prefix}</registryUrl>
                    <dockerDirectory>docker</dockerDirectory>
                    <resources>
                        <resource>
                            <targetPath>/</targetPath>
                            <directory>${project.build.directory}</directory>
                            <include>${project.build.finalName}.jar</include>
                        </resource>
                    </resources>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

And here is my settings.xml

<servers>

    <server>
     <id>azure-auth</id>
      <configuration>
         <client>my-client</client>
         <tenant>my-tenant</tenant>
         <key>my-key</key>
         <environment>AZURE</environment>
      </configuration>
   </server>
   <server>
        <id>apiefrontdoor</id>
        <username>my-username</username>
        <password>my-password</password>
    </server>
  </servers>

I can independently login to the Azure Container Registry using 'docker login' so that's not a credential issue. But although the project builds successfully, I can't push it to the same registry. Please assist.


问:
How to do product sorting when we search for certain product in Django?
views.py:-

```<code>def search(request):
global pro
global products
if not request.GET.get('price_filter') == '1' or request.GET.get('price_filter') == '2':
    q = request.GET.get("q")
    products = Product.objects.filter(active=True, name__icontains=q)
    categories = Category.objects.filter(active=True)
    brands = Brand.objects.filter(active=True)
    context = {"products": products,
               "categories": categories,
                "brands": brands,
                "title": q + " - search"}
    return render(request, "shop/home.html", context)
pro = products

if request.GET.get('price_filter') == '1':
    products = pro.order_by('price')
    categories = Category.objects.filter(active=True)
    brands = Brand.objects.filter(active=True)
    context = {"products": products,
               "categories": categories,
               "brands": brands}
    return render(request, "shop/home.html", context)

elif request.GET.get('price_filter') == '2':
    products = pro.order_by('-price')
    categories = Category.objects.filter(active=True)
    brands = Brand.objects.filter(active=True)
    context = {"products": products,
               "categories": categories,
               "brands": brands}
    return render(request, "shop/home.html", context)
</code>```

In HTML:-

```<code><form method='get' action='#' style="margin-top:-20px; margin-left: 8px;">
        <input class="btn btn-outline-dark" type="checkbox" value="1" name="price_filter"/>Low to High

        <input class="btn btn-outline-dark" type="checkbox" value="2" name="price_filter"/>High to Low
        <button class="btn" type="submit" value="Sort">Sort</button>
    </form>
</code>```

Using that search we I am able to sort low to high, but when I choose High to Low, it shows certain Error:-

```<code>Cannot use None as a query value
</code>```

I know this is not the right method to do this, but can please help me out with this, or guide me with the correct way to do sorting.

答:
In views I changed this and it is working completely fine now:-

views.py

```<code>def search(request):
global pro
global products
if request.GET.get('price_filter') not in ["1", "2"]:
    q = request.GET.get("q")
    products = Product.objects.filter(active=True, name__icontains=q)
    categories = Category.objects.filter(active=True)
    brands = Brand.objects.filter(active=True)
    context = {"products": products,
               "categories": categories,
                "brands": brands,
                "title": q + " - search"}
    return render(request, "shop/home.html", context)
pro = products

if request.GET.get('price_filter') == '1':
    products = pro.order_by('price')
    categories = Category.objects.filter(active=True)
    brands = Brand.objects.filter(active=True)
    context = {"products": products,
               "categories": categories,
               "brands": brands}
    return render(request, "shop/home.html", context)

elif request.GET.get('price_filter') == '2':
    products = pro.order_by('-price')
    categories = Category.objects.filter(active=True)
    brands = Brand.objects.filter(active=True)
    context = {"products": products,
               "categories": categories,
               "brands": brands}
    return render(request, "shop/home.html", context)
</code>```

Body:
views.py:-

def search(request):
global pro
global products
if not request.GET.get('price_filter') == '1' or request.GET.get('price_filter') == '2':
    q = request.GET.get("q")
    products = Product.objects.filter(active=True, name__icontains=q)
    categories = Category.objects.filter(active=True)
    brands = Brand.objects.filter(active=True)
    context = {"products": products,
               "categories": categories,
                "brands": brands,
                "title": q + " - search"}
    return render(request, "shop/home.html", context)
pro = products

if request.GET.get('price_filter') == '1':
    products = pro.order_by('price')
    categories = Category.objects.filter(active=True)
    brands = Brand.objects.filter(active=True)
    context = {"products": products,
               "categories": categories,
               "brands": brands}
    return render(request, "shop/home.html", context)

elif request.GET.get('price_filter') == '2':
    products = pro.order_by('-price')
    categories = Category.objects.filter(active=True)
    brands = Brand.objects.filter(active=True)
    context = {"products": products,
               "categories": categories,
               "brands": brands}
    return render(request, "shop/home.html", context)

In HTML:-

<form method='get' action='#' style="margin-top:-20px; margin-left: 8px;">
        <input class="btn btn-outline-dark" type="checkbox" value="1" name="price_filter"/>Low to High

        <input class="btn btn-outline-dark" type="checkbox" value="2" name="price_filter"/>High to Low
        <button class="btn" type="submit" value="Sort">Sort</button>
    </form>

Using that search we I am able to sort low to high, but when I choose High to Low, it shows certain Error:-

Cannot use None as a query value

I know this is not the right method to do this, but can please help me out with this, or guide me with the correct way to do sorting.

Body:
In views I changed this and it is working completely fine now:-

views.py

def search(request):
global pro
global products
if request.GET.get('price_filter') not in ["1", "2"]:
    q = request.GET.get("q")
    products = Product.objects.filter(active=True, name__icontains=q)
    categories = Category.objects.filter(active=True)
    brands = Brand.objects.filter(active=True)
    context = {"products": products,
               "categories": categories,
                "brands": brands,
                "title": q + " - search"}
    return render(request, "shop/home.html", context)
pro = products

if request.GET.get('price_filter') == '1':
    products = pro.order_by('price')
    categories = Category.objects.filter(active=True)
    brands = Brand.objects.filter(active=True)
    context = {"products": products,
               "categories": categories,
               "brands": brands}
    return render(request, "shop/home.html", context)

elif request.GET.get('price_filter') == '2':
    products = pro.order_by('-price')
    categories = Category.objects.filter(active=True)
    brands = Brand.objects.filter(active=True)
    context = {"products": products,
               "categories": categories,
               "brands": brands}
    return render(request, "shop/home.html", context)


问:
How to group rows with a Unix timestamp by week?
I currently use the following query to get data grouped by day:

```<code>SELECT DATE(from_unixtime(timestampcolumn)) as date, COUNT(*)
FROM db.table
WHERE timestampcolumn BETWEEN :startTime AND :endTime
GROUP BY DATE(from_unixtime(timestampcolumn))
ORDER BY timestampcolumn
</code>```

The DATE() function returns the string YYYY-MM-DD, so the above query is simple and works great for getting data grouped by each day, but how can I modify it to return data grouped by each week?

In response to Jonathan's answer:

I tried making an example in SQL Fiddle, but the DATE() SQL function does not work in SQL Fiddle for some reason (it simply doesn't work in SQL Fiddle, but it does on both my live and wamp servers).

So here's an example you can try out if you'd like:

SETUP:

```<code>CREATE TABLE example(id INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(id), timestamp INT, data INT);

INSERT INTO example (timestamp, data) VALUES (1355400000, 1);
INSERT INTO example (timestamp, data) VALUES (1355659200, 1);
INSERT INTO example (timestamp, data) VALUES (1357694861, 1);
INSERT INTO example (timestamp, data) VALUES (1355918400, 1);
INSERT INTO example (timestamp, data) VALUES (1356955200, 1);
INSERT INTO example (timestamp, data) VALUES (1358510400, 1);
INSERT INTO example (timestamp, data) VALUES (1358769600, 1);
INSERT INTO example (timestamp, data) VALUES (1358769600, 1);
INSERT INTO example (timestamp, data) VALUES (1371824368, 1);
INSERT INTO example (timestamp, data) VALUES (1371833476, 1);
INSERT INTO example (timestamp, data) VALUES (1371840324, 1);
INSERT INTO example (timestamp, data) VALUES (1371850523, 1);
INSERT INTO example (timestamp, data) VALUES (1371863191, 1);
INSERT INTO example (timestamp, data) VALUES (1371865401, 1);
INSERT INTO example (timestamp, data) VALUES (1371872379, 1);
INSERT INTO example (timestamp, data) VALUES (1372006190, 1);
INSERT INTO example (timestamp, data) VALUES (1372051945, 1);
INSERT INTO example (timestamp, data) VALUES (1372189402, 1);
INSERT INTO example (timestamp, data) VALUES (1372207830, 1);
INSERT INTO example (timestamp, data) VALUES (1372229733, 1);
INSERT INTO example (timestamp, data) VALUES (1372350338, 1);
INSERT INTO example (timestamp, data) VALUES (1372358259, 1);
</code>```

QUERY:

```<code>SELECT DATE(from_unixtime(timestamp)) as date, COUNT(*)
FROM example
WHERE timestamp BETWEEN 0 AND 9999999999999999999999999999999
GROUP BY DATE(from_unixtime(timestamp))
ORDER BY timestamp
</code>```

OUTPUT:

```<code>2012-12-13  1
2012-12-16  1
2012-12-19  1
2012-12-31  1
2013-01-08  1
2013-01-18  1
2013-01-21  2
2013-06-21  7
2013-06-23  1
2013-06-24  1
2013-06-25  2
2013-06-26  1
2013-06-27  2
</code>```

Now, dividing the time stamp by (7 * 24 * 3600).

QUERY:

```<code>SELECT DATE(from_unixtime(timestamp / (7 * 24 * 3600))) as date, COUNT(*)
FROM example
WHERE timestamp BETWEEN 0 AND 9999999999999999999999999999999
GROUP BY DATE(from_unixtime(timestamp / (7 * 24 * 3600)))
ORDER BY timestamp
</code>```

OUTPUT:

```<code>1969-12-31  22
</code>```

答:
Here is a clean, tested solution based on the above suggestions:

```<code>SELECT  WEEK(from_unixtime(timestamp)) AS week_no,
        date(from_unixtime(timestamp)) as week_start,
        COUNT(*) as row_count
FROM api_tracker
GROUP BY WEEK(from_unixtime(timestamp))
ORDER BY week_no DESC
</code>```

SQL response:

Thanks Shane N and Jonathan Leffler.

Body:
I currently use the following query to get data grouped by day:

SELECT DATE(from_unixtime(timestampcolumn)) as date, COUNT(*)
FROM db.table
WHERE timestampcolumn BETWEEN :startTime AND :endTime
GROUP BY DATE(from_unixtime(timestampcolumn))
ORDER BY timestampcolumn

The DATE() function returns the string YYYY-MM-DD, so the above query is simple and works great for getting data grouped by each day, but how can I modify it to return data grouped by each week?

In response to Jonathan's answer:

I tried making an example in SQL Fiddle, but the DATE() SQL function does not work in SQL Fiddle for some reason (it simply doesn't work in SQL Fiddle, but it does on both my live and wamp servers).

So here's an example you can try out if you'd like:

SETUP:

CREATE TABLE example(id INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(id), timestamp INT, data INT);

INSERT INTO example (timestamp, data) VALUES (1355400000, 1);
INSERT INTO example (timestamp, data) VALUES (1355659200, 1);
INSERT INTO example (timestamp, data) VALUES (1357694861, 1);
INSERT INTO example (timestamp, data) VALUES (1355918400, 1);
INSERT INTO example (timestamp, data) VALUES (1356955200, 1);
INSERT INTO example (timestamp, data) VALUES (1358510400, 1);
INSERT INTO example (timestamp, data) VALUES (1358769600, 1);
INSERT INTO example (timestamp, data) VALUES (1358769600, 1);
INSERT INTO example (timestamp, data) VALUES (1371824368, 1);
INSERT INTO example (timestamp, data) VALUES (1371833476, 1);
INSERT INTO example (timestamp, data) VALUES (1371840324, 1);
INSERT INTO example (timestamp, data) VALUES (1371850523, 1);
INSERT INTO example (timestamp, data) VALUES (1371863191, 1);
INSERT INTO example (timestamp, data) VALUES (1371865401, 1);
INSERT INTO example (timestamp, data) VALUES (1371872379, 1);
INSERT INTO example (timestamp, data) VALUES (1372006190, 1);
INSERT INTO example (timestamp, data) VALUES (1372051945, 1);
INSERT INTO example (timestamp, data) VALUES (1372189402, 1);
INSERT INTO example (timestamp, data) VALUES (1372207830, 1);
INSERT INTO example (timestamp, data) VALUES (1372229733, 1);
INSERT INTO example (timestamp, data) VALUES (1372350338, 1);
INSERT INTO example (timestamp, data) VALUES (1372358259, 1);

QUERY:

SELECT DATE(from_unixtime(timestamp)) as date, COUNT(*)
FROM example
WHERE timestamp BETWEEN 0 AND 9999999999999999999999999999999
GROUP BY DATE(from_unixtime(timestamp))
ORDER BY timestamp

OUTPUT:

2012-12-13  1
2012-12-16  1
2012-12-19  1
2012-12-31  1
2013-01-08  1
2013-01-18  1
2013-01-21  2
2013-06-21  7
2013-06-23  1
2013-06-24  1
2013-06-25  2
2013-06-26  1
2013-06-27  2

Now, dividing the time stamp by (7 * 24 * 3600).

QUERY:

SELECT DATE(from_unixtime(timestamp / (7 * 24 * 3600))) as date, COUNT(*)
FROM example
WHERE timestamp BETWEEN 0 AND 9999999999999999999999999999999
GROUP BY DATE(from_unixtime(timestamp / (7 * 24 * 3600)))
ORDER BY timestamp

OUTPUT:

1969-12-31  22

Body:
Here is a clean, tested solution based on the above suggestions:

SELECT  WEEK(from_unixtime(timestamp)) AS week_no,
        date(from_unixtime(timestamp)) as week_start,
        COUNT(*) as row_count
FROM api_tracker
GROUP BY WEEK(from_unixtime(timestamp))
ORDER BY week_no DESC

SQL response:

Thanks Shane N and Jonathan Leffler.


问:
Convert String to HTML Ready text for MAILTO: URL
I am writing a large Java Application in which I would like to include a "Send Email" button.
All it does is open a mailto url with the appropriate headers.

The only difficulty I am having is parsing the input strings so that they are formatted appropriately, for example:
mailto:someone@somewhere.net?subject=This is the subject
needs to become
mailto:someone@somewhere.net?subject=This%20is%20the%20subject

答: You can try URLEncoder, specifically the encode method that can be found here.