问:
WCF Authentication - Username-Password using custom validator - Works on My Machine
I have a WCF service and a client, that uses a custom UserNamePasswordValidator for authentication.

I use a self-signed certificate, created by the following command line:

```<code>makecert -sr LocalMachine -ss My -a sha1 -n CN=SelfSignedCertificate -sky exchange -pe
</code>```

Calling methods in the service from the below client works fine on my machine :) But as soon as I deploy it to my server, I get this error message: The request for security token could not be satisfied because authentication failed.

I can browse the endpoint URL and see the WSDL for the service. I'm not sure, but I recall that I configured some Anonymous Authentication in IIS on my local machine, but it looks similar on the server as well.

My WCF service is hosted in IIS 7.0, using this configuration:

```<code><system.serviceModel>
    <bindings>
        <wsHttpBinding>
            <binding name="secured">
                <security mode="Message">
                    <message clientCredentialType="UserName" />
                </security>
            </binding>
            <binding name="unsecured">
                <security mode="None" />
            </binding>
        </wsHttpBinding>
        <basicHttpBinding>
            <binding name="secured">
                <security mode="TransportWithMessageCredential">
                    <message clientCredentialType="UserName" />
                </security>
            </binding>
            <binding name="unsecured">
                <security mode="None" />
            </binding>
        </basicHttpBinding>
        <webHttpBinding>
            <binding name="unsecured">
                <security mode="None" />
            </binding>
        </webHttpBinding>
    </bindings>
    <services>
        <service name="Milkshake.Admin.Services.AdminService" behaviorConfiguration="CustomValidator">
            <endpoint address="" binding="wsHttpBinding" contract="Milkshake.Admin.Model.ServiceContracts.IAdminService" bindingConfiguration="secured" />
        </service>
        <service name="Milkshake.Admin.Services.DeploymentService">
            <endpoint address="" binding="wsHttpBinding" contract="Milkshake.Admin.Model.ServiceContracts.IDeploymentService"/>
        </service>
        <service name="Milkshake.Admin.Services.LogService" behaviorConfiguration="CustomValidator">
            <endpoint address="" binding="wsHttpBinding" contract="Milkshake.Core.Logging.ILogService" bindingConfiguration="secured" />
        </service>
        <service name="Milkshake.Admin.Services.MailService">
            <endpoint address="" binding="wsHttpBinding" contract="Milkshake.Admin.Model.ServiceContracts.IMailService"/>
        </service>
    </services>
    <behaviors>
        <serviceBehaviors>
            <behavior name="CustomValidator">
                <serviceMetadata httpGetEnabled="true" />
                <serviceCredentials>
                    <serviceCertificate findValue="SelfSignedCertificate" x509FindType="FindBySubjectName" />
                    <userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="Milkshake.Admin.Services.MilkshakeCredentialValidator, Milkshake.Admin.Services" />
                    <clientCertificate>
                        <authentication certificateValidationMode="None" />
                    </clientCertificate>
                </serviceCredentials>
                <serviceDebug httpHelpPageEnabled="true" includeExceptionDetailInFaults="true" />
            </behavior>
        </serviceBehaviors>

        <endpointBehaviors>
            <behavior name="json">
                <enableWebScript />
            </behavior>

            <behavior name="xml">
                <webHttp defaultOutgoingResponseFormat="Xml" defaultBodyStyle="Wrapped" />
            </behavior>
        </endpointBehaviors>
    </behaviors>
</system.serviceModel>
</code>```

The client configuration looks like this:

```<code><system.serviceModel>
    <client>
        <endpoint address="http://server-url/LogService.svc" binding="wsHttpBinding" contract="Milkshake.Core.Logging.ILogService">
            <identity>
                <dns value="SelfSignedCertificate" />
            </identity>
        </endpoint>
    </client>
</system.serviceModel>
</code>```

My custom validator is this:

```<code>using System;
using System.IdentityModel.Selectors;
using System.ServiceModel;

namespace Milkshake.Admin.Services
{
    /// <summary>
    /// WCF Service validator for Milkshake.
    /// </summary>
    public class MilkshakeCredentialValidator : UserNamePasswordValidator
    {
        /// <summary>
        /// When overridden in a derived class, validates the specified username and password.
        /// </summary>
        /// <param name="userName">The username to validate.</param>
        /// <param name="password">The password to validate.</param>
        public override void Validate(string userName, string password)
        {
            if (String.IsNullOrWhiteSpace(userName) || String.IsNullOrWhiteSpace(password))
            {
                throw new ArgumentNullException();
            }

            if (userName.Equals("martin") && password.Equals("normark"))
            {
                return;
            }

            FaultCode fc = new FaultCode("ValidationFailed");
            FaultReason fr = new FaultReason("Good reason");

            throw new FaultException(fr, fc);
        }
    }
}
</code>```

My service client, looks like this:

```<code>using System;
using System.ServiceModel;
using System.ServiceModel.Security;
using Milkshake.Core.Logging;

namespace Milkshake.Admin.ServiceClients.Logging
{
    /// <summary>
    /// WCF Service Client implementation of the <see cref="ILogService"/> contract.
    /// </summary>
    public class LogServiceClient : ILogService
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="LogServiceClient"/> class.
        /// </summary>
        public LogServiceClient()
        {
            var factory = new ChannelFactory<ILogService>(String.Empty);
            factory.Credentials.ServiceCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.None;
            factory.Credentials.UserName.UserName = "martin";
            factory.Credentials.UserName.Password = "normark";

            var binding = factory.Endpoint.Binding as WSHttpBinding;

            if (binding != null)
            {
                binding.Security.Mode = SecurityMode.Message;
                binding.Security.Message.ClientCredentialType = MessageCredentialType.UserName;
            }

            this.AdminLogService = factory.CreateChannel();
        }

        /// <summary>
        /// Gets or sets the admin log service.
        /// </summary>
        /// <value>The admin log service.</value>
        private ILogService AdminLogService { get; set; }

        #region ILogService Members

        /// <summary>
        /// Logs the error simple.
        /// </summary>
        /// <param name="applicationInstanceId">The application instance id.</param>
        /// <param name="logDate">The log date.</param>
        /// <param name="exceptionMessage">The exception message.</param>
        /// <param name="description">The description.</param>
        /// <param name="severity">The severity.</param>
        /// <param name="userAgent">The user agent.</param>
        /// <param name="source">The source.</param>
        public void LogErrorSimple(int applicationInstanceId, DateTime logDate, string exceptionMessage, string description, Severity severity, string userAgent, string source)
        {
            this.AdminLogService.LogErrorSimple(applicationInstanceId, logDate, exceptionMessage, description, severity, userAgent, source);
        }

        /// <summary>
        /// Logs the error advanced.
        /// </summary>
        /// <param name="applicationInstanceId">The application instance id.</param>
        /// <param name="logDate">The log date.</param>
        /// <param name="exceptionType">Type of the exception.</param>
        /// <param name="exceptionCode">The exception code.</param>
        /// <param name="exceptionMessage">The exception message.</param>
        /// <param name="stackTrace">The stack trace.</param>
        /// <param name="caller">The caller.</param>
        /// <param name="location">The location.</param>
        /// <param name="source">The source (A service, app etc).</param>
        /// <param name="description">The description.</param>
        /// <param name="severity">The severity.</param>
        /// <param name="username">The username.</param>
        /// <param name="userAgent">The user agent.</param>
        public void LogErrorAdvanced(int applicationInstanceId, DateTime logDate, string exceptionType, string exceptionCode, string exceptionMessage, string stackTrace, string caller, string location, string source, string description, Severity severity, string username, string userAgent)
        {
            this.AdminLogService.LogErrorAdvanced(applicationInstanceId, logDate, exceptionType, exceptionCode, exceptionMessage, stackTrace, caller, location, source, description, severity, userAgent, userAgent);
        }

        /// <summary>
        /// Logs the behavior with data.
        /// </summary>
        /// <param name="applicationInstanceId">The application instance id.</param>
        /// <param name="action">The action.</param>
        /// <param name="logDate">The log date.</param>
        /// <param name="userAgent">The user agent.</param>
        /// <param name="behaviorData">The behavior data.</param>
        /// <param name="source">The source.</param>
        public void LogBehaviorWithData(int applicationInstanceId, string action, DateTime logDate, string userAgent, string behaviorData, string source)
        {
            this.AdminLogService.LogBehaviorWithData(applicationInstanceId, action, logDate, userAgent, behaviorData, source);
        }

        /// <summary>
        /// Logs the behavior.
        /// </summary>
        /// <param name="applicationInstanceId">The application instance id.</param>
        /// <param name="action">The action.</param>
        /// <param name="logDate">The log date.</param>
        /// <param name="userAgent">The user agent.</param>
        /// <param name="source">The source.</param>
        public void LogBehavior(int applicationInstanceId, string action, DateTime logDate, string userAgent, string source)
        {
            this.AdminLogService.LogBehavior(applicationInstanceId, action, logDate, userAgent, source);
        }

        #endregion
    }
}
</code>```

答:
I also use the UserNamePasswordValidator with certificates generated using makecert.

Instead of using IIS, use WcfSvcHost so you can be sure it starts successfully. The reason I'm suggesting this is that possibly Chain building for the certificate is failing. There is a setting you can use to disable chain building. (Update: I think you're doing that already with CertificateValidationMode="none")

Another thing I'm noticing is that not all your service definitions specify behaviourConfiguration. This is a little beech to find because it gets removed sometimes by VS when you update your service references.

The exception you mention, is that the message from the inner most exception?

Body:
I have a WCF service and a client, that uses a custom UserNamePasswordValidator for authentication.

I use a self-signed certificate, created by the following command line:

makecert -sr LocalMachine -ss My -a sha1 -n CN=SelfSignedCertificate -sky exchange -pe

Calling methods in the service from the below client works fine on my machine :) But as soon as I deploy it to my server, I get this error message: The request for security token could not be satisfied because authentication failed.

I can browse the endpoint URL and see the WSDL for the service. I'm not sure, but I recall that I configured some Anonymous Authentication in IIS on my local machine, but it looks similar on the server as well.

My WCF service is hosted in IIS 7.0, using this configuration:

<system.serviceModel>
    <bindings>
        <wsHttpBinding>
            <binding name="secured">
                <security mode="Message">
                    <message clientCredentialType="UserName" />
                </security>
            </binding>
            <binding name="unsecured">
                <security mode="None" />
            </binding>
        </wsHttpBinding>
        <basicHttpBinding>
            <binding name="secured">
                <security mode="TransportWithMessageCredential">
                    <message clientCredentialType="UserName" />
                </security>
            </binding>
            <binding name="unsecured">
                <security mode="None" />
            </binding>
        </basicHttpBinding>
        <webHttpBinding>
            <binding name="unsecured">
                <security mode="None" />
            </binding>
        </webHttpBinding>
    </bindings>
    <services>
        <service name="Milkshake.Admin.Services.AdminService" behaviorConfiguration="CustomValidator">
            <endpoint address="" binding="wsHttpBinding" contract="Milkshake.Admin.Model.ServiceContracts.IAdminService" bindingConfiguration="secured" />
        </service>
        <service name="Milkshake.Admin.Services.DeploymentService">
            <endpoint address="" binding="wsHttpBinding" contract="Milkshake.Admin.Model.ServiceContracts.IDeploymentService"/>
        </service>
        <service name="Milkshake.Admin.Services.LogService" behaviorConfiguration="CustomValidator">
            <endpoint address="" binding="wsHttpBinding" contract="Milkshake.Core.Logging.ILogService" bindingConfiguration="secured" />
        </service>
        <service name="Milkshake.Admin.Services.MailService">
            <endpoint address="" binding="wsHttpBinding" contract="Milkshake.Admin.Model.ServiceContracts.IMailService"/>
        </service>
    </services>
    <behaviors>
        <serviceBehaviors>
            <behavior name="CustomValidator">
                <serviceMetadata httpGetEnabled="true" />
                <serviceCredentials>
                    <serviceCertificate findValue="SelfSignedCertificate" x509FindType="FindBySubjectName" />
                    <userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="Milkshake.Admin.Services.MilkshakeCredentialValidator, Milkshake.Admin.Services" />
                    <clientCertificate>
                        <authentication certificateValidationMode="None" />
                    </clientCertificate>
                </serviceCredentials>
                <serviceDebug httpHelpPageEnabled="true" includeExceptionDetailInFaults="true" />
            </behavior>
        </serviceBehaviors>

        <endpointBehaviors>
            <behavior name="json">
                <enableWebScript />
            </behavior>

            <behavior name="xml">
                <webHttp defaultOutgoingResponseFormat="Xml" defaultBodyStyle="Wrapped" />
            </behavior>
        </endpointBehaviors>
    </behaviors>
</system.serviceModel>

The client configuration looks like this:

<system.serviceModel>
    <client>
        <endpoint address="http://server-url/LogService.svc" binding="wsHttpBinding" contract="Milkshake.Core.Logging.ILogService">
            <identity>
                <dns value="SelfSignedCertificate" />
            </identity>
        </endpoint>
    </client>
</system.serviceModel>

My custom validator is this:

using System;
using System.IdentityModel.Selectors;
using System.ServiceModel;

namespace Milkshake.Admin.Services
{
    ///
    /// WCF Service validator for Milkshake.
    ///
    public class MilkshakeCredentialValidator : UserNamePasswordValidator
    {
        ///
        /// When overridden in a derived class, validates the specified username and password.
        ///
        /// <param name="userName">The username to validate.</param>
        /// <param name="password">The password to validate.</param>
        public override void Validate(string userName, string password)
        {
            if (String.IsNullOrWhiteSpace(userName) || String.IsNullOrWhiteSpace(password))
            {
                throw new ArgumentNullException();
            }

            if (userName.Equals("martin") && password.Equals("normark"))
            {
                return;
            }

            FaultCode fc = new FaultCode("ValidationFailed");
            FaultReason fr = new FaultReason("Good reason");

            throw new FaultException(fr, fc);
        }
    }
}

My service client, looks like this:

using System;
using System.ServiceModel;
using System.ServiceModel.Security;
using Milkshake.Core.Logging;

namespace Milkshake.Admin.ServiceClients.Logging
{
    ///
    /// WCF Service Client implementation of the <see cref="ILogService"/> contract.
    ///
    public class LogServiceClient : ILogService
    {
        ///
        /// Initializes a new instance of the <see cref="LogServiceClient"/> class.
        ///
        public LogServiceClient()
        {
            var factory = new ChannelFactory<ILogService>(String.Empty);
            factory.Credentials.ServiceCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.None;
            factory.Credentials.UserName.UserName = "martin";
            factory.Credentials.UserName.Password = "normark";

            var binding = factory.Endpoint.Binding as WSHttpBinding;

            if (binding != null)
            {
                binding.Security.Mode = SecurityMode.Message;
                binding.Security.Message.ClientCredentialType = MessageCredentialType.UserName;
            }

            this.AdminLogService = factory.CreateChannel();
        }

        ///
        /// Gets or sets the admin log service.
        ///
        /// <value>The admin log service.</value>
        private ILogService AdminLogService { get; set; }

        #region ILogService Members

        ///
        /// Logs the error simple.
        ///
        /// <param name="applicationInstanceId">The application instance id.</param>
        /// <param name="logDate">The log date.</param>
        /// <param name="exceptionMessage">The exception message.</param>
        /// <param name="description">The description.</param>
        /// <param name="severity">The severity.</param>
        /// <param name="userAgent">The user agent.</param>
        /// <param name="source">The source.</param>
        public void LogErrorSimple(int applicationInstanceId, DateTime logDate, string exceptionMessage, string description, Severity severity, string userAgent, string source)
        {
            this.AdminLogService.LogErrorSimple(applicationInstanceId, logDate, exceptionMessage, description, severity, userAgent, source);
        }

        ///
        /// Logs the error advanced.
        ///
        /// <param name="applicationInstanceId">The application instance id.</param>
        /// <param name="logDate">The log date.</param>
        /// <param name="exceptionType">Type of the exception.</param>
        /// <param name="exceptionCode">The exception code.</param>
        /// <param name="exceptionMessage">The exception message.</param>
        /// <param name="stackTrace">The stack trace.</param>
        /// <param name="caller">The caller.</param>
        /// <param name="location">The location.</param>
        /// <param name="source">The source (A service, app etc).</param>
        /// <param name="description">The description.</param>
        /// <param name="severity">The severity.</param>
        /// <param name="username">The username.</param>
        /// <param name="userAgent">The user agent.</param>
        public void LogErrorAdvanced(int applicationInstanceId, DateTime logDate, string exceptionType, string exceptionCode, string exceptionMessage, string stackTrace, string caller, string location, string source, string description, Severity severity, string username, string userAgent)
        {
            this.AdminLogService.LogErrorAdvanced(applicationInstanceId, logDate, exceptionType, exceptionCode, exceptionMessage, stackTrace, caller, location, source, description, severity, userAgent, userAgent);
        }

        ///
        /// Logs the behavior with data.
        ///
        /// <param name="applicationInstanceId">The application instance id.</param>
        /// <param name="action">The action.</param>
        /// <param name="logDate">The log date.</param>
        /// <param name="userAgent">The user agent.</param>
        /// <param name="behaviorData">The behavior data.</param>
        /// <param name="source">The source.</param>
        public void LogBehaviorWithData(int applicationInstanceId, string action, DateTime logDate, string userAgent, string behaviorData, string source)
        {
            this.AdminLogService.LogBehaviorWithData(applicationInstanceId, action, logDate, userAgent, behaviorData, source);
        }

        ///
        /// Logs the behavior.
        ///
        /// <param name="applicationInstanceId">The application instance id.</param>
        /// <param name="action">The action.</param>
        /// <param name="logDate">The log date.</param>
        /// <param name="userAgent">The user agent.</param>
        /// <param name="source">The source.</param>
        public void LogBehavior(int applicationInstanceId, string action, DateTime logDate, string userAgent, string source)
        {
            this.AdminLogService.LogBehavior(applicationInstanceId, action, logDate, userAgent, source);
        }

        #endregion
    }
}


来源: stackexchange

问:
JQuery .prop() on click checked > false
I have a form with checkboxes which generates a new block displaying the color filters selected by the user.

Form

In this new block, I made a click event which removes the selected filter with the ".buttonRemoveFilter" button.

I try to uncheck the checkbox in conjunction with the filter but I can only uncheck all the checkboxes.

```<code>$(document).on("click", ".buttonRemoveFilter", function(){

     $("[id^=branche_search_form_couleurs_").prop("checked", false);
     $(this).parent().parent().remove();
});
</code>```

I try to do, that when I remove a filter from the new block, it unchecks the color checkbox related to this filter.

New block

```<code><div class="poPupFiltre">
  <div class="sousBlockPoPup">
    <button class="buttonRemoveFilter">
      <img class="img-fluid imgPoPup" src="{{ asset ('../build/images/supprimer.svg') }}" alt="">
    </button>
    <p class="textPopUp"></p>
  </div>
</div>
</code>```

答:
Try these options.

In your form add a common class to your input checkbox (let's say the class name is ".chxbox")

Then use this jQuery function

```<code>   $('.chxbox').click(function(){
         id = $(this).attr('id');
         $(id).prop('checked',false);
         $(this).remove();
    });
</code>```

ContentLicense: CC BY-SA 4.0

Title: JQuery .prop() on click checked > false

Body:
I have a form with checkboxes which generates a new block displaying the color filters selected by the user.

Form

In this new block, I made a click event which removes the selected filter with the ".buttonRemoveFilter" button.

I try to uncheck the checkbox in conjunction with the filter but I can only uncheck all the checkboxes.

$(document).on("click", ".buttonRemoveFilter", function(){

     $("[id^=branche_search_form_couleurs_").prop("checked", false);
     $(this).parent().parent().remove();
});

I try to do, that when I remove a filter from the new block, it unchecks the color checkbox related to this filter.

New block

    <button class="buttonRemoveFilter">

    </button>

Body:
Try these options.

In your form add a common class to your input checkbox (let's say the class name is ".chxbox")

Then use this jQuery function

   $('.chxbox').click(function(){
         id = $(this).attr('id');
         $(id).prop('checked',false);
         $(this).remove();
    });


问:
Is it possible to manage PAT through the TFS client libraries?
We have Azure DevOps Server 2019 (on-prem, do not confuse with Azure DevOps Services 2019, which are hosted in Azure) and unfortunately its REST Api does not support managing PATs. So, I wonder if we could do it using the client libraries.

Does anyone have any example of it? E.g. I want to create/update a PAT to access the Azure Artifacts. How can this be done?

答:
Currently, there is no client libraries or REST API can manage PAT. You can only create/update PAT within the user interface (UI). You may submit a feature request here:

https://developercommunity.visualstudio.com/content/idea/post.html?space=22


答:
Add a way of knowing which filter you have clicked - if you want to remove BLANC filter, check that the user has clicked BLANC filter type. Then access checkbox input by using

```<code>$("input[value='"+clickedFilterType+"']")
</code>```

Something like this:

```<code>$(document).on("click", ".buttonRemoveFilter", function(){
     let clickedFilterType = $(this).attr("data-type");
     $("input[value='"+clickedFilterType+"']").prop("checked", false);

});
</code>```

Title: JQuery .prop() on click checked > false

Body:
Add a way of knowing which filter you have clicked - if you want to remove BLANC filter, check that the user has clicked BLANC filter type. Then access checkbox input by using

$("input[value='"+clickedFilterType+"']")

Something like this:

$(document).on("click", ".buttonRemoveFilter", function(){
     let clickedFilterType = $(this).attr("data-type");
     $("input[value='"+clickedFilterType+"']").prop("checked", false);

});


问:
CORS in .NET Core
I am trying to enable CORS in .NET Core in this way:

```<code>    public IConfigurationRoot Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddCors(options => options.AddPolicy("AllowAll", p => p.AllowAnyOrigin()
                                                                    .AllowAnyMethod()
                                                                     .AllowAnyHeader()));
        services.AddMvc();
    }

    public void Configure(IApplicationBuilder app)
    {
        app.UseCors("AllowAll");

        app.UseMvc(routes =>
         {
             routes.MapRoute(
                 name: "default",
                 template: "{controller=Home}/{action=Index}/{id?}");
         });

    }
}
</code>```

However, when I am sending a request to my app with Angular 2 I am getting the famous

"No 'Access-Control-Allow-Origin' header is present on the requested
  resource."

error message.

I am also using Windows Authentication + WebListener.
If I am checking with postman the only response headers are:

Content-Length →3533
  Content-Type →application/json;
  charset=utf-8
  Date →Fri, 14 Oct 2016 12:17:57
  GMT Server →Microsoft-HTTPAPI/2.0

So there must be still something wrong configured. Any proposals?

If I remove the outcommented line it works, but I need Windows Authentication :-(

```<code>        var host = new WebHostBuilder()
            .UseWebListener()
            .UseContentRoot(Directory.GetCurrentDirectory())
            .UseIISIntegration()
            .UseStartup<Startup>()
            //.UseWebListener(options => options.Listener.AuthenticationManager.AuthenticationSchemes = AuthenticationSchemes.NTLM)
            .Build();
</code>```

答:
Add this section in appsettings.json

```<code>"App": {
  "CorsOrigins": "http://yourdomain"
}
</code>```

and

```<code>services.AddCors(options => {
  options.AddPolicy(DefaultCorsPolicyName, builder => {

   builder.WithOrigins(
     _appConfiguration["App:CorsOrigins"]
       .Split(",", StringSplitOptions.RemoveEmptyEntries)
       .Select(o => o.RemovePostFix("/"))
       .ToArray()
   ).SetIsOriginAllowedToAllowWildcardSubdomains()
    .AllowAnyHeader()
    .AllowAnyMethod()
    .AllowCredentials();
  });
});
</code>```

Note: App:CorsOrigins in appsettings.json can contain more than one address with splitted by comma.

ContentLicense: CC BY-SA 3.0

Title: CORS in .NET Core

Body:
I am trying to enable CORS in .NET Core in this way:

    public IConfigurationRoot Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddCors(options => options.AddPolicy("AllowAll", p => p.AllowAnyOrigin()
                                                                    .AllowAnyMethod()
                                                                     .AllowAnyHeader()));
        services.AddMvc();
    }

    public void Configure(IApplicationBuilder app)
    {
        app.UseCors("AllowAll");

        app.UseMvc(routes =>
         {
             routes.MapRoute(
                 name: "default",
                 template: "{controller=Home}/{action=Index}/{id?}");
         });

    }
}

However, when I am sending a request to my app with Angular 2 I am getting the famous

"No 'Access-Control-Allow-Origin' header is present on the requested
  resource."

error message.

I am also using Windows Authentication + WebListener.
If I am checking with postman the only response headers are:

Content-Length →3533
  Content-Type →application/json;
  charset=utf-8
  Date →Fri, 14 Oct 2016 12:17:57
  GMT Server →Microsoft-HTTPAPI/2.0

So there must be still something wrong configured. Any proposals?

If I remove the outcommented line it works, but I need Windows Authentication :-(

        var host = new WebHostBuilder()
            .UseWebListener()
            .UseContentRoot(Directory.GetCurrentDirectory())
            .UseIISIntegration()
            .UseStartup<Startup>()
            //.UseWebListener(options => options.Listener.AuthenticationManager.AuthenticationSchemes = AuthenticationSchemes.NTLM)
            .Build();

Body:
Add this section in appsettings.json

"App": {
  "CorsOrigins": "http://yourdomain"
}

and

services.AddCors(options => {
  options.AddPolicy(DefaultCorsPolicyName, builder => {

   builder.WithOrigins(
     _appConfiguration["App:CorsOrigins"]
       .Split(",", StringSplitOptions.RemoveEmptyEntries)
       .Select(o => o.RemovePostFix("/"))
       .ToArray()
   ).SetIsOriginAllowedToAllowWildcardSubdomains()
    .AllowAnyHeader()
    .AllowAnyMethod()
    .AllowCredentials();
  });
});

Note: App:CorsOrigins in appsettings.json can contain more than one address with splitted by comma.


问:
Glassfish Admin Console stopped after change keystore.jks
I use GF 3.1.2.2 and now I need to configure a Lets Encrypt SSL certificate for my webapp. After I changed the default keystore.jks with the new including the Lets Encrypt cert, my webapp worked fine, but Admin Console no.

The server.log file arises this error because it needs the default keytore.jks file:

[#|2016-05-17T11:31:15.344-0400|SEVERE|glassfish3.1.2|org.glassfish.admingui|_ThreadID=72;_ThreadName=Thread-2;|javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target;
javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target;
restRequest: endpoint=https://localhost:4848/management/domain/anonymous-user-enabled
attrs={}
method=GET|#]

答:
I am 3 years late, but who knows maybe someone reads it anyway :)
The reason for your problem is that the certificate the admin-listener uses, is not within your new keystore.

The default certificate the admin-listener (Port 4848) uses has the Alias-Name 's1as' and is provided with the Glassfish installation.
This certificate is within the Default-Keystore keystore.jks.

If you changed the keystore with a new one, then Glassfish can't find the certificate he uses for the admin-listener.

This is most probably the solution to your problem:

Easy one:

Stop glassfish

Go to domain.xml in Path ./glassfish/glassfish/domains/domain1/config and whereever you find an attribute with the name 'cert-nickname' change the value to the Alias-Name of your Let's Encrypt Certificate.

Restart Glassfish

Harder but more sophisticated:

Find out which certificate your admin-listener used before.

For that temporarily change back to your old keystore.jks.

Login into the
Admin console and go look for the Certificate NickName under
/Configurations/server-config/Http-Service/Http-Listeners/admin-listeners.
The default certificate Glassfish uses has the Name s1as.

a) If its a fresh Glassfish installation and the admin-listener still uses the default certificate s1as then i would suggest you switch over to your new Certificate.

Just change the Certificate NickName to the Alias-Name of your Lets' Encrypt certificate and click the save button.

Stop Glassfish

Switch over to your new Keystore

Start Glassfish

b) If you insist on keeping the old certificate then you have to extract it from your 'old' keystore via keytool and import it into your new keystore.

Stop Glassfish

Extract the old certificate with this command:

```<code> keytool -export -alias myOldCertificateNickname -keystore keystore.jks -file myOldCertificate.crt
</code>```

Replace myOldCertificateNickname with the Certificate NickName you found in Step 1!

Import your freshly exported old certificate into your new keystore

```<code>keytool -import -alias myOldCertificateNickname -file myOldCertificate.crt -keystore myNewKeystore.jks
</code>```

Start Glassfish

Now this is most important!!
For all this to work you need to know the password for both keystore's and the certifcates as well! And the MasterPW of Glassfish too!
Because Glassfish insist that all 3 Passwords have to be the same (MasterPW, Keystore Password, Password for the certificate)

And here a really good online guide for Installation of certificate in Glassfish

https://www.ssls.com/knowledgebase/how-to-install-an-ssl-certificate-on-glassfish/

Body:
I am 3 years late, but who knows maybe someone reads it anyway :)
The reason for your problem is that the certificate the admin-listener uses, is not within your new keystore.

The default certificate the admin-listener (Port 4848) uses has the Alias-Name 's1as' and is provided with the Glassfish installation.
This certificate is within the Default-Keystore keystore.jks.

If you changed the keystore with a new one, then Glassfish can't find the certificate he uses for the admin-listener.

This is most probably the solution to your problem:

Easy one:

Stop glassfish

Go to domain.xml in Path ./glassfish/glassfish/domains/domain1/config and whereever you find an attribute with the name 'cert-nickname' change the value to the Alias-Name of your Let's Encrypt Certificate.

Restart Glassfish

Harder but more sophisticated:

Find out which certificate your admin-listener used before.

For that temporarily change back to your old keystore.jks.

Login into the
Admin console and go look for the Certificate NickName under
/Configurations/server-config/Http-Service/Http-Listeners/admin-listeners.
The default certificate Glassfish uses has the Name s1as.

a) If its a fresh Glassfish installation and the admin-listener still uses the default certificate s1as then i would suggest you switch over to your new Certificate.

Just change the Certificate NickName to the Alias-Name of your Lets' Encrypt certificate and click the save button.

Stop Glassfish

Switch over to your new Keystore

Start Glassfish

b) If you insist on keeping the old certificate then you have to extract it from your 'old' keystore via keytool and import it into your new keystore.

Stop Glassfish

Extract the old certificate with this command:

 keytool -export -alias myOldCertificateNickname -keystore keystore.jks -file myOldCertificate.crt

Replace myOldCertificateNickname with the Certificate NickName you found in Step 1!

Import your freshly exported old certificate into your new keystore

keytool -import -alias myOldCertificateNickname -file myOldCertificate.crt -keystore myNewKeystore.jks

Start Glassfish

Now this is most important!!
For all this to work you need to know the password for both keystore's and the certifcates as well! And the MasterPW of Glassfish too!
Because Glassfish insist that all 3 Passwords have to be the same (MasterPW, Keystore Password, Password for the certificate)

And here a really good online guide for Installation of certificate in Glassfish

https://www.ssls.com/knowledgebase/how-to-install-an-ssl-certificate-on-glassfish/


问:
How to compare 2 collections in mongodb and find the missing ids
I have two collections in MongoDb and want to compare those and get the difference documents.

for example Collection A has below 5 documents

```<code>{
    "Number" : "0000A95B"
}
{
    "Number" : "0001385B"
}
{
    "Number" : "0002195B"
}
{
    "Number" : "0002E85B"
}
{
    "Number" : "0002FC5B"
}
</code>```

Collection B has below 3 documents:

```<code>{
    "Number" : "0000A95B"
}
{
    "Number" : "0001385B"
}
{
    "Number" : "0002195B"
}
</code>```

I need a query to get the documents which are present in A but not in B

答:
Could use an aggregation query with a $lookup.

```<code>db.getCollection("collection_a").aggregate([{
$lookup: {
    from: "collection_b",
    localField: "Number",
    foreignField: "Number",
    as: "b_docs"
}
},{
$match: {
    b_docs: {
        $size: 0
    }
}
}])
</code>```

The first $lookup stage should perform a "join" of sorts on collection_a and collection_b wherein the docs with the matching value of number from b will be added in the b_docs property as an array. If no document is found in collection_b, b_docs should be an empty array, so, just add a $match pipeline to filter the results where the size of the b_docs array is 0.

I have not tested the above query, you might want to try it out.

Body:
I have two collections in MongoDb and want to compare those and get the difference documents.

for example Collection A has below 5 documents

{
    "Number" : "0000A95B"
}
{
    "Number" : "0001385B"
}
{
    "Number" : "0002195B"
}
{
    "Number" : "0002E85B"
}
{
    "Number" : "0002FC5B"
}

Collection B has below 3 documents:

{
    "Number" : "0000A95B"
}
{
    "Number" : "0001385B"
}
{
    "Number" : "0002195B"
}

I need a query to get the documents which are present in A but not in B

Body:
Could use an aggregation query with a $lookup.

db.getCollection("collection_a").aggregate([{
$lookup: {
    from: "collection_b",
    localField: "Number",
    foreignField: "Number",
    as: "b_docs"
}
},{
$match: {
    b_docs: {
        $size: 0
    }
}
}])

The first $lookup stage should perform a "join" of sorts on collection_a and collection_b wherein the docs with the matching value of number from b will be added in the b_docs property as an array. If no document is found in collection_b, b_docs should be an empty array, so, just add a $match pipeline to filter the results where the size of the b_docs array is 0.

I have not tested the above query, you might want to try it out.


问:
FluentNhibernate Mapping of lookup table in to properties of Parent Object
Using FluentNhiberante is there a way to map the following:

Parent Table (Employee)

```<code>EmployeeId INT Primary Key
FirstName
LastName
EmployeeTypeId
</code>```

Lookup Table (EmployeeType)

```<code>EmployeeTypeId INT Primary Key
EmployeeTypeDescription
</code>```

My class is defined as:

```<code>public class Employee
{
    int EmployeeId {get; set;}
    ...
    string EmployeeTypeDescription {get; set;}
}
</code>```

Is there a way via the FluentNhibernate mapping to populate the EmployeeTypeDescription property in the Employee object from the EmployeeTypeDescription table by looking up using the EmployeeTypeId column in Employee?

I'm pretty sure the normal and proper way to do this is by using References in the mapping file and then by adding a EmployeeType property to the Employee class and accessing the description using Employee.EmployeeType.EmployeeTypeDescription.  I'm unable to change the code to do that at this time so am wondering how to just set the EmployeeTypeDescription property for now.

答:
it should be possible tweaking the examplecode below:</p>

```<code>public class EmployeeMap : ClassMap<Employee>
{
    public EmployeeMap()
    {
        ...
        Join("EmployeeType", join =>
        {
            join.KeyColumn("EmployeeTypeId");
            join.Map(k => k.TherapieOK, "somecolumn"));
        }
        ...
    }
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Using FluentNhiberante is there a way to map the following:

Parent Table (Employee)

EmployeeId INT Primary Key
FirstName
LastName
EmployeeTypeId

Lookup Table (EmployeeType)

EmployeeTypeId INT Primary Key
EmployeeTypeDescription

My class is defined as:

public class Employee
{
    int EmployeeId {get; set;}
    ...
    string EmployeeTypeDescription {get; set;}
}

Is there a way via the FluentNhibernate mapping to populate the EmployeeTypeDescription property in the Employee object from the EmployeeTypeDescription table by looking up using the EmployeeTypeId column in Employee?

I'm pretty sure the normal and proper way to do this is by using References in the mapping file and then by adding a EmployeeType property to the Employee class and accessing the description using Employee.EmployeeType.EmployeeTypeDescription.  I'm unable to change the code to do that at this time so am wondering how to just set the EmployeeTypeDescription property for now.

Body:
it should be possible tweaking the examplecode below:

public class EmployeeMap : ClassMap<Employee>
{
    public EmployeeMap()
    {
        ...
        Join("EmployeeType", join =>
        {
            join.KeyColumn("EmployeeTypeId");
            join.Map(k => k.TherapieOK, "somecolumn"));
        }
        ...
    }
}


问:
Javascript style.background not allowing me to adjust size of image
I want the background image of the red section to change when the user hovers over the blue section.

I have got this to work fine with the following code

```<code><script>
    document.getElementById('scrolling-background-column-left').onmouseover = function()
     {
      document.getElementById('scrolling-background-section').style.background = "url('https://media.cntraveler.com/photos/5698051378d099fc122487e3/master/w_820,c_limit/Sunset-Beach-Oahu-cr-getty.jpg') no-repeat center";
     };

     document.getElementById('scrolling-background-column-left').onmouseout = function()
     {
      document.getElementById('scrolling-background-section').style.background = "";
     };
</script>
</code>```

However  is the result when i hover over the blue section. Is there a way to make the image span across the entire section/whole width of the page? I have tried adding cover to the code however this doesn't seem to work, if i try changing the size of the image through the code it breaks everything.

答:
cover should work in your case. When you use the background shorthand property, you need to have a / separating the position and size values:

```<code>document.getElementById('scrolling-background-section').style.background = "url('media.cntraveler.com/photos/5698051378d099fc122487e3/master/…) no-repeat center / cover";
</code>```

Body:
I want the background image of the red section to change when the user hovers over the blue section.

I have got this to work fine with the following code

However  is the result when i hover over the blue section. Is there a way to make the image span across the entire section/whole width of the page? I have tried adding cover to the code however this doesn't seem to work, if i try changing the size of the image through the code it breaks everything.

Body:
cover should work in your case. When you use the background shorthand property, you need to have a / separating the position and size values:

document.getElementById('scrolling-background-section').style.background = "url('media.cntraveler.com/photos/5698051378d099fc122487e3/master/…) no-repeat center / cover";


问:
Powershell Where-Object with array of enum
I want the items from Get-NlbClusterNode which contains the state "Converged" (Enum of [Microsoft.NetworkLoadBalancingClusters.PowerShell.NodeStatusCode])

I tried something like that:

```<code>Get-NlbClusterNode | %{ $_.State | ?{$_.ToString() -eq "Converged"} }
</code>```

But this gets me only the matching state.

I tried the contains operator

```<code>Get-NlbClusterNode | ?{ $_.State -ccontains "Converged"}
# or
Get-NlbClusterNode | ?{ $_.State -ccontains [Microsoft.NetworkLoadBalancingClusters.PowerShell.NodeStatusCode]::Converged}
</code>```

But this doesn't work ether.

This is the PowerShell-Object

```<code><Objs Version="1.1.0.1" xmlns="http://schemas.microsoft.com/powershell/2004/04">
  <Obj RefId="0">
    <TN RefId="0">
      <T>System.Collections.Generic.List`1[[Microsoft.NetworkLoadBalancingClusters.PowerShell.Node, Microsoft.NetworkLoadBalancingClusters.PowerShell, Version=6.3.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]]</T>
      <T>System.Object</T>
    </TN>
    <LST>
      <Obj RefId="1">
        <TN RefId="1">
          <T>Microsoft.NetworkLoadBalancingClusters.PowerShell.Node</T>
          <T>System.Object</T>
        </TN>
        <ToString>Server02</ToString>
        <Props>
          <Obj N="Cluster" RefId="2">
            <TN RefId="2">
              <T>Microsoft.NetworkLoadBalancingClusters.PowerShell.Cluster</T>
              <T>System.Object</T>
            </TN>
            <ToString />
            <Props>
              <S N="Name"></S>
              <S N="ClusterIPAddress">192.168.0.20</S>
              <S N="ClusterNetworkMask">255.255.255.0</S>
              <S N="ClusterMacAddress">03-12-c0-a8-56-ac</S>
              <S N="OperationMode">MULTICAST</S>
              <B N="BdaReverseHash">false</B>
              <B N="BdaTeamActive">false</B>
              <Nil N="BdaTeamId" />
              <B N="BdaTeamMaster">false</B>
            </Props>
            <MS>
              <S N="ClusterName"></S>
              <S N="IPAddress">192.168.0.20</S>
            </MS>
          </Obj>
          <S N="Name">Server02</S>
          <S N="InterfaceName">NLB</S>
          <S N="Host">Server02</S>
          <Obj N="State" RefId="3">
            <TN RefId="3">
              <T>Microsoft.NetworkLoadBalancingClusters.PowerShell.NodeStatus</T>
              <T>System.Object</T>
            </TN>
            <ToString>Converged</ToString>
            <Props>
              <S N="NodeStatusCode">Converged</S>
            </Props>
          </Obj>
          <I32 N="HostPriority">4</I32>
          <S N="AdapterGuid">{8FEAE540-F32E-42D0-940B-6E34E5977E77}</S>
          <Obj N="InitialHostState" RefId="4">
            <TN RefId="4">
              <T>Microsoft.NetworkLoadBalancingClusters.PowerShell.NodeInitialHostState</T>
              <T>System.Enum</T>
              <T>System.ValueType</T>
              <T>System.Object</T>
            </TN>
            <ToString>Started</ToString>
            <I32>1</I32>
          </Obj>
          <B N="PersistSuspendOnReboot">false</B>
          <B N="MaskSourceMac">true</B>
          <I32 N="FilterIcmp">0</I32>
          <I32 N="GreDescriptorTimeout">10</I32>
        </Props>
      </Obj>
      <Obj RefId="5">
        <TNRef RefId="1" />
        <ToString>Server01</ToString>
        <Props>
          <Ref N="Cluster" RefId="2" />
          <S N="Name">Server01</S>
          <S N="InterfaceName">NLB</S>
          <S N="Host">Server01</S>
          <Obj N="State" RefId="6">
            <TNRef RefId="3" />
            <ToString>Converged(default)</ToString>
            <Props>
              <S N="NodeStatusCode">Default</S>
            </Props>
          </Obj>
          <I32 N="HostPriority">3</I32>
          <S N="AdapterGuid">{B47F1065-2E61-49A9-BFBB-E172EA9444E6}</S>
          <Obj N="InitialHostState" RefId="7">
            <TNRef RefId="4" />
            <ToString>Started</ToString>
            <I32>1</I32>
          </Obj>
          <B N="PersistSuspendOnReboot">false</B>
          <B N="MaskSourceMac">true</B>
          <I32 N="FilterIcmp">0</I32>
          <I32 N="GreDescriptorTimeout">10</I32>
        </Props>
      </Obj>
    </LST>
  </Obj>
</Objs>
</code>```

Here is the type Microsoft.NetworkLoadBalancingClusters.PowerShell.Node

```<code>   TypeName: Microsoft.NetworkLoadBalancingClusters.PowerShell.Node

Name                   MemberType Definition
----                   ---------- ----------
Equals                 Method     bool Equals(System.Object obj)
GetHashCode            Method     int GetHashCode()
GetType                Method     type GetType()
ToString               Method     string ToString()
AdapterGuid            Property   string AdapterGuid {get;set;}
Cluster                Property   Microsoft.NetworkLoadBalancingClusters.PowerShell.Cluster Cluster {get;set;}
FilterIcmp             Property   int FilterIcmp {get;set;}
GreDescriptorTimeout   Property   int GreDescriptorTimeout {get;set;}
Host                   Property   string Host {get;set;}
HostPriority           Property   int HostPriority {get;set;}
InitialHostState       Property   Microsoft.NetworkLoadBalancingClusters.PowerShell.NodeInitialHostState InitialHost
InterfaceName          Property   string InterfaceName {get;set;}
MaskSourceMac          Property   bool MaskSourceMac {get;set;}
Name                   Property   string Name {get;set;}
PersistSuspendOnReboot Property   bool PersistSuspendOnReboot {get;set;}
State                  Property   Microsoft.NetworkLoadBalancingClusters.PowerShell.NodeStatus State {get;set;}
</code>```

答:
Get-NlbClusterNode | ?{$_.State.NodeStatusCode -eq [Microsoft.NetworkLoadBalancingClusters.PowerShell.NodeStatusCode]::Converged}
```

<p>or</p>

<pre class="lang-bsh prettyprint-override"><code>Get-NlbClusterNode | ?{$_.State.NodeStatusCode -eq "Converged"}
</code>```

Because the State property has another property NodeStatusCode

```<code>PS C:\Windows\system32> Get-NlbClusterNode | %{$_.State | Get-Member}

   TypeName: Microsoft.NetworkLoadBalancingClusters.PowerShell.NodeStatus

Name           MemberType Definition
----           ---------- ----------
Equals         Method     bool Equals(System.Object obj)
GetHashCode    Method     int GetHashCode()
GetType        Method     type GetType()
ToString       Method     string ToString()
NodeStatusCode Property   Microsoft.NetworkLoadBalancingClusters.PowerShell.NodeStatusCode NodeStatusCode {get;set;}
</code>```

Body:
I want the items from Get-NlbClusterNode which contains the state "Converged" (Enum of [Microsoft.NetworkLoadBalancingClusters.PowerShell.NodeStatusCode])

I tried something like that:

Get-NlbClusterNode | %{ $_.State | ?{$_.ToString() -eq "Converged"} }

But this gets me only the matching state.

I tried the contains operator

Get-NlbClusterNode | ?{ $_.State -ccontains "Converged"}
# or
Get-NlbClusterNode | ?{ $_.State -ccontains [Microsoft.NetworkLoadBalancingClusters.PowerShell.NodeStatusCode]::Converged}

But this doesn't work ether.

This is the PowerShell-Object

<Objs Version="1.1.0.1" xmlns="http://schemas.microsoft.com/powershell/2004/04">
  <Obj RefId="0">
    <TN RefId="0">
      <T>System.Collections.Generic.List`1[[Microsoft.NetworkLoadBalancingClusters.PowerShell.Node, Microsoft.NetworkLoadBalancingClusters.PowerShell, Version=6.3.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]]</T>
      <T>System.Object</T>
    </TN>
    <LST>
      <Obj RefId="1">
        <TN RefId="1">
          <T>Microsoft.NetworkLoadBalancingClusters.PowerShell.Node</T>
          <T>System.Object</T>
        </TN>
        <ToString>Server02</ToString>
        <Props>
          <Obj N="Cluster" RefId="2">
            <TN RefId="2">
              <T>Microsoft.NetworkLoadBalancingClusters.PowerShell.Cluster</T>
              <T>System.Object</T>
            </TN>
            <ToString />
            <Props>
              <S N="Name"></S>
              <S N="ClusterIPAddress">192.168.0.20</S>
              <S N="ClusterNetworkMask">255.255.255.0</S>
              <S N="ClusterMacAddress">03-12-c0-a8-56-ac</S>
              <S N="OperationMode">MULTICAST</S>
              false
              false
              <Nil N="BdaTeamId" />
              false
            </Props>
            <MS>
              <S N="ClusterName"></S>
              <S N="IPAddress">192.168.0.20</S>
            </MS>
          </Obj>
          <S N="Name">Server02</S>
          <S N="InterfaceName">NLB</S>
          <S N="Host">Server02</S>
          <Obj N="State" RefId="3">
            <TN RefId="3">
              <T>Microsoft.NetworkLoadBalancingClusters.PowerShell.NodeStatus</T>
              <T>System.Object</T>
            </TN>
            <ToString>Converged</ToString>
            <Props>
              <S N="NodeStatusCode">Converged</S>
            </Props>
          </Obj>
          <I32 N="HostPriority">4</I32>
          <S N="AdapterGuid">{8FEAE540-F32E-42D0-940B-6E34E5977E77}</S>
          <Obj N="InitialHostState" RefId="4">
            <TN RefId="4">
              <T>Microsoft.NetworkLoadBalancingClusters.PowerShell.NodeInitialHostState</T>
              <T>System.Enum</T>
              <T>System.ValueType</T>
              <T>System.Object</T>
            </TN>
            <ToString>Started</ToString>
            <I32>1</I32>
          </Obj>
          false
          true
          <I32 N="FilterIcmp">0</I32>
          <I32 N="GreDescriptorTimeout">10</I32>
        </Props>
      </Obj>
      <Obj RefId="5">
        <TNRef RefId="1" />
        <ToString>Server01</ToString>
        <Props>
          <Ref N="Cluster" RefId="2" />
          <S N="Name">Server01</S>
          <S N="InterfaceName">NLB</S>
          <S N="Host">Server01</S>
          <Obj N="State" RefId="6">
            <TNRef RefId="3" />
            <ToString>Converged(default)</ToString>
            <Props>
              <S N="NodeStatusCode">Default</S>
            </Props>
          </Obj>
          <I32 N="HostPriority">3</I32>
          <S N="AdapterGuid">{B47F1065-2E61-49A9-BFBB-E172EA9444E6}</S>
          <Obj N="InitialHostState" RefId="7">
            <TNRef RefId="4" />
            <ToString>Started</ToString>
            <I32>1</I32>
          </Obj>
          false
          true
          <I32 N="FilterIcmp">0</I32>
          <I32 N="GreDescriptorTimeout">10</I32>
        </Props>
      </Obj>
    </LST>
  </Obj>
</Objs>

Here is the type Microsoft.NetworkLoadBalancingClusters.PowerShell.Node

   TypeName: Microsoft.NetworkLoadBalancingClusters.PowerShell.Node

Name                   MemberType Definition
----                   ---------- ----------
Equals                 Method     bool Equals(System.Object obj)
GetHashCode            Method     int GetHashCode()
GetType                Method     type GetType()
ToString               Method     string ToString()
AdapterGuid            Property   string AdapterGuid {get;set;}
Cluster                Property   Microsoft.NetworkLoadBalancingClusters.PowerShell.Cluster Cluster {get;set;}
FilterIcmp             Property   int FilterIcmp {get;set;}
GreDescriptorTimeout   Property   int GreDescriptorTimeout {get;set;}
Host                   Property   string Host {get;set;}
HostPriority           Property   int HostPriority {get;set;}
InitialHostState       Property   Microsoft.NetworkLoadBalancingClusters.PowerShell.NodeInitialHostState InitialHost
InterfaceName          Property   string InterfaceName {get;set;}
MaskSourceMac          Property   bool MaskSourceMac {get;set;}
Name                   Property   string Name {get;set;}
PersistSuspendOnReboot Property   bool PersistSuspendOnReboot {get;set;}
State                  Property   Microsoft.NetworkLoadBalancingClusters.PowerShell.NodeStatus State {get;set;}

Body:
Get-NlbClusterNode | ?{$_.State.NodeStatusCode -eq [Microsoft.NetworkLoadBalancingClusters.PowerShell.NodeStatusCode]::Converged}

or

Get-NlbClusterNode | ?{$_.State.NodeStatusCode -eq "Converged"}

Because the State property has another property NodeStatusCode

PS C:\Windows\system32> Get-NlbClusterNode | %{$_.State | Get-Member}

   TypeName: Microsoft.NetworkLoadBalancingClusters.PowerShell.NodeStatus

Name           MemberType Definition
----           ---------- ----------
Equals         Method     bool Equals(System.Object obj)
GetHashCode    Method     int GetHashCode()
GetType        Method     type GetType()
ToString       Method     string ToString()
NodeStatusCode Property   Microsoft.NetworkLoadBalancingClusters.PowerShell.NodeStatusCode NodeStatusCode {get;set;}


问:
CSV File Import Strangeness: Only Imports if Resaved in Excel
I am a bit dazzled with what is going on with a csv (.txt) file I am trying to import into MYOB. Using the Drupal CMS, with the views and views bonus modules, I am able to quickly get a feed together that will get the needed fields and drop them into a csv (tab-delimited) txt file.

Here is where the strange issues occurs. If I try to import the file directly into the MYOB program, the records simply are skipped because apparently a field doesn't match the data in the myob file ('tax code when bought field). However, if I open the txt field in Excel, then resave the file (without changing any contents, nothing), and then do the import in Myob, everything works 100%.

I have looked at the source code to check the Content-Type and Content-disposition headers but they are all right.

header('Content-type: text/csv; charset=utf-8');
header('Content-disposition: attachment; filename="[thefilename].txt"');

I've checked to ensure that whitespace and line breaks etc are stripped from the field.

Does anyone have an idea on what may be going wrong here? What I should check for? The workaround works, but just introduces an extra "unnecessary" process.

答: I would suggest that Drupal is using unix style line endings (http://en.wikipedia.org/wiki/Newline), and that opening and saving in Excel changes these to Windows style line endings which is what MYOB uses.</p>


问:
Optimized Joined query for large tables
I have a project to analyze event logs.
The goal is based on a parent table(Table 1) to compare the timestamps on an interval of 30 seconds.

Table1

```<code>id                            command                           datetime
---------------------       -------------------               ----------------------
 1                              cat                            2018-11-03 23:29:31
 2                              nmap                           2018-11-03 23:22:32
 3                              ssh                            2018-11-03 23:22:40
</code>```

Event Log Tables

```<code>    id                              raw                              datetime
---------------                  ------------                  --------------------
     1                              text                         2018-11-03 23:23:10
     2                              text                         2018-11-03 23:23:20
</code>```

So based on table1 datetime i want to output all the event logs that were triggered in a time iterval eg 30 seconds

For now i use this left join statement and it works fine for small size tables (less than 1 MB):

```<code>    SELECT table1.command as Command,table2.raw as Nginx,Table3.raw as Apache
    FROM Table1
    left join Table2
    on Table1.datetime::timestamp>= Table2.datetime::timestamp - interval '30 seconds'
    and Table1.datetime::timestamp<= Table2.datetime::timestamp + interval '30 seconds'
    left join
    Table3  on table1.datetime::timestamp>= Table3.datetime::timestamp - interval '1   seconds'
    and Table1.datetime::timestamp<= Table3.datetime::timestamp + interval '30 seconds'
</code>```

It works fines and gives me the output that i want,the problem is that i have tables with 200K+ rows and the takes a lot of time for the query to be executed,
Is not that is crucial to be really fast but for example if i join 3 tables the (Table1 on the example) and the other 2 table contain 200k+ rows the query time is over 5 hours.

Bellow is an Explain statement to get an idea:

```<code>     Nested Loop Left Join  (cost=0.00..930881273799.88 rows=1202913100267 width=1819)
       Join Filter: ((b1.datetime >= (s1.datetime - '00:00:30'::interval)) AND (b1.datetime <= (s1.datetime + '00:00:30'::interval)))
       ->  Nested Loop Left Join  (cost=0.00..60290628.13 rows=36384533 width=1343)
             Join Filter: ((b1.datetime <= s2.datetime) AND (b1.datetime >= (s2.datetime - '00:00:30'::interval)))
             ->  Seq Scan on bash b1  (cost=0.00..75.13 rows=4013 width=34)
             ->  Materialize  (cost=0.00..28885.00 rows=81600 width=1317)
                   ->  Seq Scan on suricata__alert s2  (cost=0.00..15089.00 rows=81600 width=1317)
       ->  Materialize  (cost=0.00..43131.25 rows=297550 width=492)
             ->  Seq Scan on suricata__http s1  (cost=0.00..22755.50 rows=297550 width=492)
</code>```

Can I optimize the Join Statement? Should I get different approach to the problem (use Views,Indexes?)

答:
An index can only be used if the WHERE condition is of the form

<indexed expression> <operator> <constant>

where <operator> must be in the operator class with which the index was defined, and <constant> doesn't really have to be a constant, but have a fixed value for the duration of the index scan.

So you should rewrite your query to

```<code>SELECT table1.command AS Command,
       table2.raw AS Nginx,
       table3.raw AS Apache
FROM Table1
   LEFT JOIN table2
      ON table2.datetime::timestamp
         BETWEEN table1.datetime::timestamp - interval '30 seconds'
             AND table1.datetime::timestamp + interval '30 seconds'
   LEFT JOIN table3
      ON table3.datetime::timestamp
         BETWEEN table1.datetime::timestamp - interval '30 seconds'
             AND table1.datetime::timestamp + interval '30 seconds';
</code>```

Make sure there are indexes on the datetime column of table2 and table3.

This might still be slow unless you limit the number of rows that you want to retrieve from table1 with a WHERE condition.

Title: Optimized Joined query for large tables

Body:
I have a project to analyze event logs.
The goal is based on a parent table(Table 1) to compare the timestamps on an interval of 30 seconds.

Table1

id                            command                           datetime
---------------------       -------------------               ----------------------
 1                              cat                            2018-11-03 23:29:31
 2                              nmap                           2018-11-03 23:22:32
 3                              ssh                            2018-11-03 23:22:40

Event Log Tables

    id                              raw                              datetime
---------------                  ------------                  --------------------
     1                              text                         2018-11-03 23:23:10
     2                              text                         2018-11-03 23:23:20

So based on table1 datetime i want to output all the event logs that were triggered in a time iterval eg 30 seconds

For now i use this left join statement and it works fine for small size tables (less than 1 MB):

    SELECT table1.command as Command,table2.raw as Nginx,Table3.raw as Apache
    FROM Table1
    left join Table2
    on Table1.datetime::timestamp>= Table2.datetime::timestamp - interval '30 seconds'
    and Table1.datetime::timestamp<= Table2.datetime::timestamp + interval '30 seconds'
    left join
    Table3  on table1.datetime::timestamp>= Table3.datetime::timestamp - interval '1   seconds'
    and Table1.datetime::timestamp<= Table3.datetime::timestamp + interval '30 seconds'

It works fines and gives me the output that i want,the problem is that i have tables with 200K+ rows and the takes a lot of time for the query to be executed,
Is not that is crucial to be really fast but for example if i join 3 tables the (Table1 on the example) and the other 2 table contain 200k+ rows the query time is over 5 hours.

Bellow is an Explain statement to get an idea:

     Nested Loop Left Join  (cost=0.00..930881273799.88 rows=1202913100267 width=1819)
       Join Filter: ((b1.datetime >= (s1.datetime - '00:00:30'::interval)) AND (b1.datetime <= (s1.datetime + '00:00:30'::interval)))
       ->  Nested Loop Left Join  (cost=0.00..60290628.13 rows=36384533 width=1343)
             Join Filter: ((b1.datetime <= s2.datetime) AND (b1.datetime >= (s2.datetime - '00:00:30'::interval)))
             ->  Seq Scan on bash b1  (cost=0.00..75.13 rows=4013 width=34)
             ->  Materialize  (cost=0.00..28885.00 rows=81600 width=1317)
                   ->  Seq Scan on suricata__alert s2  (cost=0.00..15089.00 rows=81600 width=1317)
       ->  Materialize  (cost=0.00..43131.25 rows=297550 width=492)
             ->  Seq Scan on suricata__http s1  (cost=0.00..22755.50 rows=297550 width=492)

Can I optimize the Join Statement? Should I get different approach to the problem (use Views,Indexes?)

Body:
An index can only be used if the WHERE condition is of the form

<indexed expression> <operator> <constant>

where <operator> must be in the operator class with which the index was defined, and <constant> doesn't really have to be a constant, but have a fixed value for the duration of the index scan.

So you should rewrite your query to

SELECT table1.command AS Command,
       table2.raw AS Nginx,
       table3.raw AS Apache
FROM Table1
   LEFT JOIN table2
      ON table2.datetime::timestamp
         BETWEEN table1.datetime::timestamp - interval '30 seconds'
             AND table1.datetime::timestamp + interval '30 seconds'
   LEFT JOIN table3
      ON table3.datetime::timestamp
         BETWEEN table1.datetime::timestamp - interval '30 seconds'
             AND table1.datetime::timestamp + interval '30 seconds';

Make sure there are indexes on the datetime column of table2 and table3.

This might still be slow unless you limit the number of rows that you want to retrieve from table1 with a WHERE condition.


问:
Django users and permissions
I need to develop a scenario of users and groups in my django application there are three groups
   - Admin
   - Manager
   - Employee
Generally admin is available by creating superuser and I need to create the users for different groups
 - Admin can access all the records created by all users

Now my requirement is some users are belongs manager group and some normal users belongs to employee group..

How the associate user belongs to manager group can fetch his own records along with his subordinate user's records from employee group

I'm fully confused to give relation between normal users with an associate user from manager group.

How can I assign some employee users to a manager user?

答:
Just to make sure we are on the same page, you wish to have the following user structure:

An Admin can see EVERYTHING

A Manager can see HIMSELF and all his associated Users

A User can see HIMSELF and that's it

So technically, there's only a relation between Managers and Users

Assuming your Admin is not the same as the native admin role from Django, you could setup the following logic:

Extend the User model with a 1-to-1 relation to your custom model. Let's call it Profile.

One of the field in Profile could be the role which would either be Admin, Manager, or User (might want to create a referantial table and use a foreign key)

Another field could be related_manager which would be a foreign key to the user model. It would be a way to say "that user is my manager"

You would need to add specific control in your model, notably:

related_manager is required (or optional?) if user is "User".

related_manager is forced to None if user is not "User"

related_manager must be a user with 'Manager' role

You'd probably have to setup signals to handle "What happens when a Manager, who had users to manage, becomes a basic User?" Do these users become manager-less? Or maybe you prevent it from happening, and a manager can only be demoted once he has no user attached? It all depends on what you want

Note that this is one of many ways to deal with your situation

Title: Django users and permissions


问:
Printing to Excel File From Java Based on Columns
Apologies in advance for any formatting/other errors, I am still very much a newbie to Java.

I am conducting a gene expression analysis in which I have a program that prints ~ 6 million gene names and their expression values in 23,000 sets of 249 (there are 249 patients total and they each have 23,000 genes/gene expression values). Right now, I have this program looping through all the 249 individual patient files, obtaining the 23,000 gene values, and printing to a text file (with 6 million rows and 2 columns, one column for gene name and one for expression).

However, I would like this program to print to an excel file instead, so that there are 249 rows (for each patient) and 23,000 columns (for each gene). I have been trying for a couple of days to do this (with apache POI) and still am unable to. I found this example code: https://www.scientecheasy.com/2019/01/write-excel-file-in-java.html, which is what I have been trying to modify to fit my program, but nothing seems to be working. I have included my original program (that prints to the text file but also include the POI jars I downloaded). Any help would be MUCH appreciated!

```<code>import java.io.*;
import java.io.FileOutputStream;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class CreateExcel {

   public static final File folder = new File("C:/Users/menon/OneDrive/Documents/R/TARGET");
   private static PrintStream output;
   XSSFWorkbook wb = new XSSFWorkbook();
   XSSFSheet sheet1 = wb.createSheet("values");

   public static void main(String [] args) throws FileNotFoundException {
      output = new PrintStream(new File("final_CSRSEF_data.txt"));
      listFilesForFolder(folder);
   }

   public static double listFilesForFolder(final File folder) throws FileNotFoundException {
      double value = 0.0;
      //contains names of all the 23k genes in order to loop through the 249 files and collect the needed names each time
      File list = new File("C:/Users/menon/OneDrive/Documents/NamesOfGenes.txt");
      Scanner names = new Scanner(list);
      String data;
      while (names.hasNext()) {
         String name = names.next();
         //looping through all separate 249 patient files in folder and searching for gene name
         for (final File fileEntry : folder.listFiles()) {
            Scanner files = new Scanner(fileEntry);
            if (fileEntry.isDirectory()) {
               listFilesForFolder(fileEntry);
            } else {
               while (files.hasNextLine()) {
                  final String lineFromFile = files.nextLine();
                  if(lineFromFile.contains(name)) {
                     //System.out.print(name+ " in file " + fileEntry.getName());
                     String[] thisOne = lineFromFile.split("\\s");
                     String res = thisOne[0];
                     //System.out.println(res);
                     if (res.equals(name)) {
                        print(lineFromFile);
                        print("\n");
                     }
                  }
               }

            }
         }
         print("----------------");
         print("\n");
      }
      return 0.0;
   }

   //print to final_CSRSEF_data.txt
   private static void print(String stat) {
      output.print(stat);
   }
}
</code>```

So basically what I am printing before the "---------------" in each text file should instead be in a separate column (not row) in an excel sheet.

Once again, thank you in advance!

答:
try look at this:

www.pela.it, in my home page there's a link to download "gene expression" tool

i did it in java two years ago and if it is what you are trying to do i'll be happy to help.

It elaborate an xml raw data output from pcr tool and finally print a paginated excel with all elaboration phases. There's a ppt too that explain in detail.

Body:
Apologies in advance for any formatting/other errors, I am still very much a newbie to Java.

I am conducting a gene expression analysis in which I have a program that prints ~ 6 million gene names and their expression values in 23,000 sets of 249 (there are 249 patients total and they each have 23,000 genes/gene expression values). Right now, I have this program looping through all the 249 individual patient files, obtaining the 23,000 gene values, and printing to a text file (with 6 million rows and 2 columns, one column for gene name and one for expression).

However, I would like this program to print to an excel file instead, so that there are 249 rows (for each patient) and 23,000 columns (for each gene). I have been trying for a couple of days to do this (with apache POI) and still am unable to. I found this example code: https://www.scientecheasy.com/2019/01/write-excel-file-in-java.html, which is what I have been trying to modify to fit my program, but nothing seems to be working. I have included my original program (that prints to the text file but also include the POI jars I downloaded). Any help would be MUCH appreciated!

import java.io.*;
import java.io.FileOutputStream;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class CreateExcel {

   public static final File folder = new File("C:/Users/menon/OneDrive/Documents/R/TARGET");
   private static PrintStream output;
   XSSFWorkbook wb = new XSSFWorkbook();
   XSSFSheet sheet1 = wb.createSheet("values");

   public static void main(String [] args) throws FileNotFoundException {
      output = new PrintStream(new File("final_CSRSEF_data.txt"));
      listFilesForFolder(folder);
   }

   public static double listFilesForFolder(final File folder) throws FileNotFoundException {
      double value = 0.0;
      //contains names of all the 23k genes in order to loop through the 249 files and collect the needed names each time
      File list = new File("C:/Users/menon/OneDrive/Documents/NamesOfGenes.txt");
      Scanner names = new Scanner(list);
      String data;
      while (names.hasNext()) {
         String name = names.next();
         //looping through all separate 249 patient files in folder and searching for gene name
         for (final File fileEntry : folder.listFiles()) {
            Scanner files = new Scanner(fileEntry);
            if (fileEntry.isDirectory()) {
               listFilesForFolder(fileEntry);
            } else {
               while (files.hasNextLine()) {
                  final String lineFromFile = files.nextLine();
                  if(lineFromFile.contains(name)) {
                     //System.out.print(name+ " in file " + fileEntry.getName());
                     String[] thisOne = lineFromFile.split("\\s");
                     String res = thisOne[0];
                     //System.out.println(res);
                     if (res.equals(name)) {
                        print(lineFromFile);
                        print("\n");
                     }
                  }
               }

            }
         }
         print("----------------");
         print("\n");
      }
      return 0.0;
   }

   //print to final_CSRSEF_data.txt
   private static void print(String stat) {
      output.print(stat);
   }
}

So basically what I am printing before the "---------------" in each text file should instead be in a separate column (not row) in an excel sheet.

Once again, thank you in advance!


问:
Required request body is missing in Spring when Angular Post call is sent
In my Angular application I'm trying to create a POST request, with a json body, that will be sent to my Spring Restful back-end; I have created a service in Angular to handle the API Post method but when I try to send the request, I obtain this error in my front-end console:

core.js:6014 ERROR HttpErrorResponse {headers: HttpHeaders, status: 0, statusText: "Unknown Error", url: "http://127.0.0.1:8080/center/search_1/page/0", ok: false, …}

and this error in my back-end console:

Required request body is missing: public org.springframework.data.domain.Page

This is the code of my service in Angular:

```<code>import {HttpClient, HttpHeaders, HttpParams} from '@angular/common/http';
import {FirstQuery} from '../../../_responseModels/firstQuery/first-query';
import {tap} from 'rxjs/operators';
import {stringify} from 'querystring';

@Injectable({
  providedIn: 'root'
})
export class ApiCenterSearch1Service {

  apiURL = 'http://127.0.0.1:8080/center/search_1/page/0';

  constructor(private httpClient: HttpClient) {}

  getFirstQuery(body: JSON): any {

    return  this.httpClient.post<FirstQuery[]>(this.apiURL, JSON.stringify(body),
      {
        headers : new HttpHeaders({'Content-Type': 'application/json'})
        // observe: 'response'
      });
  }

}
</code>```

and this is a part of the code of a component that triggers the API call:

```<code>funcThis.apiCenterSearch1Service.getFirstQuery(JSON.parse(jsonRequest)).subscribe(
              res => {
                console.log(res);
              });
</code>```

I've already tested my Spring API through Insomnia (an API tester application) and it works without any problems (and I also checked that the JSON required by the back-end is well formatted so I don't think that the problem is this).

Where am I doing wrong?

答: I have completely fixed this issue adding to my back-end application the @CrossOrigin annotation in all the API entry points in order to enable CORS policy; so it was not a front-end problem</p>

Body:
In my Angular application I'm trying to create a POST request, with a json body, that will be sent to my Spring Restful back-end; I have created a service in Angular to handle the API Post method but when I try to send the request, I obtain this error in my front-end console:

core.js:6014 ERROR HttpErrorResponse {headers: HttpHeaders, status: 0, statusText: "Unknown Error", url: "http://127.0.0.1:8080/center/search_1/page/0", ok: false, …}

and this error in my back-end console:

Required request body is missing: public org.springframework.data.domain.Page

This is the code of my service in Angular:

import {HttpClient, HttpHeaders, HttpParams} from '@angular/common/http';
import {FirstQuery} from '../../../_responseModels/firstQuery/first-query';
import {tap} from 'rxjs/operators';
import {stringify} from 'querystring';

@Injectable({
  providedIn: 'root'
})
export class ApiCenterSearch1Service {

  apiURL = 'http://127.0.0.1:8080/center/search_1/page/0';

  constructor(private httpClient: HttpClient) {}

  getFirstQuery(body: JSON): any {

    return  this.httpClient.post<FirstQuery[]>(this.apiURL, JSON.stringify(body),
      {
        headers : new HttpHeaders({'Content-Type': 'application/json'})
        // observe: 'response'
      });
  }

}

and this is a part of the code of a component that triggers the API call:

funcThis.apiCenterSearch1Service.getFirstQuery(JSON.parse(jsonRequest)).subscribe(
              res => {
                console.log(res);
              });

I've already tested my Spring API through Insomnia (an API tester application) and it works without any problems (and I also checked that the JSON required by the back-end is well formatted so I don't think that the problem is this).

Where am I doing wrong?


问:
What is the problem with my generic protocol in Swift?
Couldn't get my head around how protocol generic types work in Swift. Same solution in Java or Kotlin would work without problems.

```<code>protocol ResultProtocol {
   associatedtype T: ResultTypeProtocol
   var result: T? { get set }
}

protocol ResultTypeProtocol {
   func didGet()
}

protocol InteractorProtocol: ResultProtocol where T == InteractorResultProtocol {
   func someLogicRelatedToInteractor()
}

protocol InteractorResultProtocol: ResultTypeProtocol {
   func interactorResult()
}

class Interactor: InteractorProtocol {
  typealias T = InteractorResultProtocol

  var result: InteractorResultProtocol?

  func someLogicRelatedToInteractor() {}
}
</code>```

I get 2 errors in my code.
First one is when I put where generic constraint on another protocol

Second error is that my Interactor class doesn't conform to the protocol. When I click fix it will add another 'typealias T = type' and want me specify T again.

I want to know if there is another way to achieve this in Swift or how to fix this problem.
Idea behind this is to extend my interactor classes with generic property result which is used as delegate for other layers. Interactor is used via his protocol and it's injected in all other classes.

答:
As @vadian comment says: "The type of the typealias must be a concrete type, not a protocol".
But if you want this class to be used with different InteractorResultProtocol then you can use generic for Interactor class also. And define T later.

```<code>class Interactor<ResultProtocolType: InteractorResultProtocol>: InteractorProtocol {
    typealias T = ResultProtocolType
    var result: ResultProtocolType?
    func someLogicRelatedToInteractor() {}
}
</code>```

Usage:

```<code>struct MyInteractorResultProtocol: InteractorResultProtocol {
    func interactorResult() {}
    func didGet() {}
}
let interactor = Interactor<MyInteractorResultProtocol>()
</code>```

Body:
Couldn't get my head around how protocol generic types work in Swift. Same solution in Java or Kotlin would work without problems.

protocol ResultProtocol {
   associatedtype T: ResultTypeProtocol
   var result: T? { get set }
}

protocol ResultTypeProtocol {
   func didGet()
}

protocol InteractorProtocol: ResultProtocol where T == InteractorResultProtocol {
   func someLogicRelatedToInteractor()
}

protocol InteractorResultProtocol: ResultTypeProtocol {
   func interactorResult()
}

class Interactor: InteractorProtocol {
  typealias T = InteractorResultProtocol

  var result: InteractorResultProtocol?

  func someLogicRelatedToInteractor() {}
}

I get 2 errors in my code.
First one is when I put where generic constraint on another protocol

Second error is that my Interactor class doesn't conform to the protocol. When I click fix it will add another 'typealias T = type' and want me specify T again.

I want to know if there is another way to achieve this in Swift or how to fix this problem.
Idea behind this is to extend my interactor classes with generic property result which is used as delegate for other layers. Interactor is used via his protocol and it's injected in all other classes.

Body:
As @vadian comment says: "The type of the typealias must be a concrete type, not a protocol".
But if you want this class to be used with different InteractorResultProtocol then you can use generic for Interactor class also. And define T later.

class Interactor<ResultProtocolType: InteractorResultProtocol>: InteractorProtocol {
    typealias T = ResultProtocolType
    var result: ResultProtocolType?
    func someLogicRelatedToInteractor() {}
}

Usage:

struct MyInteractorResultProtocol: InteractorResultProtocol {
    func interactorResult() {}
    func didGet() {}
}
let interactor = Interactor<MyInteractorResultProtocol>()


问:
How to create Stream Provider in flutter
I've done many searches and nothing helped to get rid of the error.

here is my code :

main.dart

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return StreamProvider<User>.value(
      value: AuthService().user,
      child: MaterialApp(
        home: Wrapper(),
      ),
    );
  }
}
```

<p>and here is the auth services where I created the stream: </p>

<p><strong>auth.dart</strong></p>

<pre class="lang-dart prettyprint-override"><code>  // Create user object based on fireBase user
  User _userFromFireBaseUser(FirebaseUser user) {
    return user != null ? User(uid: user.uid) : null;
  }

  // Auth change stream
  Stream<User> get user {
    return _auth.onAuthStateChanged
    .map(_userFromFireBaseUser);
  }
</code>```

And finally here is how I add it in my Wrapper:

Wrapper.dart

class Wrapper extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    //final user = Provider.of<User>(context);
    final loggedUser = Provider.of<User>(context);
   print(loggedUser);
    return Authenticate();
  }
}
```

<p>it returns this error :</p>

```Error: Could not find the correct Provider<User> above this Wrapper Widget

To fix, please:

  * Ensure the Provider<User> is an ancestor to this Wrapper Widget
  * Provide types to Provider<User>
  * Provide types to Consumer<User>
  * Provide types to Provider.of<User>()
  * Ensure the correct `context` is being used.
```

答:
You are calling directly Wrapper class.

```<code>runApp(Wrapper());
</code>```

Instead do

```<code>runApp(MyApp());
</code>```

Body:
I've done many searches and nothing helped to get rid of the error.

here is my code :

main.dart

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return StreamProvider<User>.value(
      value: AuthService().user,
      child: MaterialApp(
        home: Wrapper(),
      ),
    );
  }
}

and here is the auth services where I created the stream:

auth.dart

  // Create user object based on fireBase user
  User _userFromFireBaseUser(FirebaseUser user) {
    return user != null ? User(uid: user.uid) : null;
  }

  // Auth change stream
  Stream<User> get user {
    return _auth.onAuthStateChanged
    .map(_userFromFireBaseUser);
  }

And finally here is how I add it in my Wrapper:

Wrapper.dart

class Wrapper extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    //final user = Provider.of<User>(context);
    final loggedUser = Provider.of<User>(context);
   print(loggedUser);
    return Authenticate();
  }
}

it returns this error :

Error: Could not find the correct Provider<User> above this Wrapper Widget

To fix, please:

  * Ensure the Provider<User> is an ancestor to this Wrapper Widget
  * Provide types to Provider<User>
  * Provide types to Consumer<User>
  * Provide types to Provider.of<User>()
  * Ensure the correct `context` is being used.

Body:
You are calling directly Wrapper class.

runApp(Wrapper());

Instead do

runApp(MyApp());


问:
Is it possible to load new Javascript files with AJAX?
I'm building a new AJAX powered website with distinct sections.  Each section requires a new set of Javascript functions to run.  I'd rather not load every script at the start, as there might be quite a few.

Is there a way to load new scripts using AJAX and remove old ones (so as to make sure there are no compatibility issues with similar variable names or function signatures).

Thanks

Edit - JQuery is fine, it doesn't have to be old school Javascript

答:
For loading new scripts you should check out LABjs

Unloading them is however not possible, see another StackOverflow post on this issue.


问:
Angular 8: unable to send Authorization with service
I want to send the following "Authorization" through service.

```<code>Authorization :: Basic c3ByaW5nLXNlY3VyaXR5LW9hdXRoMi1yZWFkLXdyaXRlLWNsaWVudDpzcHJpbmctc2VjdXJpdHktb2F1dGgyLXJlYWQtd3JpdGUtY2xpZW50LXBhc3N3b3JkMTIzNA==
</code>```

In the service I wrote the following code:

```<code>constructor(
        private http: HttpClient
    ) {
        this.header_auth = {
          headers: new HttpHeaders()
            .set('Authorization',  "Basic c3ByaW5nLXNlY3VyaXR5LW9hdXRoMi1yZWFkLXdyaXRlLWNsaWVudDpzcHJpbmctc2VjdXJpdHktb2F1dGgyLXJlYWQtd3JpdGUtY2xpZW50LXBhc3N3b3JkMTIzNA==")
        }
    }

getToken() {
        return this.http.post(this.rootUrl + "oauth/token?client_id=spring-security-oauth2-read-write-client&password=XXXXX&username=XX@XXX.com&grant_type=password", this.header_auth);
    }
</code>```

I also used this code:
 public basic: any = 'Basic c3ByaW5nLXNlY3VyaXR5LW9hdXRoMi1yZWFkLXdyaXRlLWNsaWVudDpzcHJpbmctc2VjdXJpdHktb2F1dGgyLXJlYWQtd3JpdGUtY2xpZW50LXBhc3N3b3JkMTIzNA==';

```<code>getToken() {

        const request = {
             headers: {
               'Authorization': this.basic,
             }
        };

        return this.http.post<any>(
            this.rootUrl + "oauth/token?client_id=spring-security-oauth2-read-write-client&password=XXXXX&username=XX@XXX.com&grant_type=password",
            { headers: request.headers }
        );
}
</code>```

When I called the service in my component, it shows me "error: "Unauthorized" But the same API URL is working well in "Postman".

xxx.component.ts:

```<code>this.commService.getToken().subscribe((data: any) => {
  console.log(data);
});
</code>```

In console I see the following error:

POST http://10.X.X.XXX:8089/XXXX/oauth/token?client_id=spring-security-oauth2-read-write-client&password=XXX&username=XX@XXX.com&grant_type=password 401

See postman screen:

答:
Try this;

```<code>getToken() {
    return this.hc.post(`${this.rootUrl}oauth/token`, {}, {
      params: new HttpParams()
        .append('client_id', 'spring-security-oauth2-read-write-client')
        .append('password', 'XXXXX')
        .append('username', 'XX@XXX.com')
        .append('grant_type', 'password'),
      headers: new HttpHeaders()
        .set('Authorization', 'Basic c3ByaW5nLXNlY3VyaXR5LW9hdXRoMi1yZWFkLXdyaXRlLWNsaWVudDpzcHJpbmctc2VjdXJpdHktb2F1dGgyLXJlYWQtd3JpdGUtY2xpZW50LXBhc3N3b3JkMTIzNA=='),
    });
  }
</code>```

You can try with HttpParams instead of manually query string.
And also check this guide

Body:
I want to send the following "Authorization" through service.

Authorization :: Basic c3ByaW5nLXNlY3VyaXR5LW9hdXRoMi1yZWFkLXdyaXRlLWNsaWVudDpzcHJpbmctc2VjdXJpdHktb2F1dGgyLXJlYWQtd3JpdGUtY2xpZW50LXBhc3N3b3JkMTIzNA==

In the service I wrote the following code:

constructor(
        private http: HttpClient
    ) {
        this.header_auth = {
          headers: new HttpHeaders()
            .set('Authorization',  "Basic c3ByaW5nLXNlY3VyaXR5LW9hdXRoMi1yZWFkLXdyaXRlLWNsaWVudDpzcHJpbmctc2VjdXJpdHktb2F1dGgyLXJlYWQtd3JpdGUtY2xpZW50LXBhc3N3b3JkMTIzNA==")
        }
    }

getToken() {
        return this.http.post(this.rootUrl + "oauth/token?client_id=spring-security-oauth2-read-write-client&password=XXXXX&username=XX@XXX.com&grant_type=password", this.header_auth);
    }

I also used this code:
 public basic: any = 'Basic c3ByaW5nLXNlY3VyaXR5LW9hdXRoMi1yZWFkLXdyaXRlLWNsaWVudDpzcHJpbmctc2VjdXJpdHktb2F1dGgyLXJlYWQtd3JpdGUtY2xpZW50LXBhc3N3b3JkMTIzNA==';

getToken() {

        const request = {
             headers: {
               'Authorization': this.basic,
             }
        };

        return this.http.post<any>(
            this.rootUrl + "oauth/token?client_id=spring-security-oauth2-read-write-client&password=XXXXX&username=XX@XXX.com&grant_type=password",
            { headers: request.headers }
        );
}

When I called the service in my component, it shows me "error: "Unauthorized" But the same API URL is working well in "Postman".

xxx.component.ts:

this.commService.getToken().subscribe((data: any) => {
  console.log(data);
});

In console I see the following error:

POST http://10.X.X.XXX:8089/XXXX/oauth/token?client_id=spring-security-oauth2-read-write-client&password=XXX&username=XX@XXX.com&grant_type=password 401

See postman screen:

Body:
Try this;

getToken() {
    return this.hc.post(`${this.rootUrl}oauth/token`, {}, {
      params: new HttpParams()
        .append('client_id', 'spring-security-oauth2-read-write-client')
        .append('password', 'XXXXX')
        .append('username', 'XX@XXX.com')
        .append('grant_type', 'password'),
      headers: new HttpHeaders()
        .set('Authorization', 'Basic c3ByaW5nLXNlY3VyaXR5LW9hdXRoMi1yZWFkLXdyaXRlLWNsaWVudDpzcHJpbmctc2VjdXJpdHktb2F1dGgyLXJlYWQtd3JpdGUtY2xpZW50LXBhc3N3b3JkMTIzNA=='),
    });
  }

You can try with HttpParams instead of manually query string.
And also check this guide


答:
This is the right way to set headers. It is important to set the Content-Type

```<code>this.header_auth = {headers: new HttpHeaders({
   'Content-Type': 'application/json; charset=utf-8',
    Authorization: 'Basic c3ByaW5nLXNlY3VyaXR5LW9hdXRoMi1yZWFkLXdyaXRlLWNsaWVudDpzcHJpbmctc2VjdXJpdHktb2F1dGgyLXJlYWQtd3JpdGUtY2xpZW50LXBhc3N3b3JkMTIzNA=='
})};
</code>```

Title: Angular 8: unable to send Authorization with service

Body:
This is the right way to set headers. It is important to set the Content-Type

this.header_auth = {headers: new HttpHeaders({
   'Content-Type': 'application/json; charset=utf-8',
    Authorization: 'Basic c3ByaW5nLXNlY3VyaXR5LW9hdXRoMi1yZWFkLXdyaXRlLWNsaWVudDpzcHJpbmctc2VjdXJpdHktb2F1dGgyLXJlYWQtd3JpdGUtY2xpZW50LXBhc3N3b3JkMTIzNA=='
})};


问:
How to process an array one by one in javascript?
I have an array of values in a stream and you wish to pipe it such that it will emit the arrays values individually, one by one and wait for them all to be completed before processing another array</p>

```<code>// This is the array:
let arr = [[1,2,3], [4,5,6]];

let data = arr.filter( (value) => {
  let newdata = value.filter((newVal, index) => {
    if (newVal !== value[index]) {
      return '' ;
    }
  });
});

console.log(data);
// Output: []
// Expected output: [[], []]
</code>```

答:
At root use Map instead of filter:</p>

```<code>  let arr = [[1,2,3], [4,5,6]];

  let data = arr.map( (value) => {
    let newdata = value.filter((newVal, index) => {
      if (newVal !== value[index]) {
       return '' ;
      }
    });
    return newdata;
  });

  console.log(data);
</code>```

Body:
I have an array of values in a stream and you wish to pipe it such that it will emit the arrays values individually, one by one and wait for them all to be completed before processing another array

// This is the array:
let arr = [[1,2,3], [4,5,6]];

let data = arr.filter( (value) => {
  let newdata = value.filter((newVal, index) => {
    if (newVal !== value[index]) {
      return '' ;
    }
  });
});

console.log(data);
// Output: []
// Expected output: [[], []]

Body:
At root use Map instead of filter:

  let arr = [[1,2,3], [4,5,6]];

  let data = arr.map( (value) => {
    let newdata = value.filter((newVal, index) => {
      if (newVal !== value[index]) {
       return '' ;
      }
    });
    return newdata;
  });

  console.log(data);


问:
How to parse the JSON and get the data row by row?
I would like to ask how do I get the data using the JSON. I am using the Web API and deploy using request and response.

Class1.cs

This is calling the web API by using the request and response.

```<code>public static string Test()

{

    string strReq = "{ \"header\": { \"Token\": \"ba42d11f - e0ae - 4d6c - 800a - 1564485b7ccb\"},\"body\": { \"SOHeaders\": [{ \"WarehouseCode\": \"W001\", \"CompanyCode\": \"C001\", \"SONo\": \"SO001\"}]}}";
    UploadToBCSSoftSCM a = new UploadToBCSSoftSCM();
    string strRes = a.GetSOSts(strReq);

    return strRes;
}
</code>```

HomeController.cs

I can get the response from here but I don't know how to split or parse the data.

```<code>public ActionResult Index()
{
    // ViewBag.Title = "Home Page";

    string r = Class1.Test();
    Debug.WriteLine(r);

    return View();
}
</code>```

The result of response is

```<code>{
    "header": {
        "Token": "7c6cbeba-ff57-40d2-8759-84ccb59235fd",
        "DtTime": "2020-02-20 13:10:34.365",
        "ResultCode": "S",
        "ResultMsg": ""
    },
    "body": [
        {
            "WarehouseCode": "W001",
            "CompanyCode": "C001",
            "SONo": "SO001",
            "SOSts": "New"
        }
    ]
}
</code>```

答:
O site json2csharp.com you can generate classes necessary to deserialize JSON.

```<code>public class Header
{
    public string Token { get; set; }
    public string DtTime { get; set; }
    public string ResultCode { get; set; }
    public string ResultMsg { get; set; }
}

public class Body
{
    public string WarehouseCode { get; set; }
    public string CompanyCode { get; set; }
    public string SONo { get; set; }
    public string SOSts { get; set; }
}

public class RootObject
{
    public Header header { get; set; }
    public List<Body> body { get; set; }
}
</code>```

Then using JSON.NET you can deserialize your response into objects.

```<code>var data = JsonConvert.DeserializeObject<RootObject>(json);
</code>```

and then in loop you can reach all records

```<code>foreach(var d in data.body)
{
}
</code>```

Body:
I would like to ask how do I get the data using the JSON. I am using the Web API and deploy using request and response.

Class1.cs

This is calling the web API by using the request and response.

public static string Test()

{

    string strReq = "{ \"header\": { \"Token\": \"ba42d11f - e0ae - 4d6c - 800a - 1564485b7ccb\"},\"body\": { \"SOHeaders\": [{ \"WarehouseCode\": \"W001\", \"CompanyCode\": \"C001\", \"SONo\": \"SO001\"}]}}";
    UploadToBCSSoftSCM a = new UploadToBCSSoftSCM();
    string strRes = a.GetSOSts(strReq);

    return strRes;
}

HomeController.cs

I can get the response from here but I don't know how to split or parse the data.

public ActionResult Index()
{
    // ViewBag.Title = "Home Page";

    string r = Class1.Test();
    Debug.WriteLine(r);

    return View();
}

The result of response is

{
    "header": {
        "Token": "7c6cbeba-ff57-40d2-8759-84ccb59235fd",
        "DtTime": "2020-02-20 13:10:34.365",
        "ResultCode": "S",
        "ResultMsg": ""
    },
    "body": [
        {
            "WarehouseCode": "W001",
            "CompanyCode": "C001",
            "SONo": "SO001",
            "SOSts": "New"
        }
    ]
}

Body:
O site json2csharp.com you can generate classes necessary to deserialize JSON.

public class Header
{
    public string Token { get; set; }
    public string DtTime { get; set; }
    public string ResultCode { get; set; }
    public string ResultMsg { get; set; }
}

public class Body
{
    public string WarehouseCode { get; set; }
    public string CompanyCode { get; set; }
    public string SONo { get; set; }
    public string SOSts { get; set; }
}

public class RootObject
{
    public Header header { get; set; }
    public List<Body> body { get; set; }
}

Then using JSON.NET you can deserialize your response into objects.

var data = JsonConvert.DeserializeObject<RootObject>(json);

and then in loop you can reach all records

foreach(var d in data.body)
{
}