问:
Error: NED type 'myApp' could not be fully resolved due to a missing base type or interface?
In my project,
I implement a new class called myApp which inherits from ApplicationBase and UdpSocket classes. When I build my project I get no error, but when I debug C/C++ application with the IDE, it displays the first error in errors section. And the command line display the second error when I run make :

Code of myApp.ned, myApp.h and myApp.cc in what follows :

I did include inet library in project references, and I tried the solution posted in The following NED types could not be fully resolved, due to a missing base type or interface.

```<code>import inet.applications.contract.IApp;

simple myApp like IApp
{
    parameters:
        int localPort = default(-1);  // local UDP port number (-1: use ephemeral port)
        int destPort; // remote UDP port number
        string packetName = default("myApp");
        string interfaceTableModule;   // The path to the InterfaceTable module
        double helloInterval @unit(s) = default(5s);  // how often hello messages should be sent out
        volatile double sendInterval @unit(s); // should usually be a random value, e.g. exponential(1)
        double startTime @unit(s) = default(this.sendInterval); // application start time (start of the first packet)
        double stopTime @unit(s) = default(-1s);  // time of finishing sending, -1s means forever
        double maxVariance = default(1); // This is the maximum of a random value to determine when the first hello message will be sent out
        volatile double broadcastDelay @unit(s) = default(uniform(0s,0.01s));
        int timeToLive = default(-1); // if not -1, set the TTL (IPv4) or Hop Limit (IPv6) field of sent packets to this value
        bool dontFragment = default(false); // if true, asks IP to not fragment the message during routing
        int typeOfService = default(-1); // if not -1, set the ToS (IPv4) or Traffic Class (IPv6) field of sent packets to this value
        string multicastInterface = default("");  // if not empty, set the multicast output interface option on the socket (interface name expected)
        bool receiveBroadcast = default(false); // if true, makes the socket receive broadcast packets
        bool joinLocalMulticastGroups = default(false); // if true, makes the socket receive packets from all multicast groups set on local interfaces
        @class(myApp);
    gates:
        input socketIn @labels(UdpControlInfo/up);
        output socketOut @labels(UdpControlInfo/down);
}

#ifndef MYAPP_H_
#define MYAPP_H_

#include "inet/common/INETDefs.h"

#include "inet/applications/base/ApplicationBase.h"
#include "inet/transportlayer/contract/udp/UdpSocket.h"
#include "inet/transportlayer/contract/udp/UdpControlInfo_m.h"
#include "inet/common/ModuleAccess.h"
#include "inet/common/TimeTag_m.h"
#include "inet/common/packet/Packet.h"
#include "inet/common/lifecycle/ModuleOperations.h"
#include "inet/common/IProtocolRegistrationListener.h"
#include "inet/common/ProtocolTag_m.h"
#include "inet/linklayer/common/InterfaceTag_m.h"
#include "inet/networklayer/contract/IInterfaceTable.h"
#include "inet/networklayer/contract/ipv4/Ipv4Address.h"
#include "inet/networklayer/ipv4/IIpv4RoutingTable.h"
#include "inet/networklayer/ipv4/Ipv4Header_m.h"
#include "inet/networklayer/ipv4/Ipv4InterfaceData.h"
#include "inet/networklayer/common/FragmentationTag_m.h"
#include "inet/networklayer/common/L3AddressResolver.h"

#include "HelloMsg_m.h"
#include "XedMsg_m.h"

#include <omnetpp.h>
#include <vector>
#include <random>
#include <algorithm>

using namespace omnetpp;
using namespace inet;
using namespace std;

class myApp : public ApplicationBase, public UdpSocket::ICallback
{
    protected:
        //enum SelfMsgKinds { START = 1, SEND, STOP };
        int localPort = -1, destPort = -1;
        bool dontFragment = false;
        const char *packetName = nullptr;

        simtime_t startTime;
        simtime_t stopTime;

        // state
        UdpSocket socket;
        cMessage *selfMsg = nullptr;
        cModule *host = nullptr;
        cMessage *event = nullptr;
        cPar *broadcastDelay = nullptr;
        unsigned int sequencenumber = 0;
        simtime_t helloInterval;
        IInterfaceTable *ift = nullptr;
        InterfaceEntry *interface80211ptr = nullptr;
        int interfaceId = -1;
        list<L3Address> neighbors;
        Ipv4Address source;

        /********** XED **********/
        class XED
        {
          public:
            L3Address originatorAddr, destinationAddr;
            unsigned int random;
            XED(const L3Address& originatorAddr, const L3Address& destinationAddr, unsigned int random)
            : originatorAddr(originatorAddr), destinationAddr(destinationAddr), random(random) {};
            bool operator==(const XED& other) const
            {
                return this->originatorAddr == other.originatorAddr && this->destinationAddr == other.destinationAddr
                        && this->random == other.random;
            }
        };

        list<XED> lr,ls;

        /********** MTLSD **********/
        class MTLSD
        {
          public:
            L3Address originatorAddr, destinationAddr;
            char *position;
            simtime_t time;
            MTLSD(const L3Address& originatorAddr, const L3Address& destinationAddr, char *position, simtime_t time)
            : originatorAddr(originatorAddr), destinationAddr(destinationAddr), position(position), time(time) {};
            bool operator==(const MTLSD& other) const
            {
                return this->originatorAddr == other.originatorAddr && this->destinationAddr == other.destinationAddr
                        && this->position == other.position && this->time == time;
            }
        };

    protected:
        virtual int numInitStages() const override { return NUM_INIT_STAGES; }
        virtual void initialize(int stage) override;
        virtual void handleMessageWhenUp(cMessage *msg) override;

        void handleSelfMessage(cMessage *msg);

        /*virtual void processStart();
        virtual void processSend();
        virtual void processStop();*/

        // lifecycle
        virtual void handleStartOperation(LifecycleOperation *operation) override { start(); }
        virtual void handleStopOperation(LifecycleOperation *operation) override { stop(); }
        virtual void handleCrashOperation(LifecycleOperation *operation) override  { stop(); }
        void start();
        void stop();

        virtual void socketDataArrived(UdpSocket *socket, Packet *packet) override;
        virtual void socketErrorArrived(UdpSocket *socket, Indication *indication) override;
        virtual void socketClosed(UdpSocket *socket) override;

        //virtual void generateMTLSDPacket();
        //virtual Packet *generateXEDPacket();
        virtual double generateRandom();

    public:
       myApp() {}
       ~myApp();
};

#endif /* MYAPP_H_ */

#include "myApp.h"
#include "inet/applications/base/ApplicationPacket_m.h"
#include "inet/applications/udpapp/UdpBasicApp.h"
#include "inet/common/TagBase_m.h"
#include "inet/networklayer/common/L3AddressTag_m.h"
#include <iterator>

using namespace std;
Define_Module(myApp);

myApp::~myApp()
{
    EV << "App destructor" << endl;
    cancelAndDelete(selfMsg);
}

void myApp::initialize(int stage)
{
    ApplicationBase::initialize(stage);

    if (stage == INITSTAGE_LOCAL)
    {
        sequencenumber = 0;
        ift = getModuleFromPar<IInterfaceTable>(par("interfaceTableModule"), this);
        event = new cMessage("event");
        broadcastDelay = &par("broadcastDelay");
        helloInterval = par("helloInterval");
        localPort = par("localPort");
        destPort = par("destPort");
        packetName = par("packetName");
        startTime = par("startTime");
        stopTime = par("stopTime");

    }
    else if (stage == INITSTAGE_ROUTING_PROTOCOLS)
    {
        registerService(Protocol::manet, nullptr, gate("socketIn"));
        registerProtocol(Protocol::manet, gate("socketOut"), nullptr);
    }
}

void myApp::handleSelfMessage(cMessage *msg)
{
    if (msg == event)
    {
        auto hello = makeShared<HelloMsg>();
        Ipv4Address source = (interface80211ptr->getProtocolData<Ipv4InterfaceData>()->getIPAddress());
        hello->setChunkLength(b(128));
        hello->setSrcAddress(source);
        sequencenumber += 2;
        hello->setSequencenumber(sequencenumber);
        hello->setNextAddress(source);
        hello->setHopdistance(1);
        auto packet = new Packet("Hello", hello);
        packet->addTagIfAbsent<L3AddressReq>()->setDestAddress(Ipv4Address(255, 255, 255, 255));
        packet->addTagIfAbsent<L3AddressReq>()->setSrcAddress(source);
        packet->addTagIfAbsent<InterfaceReq>()->setInterfaceId(interface80211ptr->getInterfaceId());
        packet->addTagIfAbsent<PacketProtocolTag>()->setProtocol(&Protocol::manet);
        packet->addTagIfAbsent<DispatchProtocolReq>()->setProtocol(&Protocol::ipv4);

        send(packet, "socketOut");
        packet = nullptr;
        hello = nullptr;

        scheduleAt(simTime()+helloInterval+broadcastDelay->doubleValue(), event);
    }
}

void myApp::handleMessageWhenUp(cMessage *msg)
{
    if (msg->isSelfMessage())
    {
        handleSelfMessage(msg);
    }
    else if (check_and_cast<Packet *>(msg)->getTag<PacketProtocolTag>()->getProtocol() == &Protocol::manet)
    {
        auto recHello = staticPtrCast<HelloMsg>(check_and_cast<Packet *>(msg)->peekData<HelloMsg>()->dupShared());
        if (msg->arrivedOn("socketIn"))
        {
            bubble("Received hello message");
            Ipv4Address source = interface80211ptr->getProtocolData<Ipv4InterfaceData>()->getIPAddress();
            Ipv4Address src;
            unsigned int msgsequencenumber;
            int numHops;
            Ipv4Address next;

            src = recHello->getSrcAddress();
            msgsequencenumber = recHello->getSequencenumber();
            next = recHello->getNextAddress();
            numHops = recHello->getHopdistance();

            if (src == source)
            {
                EV_INFO << "Hello msg dropped. This message returned to the original creator.\n";
                delete msg;
                return;
            }
            else
            {
                neighbors.push_back(src);
                /*list<XED>::iterator findIter = find(ls.begin()->destinationAddr, ls.end()->destinationAddr, src);
                if (findIter != ls.end()->destinationAddr)
                {

                }*/
                source = (interface80211ptr->getProtocolData<Ipv4InterfaceData>()->getIPAddress());
                //socket.bind(source, localPort);
                auto xed = makeShared<XedMsg>();
                xed->setChunkLength(b(128)); ///size of XED message in bits
                xed->setSrcAddress(source);
                xed->setDstAddress(src);
                double random = generateRandom();
                xed->setRandom(random);
                //XED item = XED(source, src, random);
                //ls.push_back(item);
                auto packet = new Packet("XED", xed);
                packet->addTagIfAbsent<L3AddressReq>()->setDestAddress(src);
                packet->addTagIfAbsent<L3AddressReq>()->setSrcAddress(source);
                packet->addTagIfAbsent<InterfaceReq>()->setInterfaceId(interfaceId);
                packet->addTagIfAbsent<PacketProtocolTag>()->setProtocol(&Protocol::ipv4);
                packet->addTagIfAbsent<DispatchProtocolReq>()->setProtocol(&Protocol::ipv4);

                socket.setOutputGate(gate("socketOut"));
                socket.setCallback(this);
                socket.bind(source, localPort);
                //emit(packetSentSignal, packet);
                socket.sendTo(packet, src, destPort);

                //send(packet, "socketOut");
                packet = nullptr;
                xed = nullptr;

                /*Ipv4Address source = (interface80211ptr->getProtocolData<Ipv4InterfaceData>()->getIPAddress());
                EV << "I am node " << source << ", my neighbors are : " << endl;
                list<L3Address>::iterator it;
                for (it = neighbors.begin(); it != neighbors.end(); ++it)
                {
                    EV << it. << endl;
                }
                for (auto const& i : neighbors)
                {
                    EV << i.str() << endl;
                }*/
                EV << "I am your neighbor " << src.str();
            }
            delete msg;
        }
        else if (check_and_cast<Packet *>(msg)->getTag<PacketProtocolTag>()->getProtocol() == &Protocol::ipv4)
        {
            EV << "Xed message received" << endl;
            //auto recXed = staticPtrCast<XedMsg>(check_and_cast<Packet *>(msg)->peekData<XedMsg>()->dupShared());
        }
        else
            throw cRuntimeError("Message arrived on unknown gate %s", msg->getArrivalGate()->getName());
    }
}

void myApp::start()
{
    /*socket.setOutputGate(gate("socketOut"));
    socket.setCallback(this);*/
    int  num_80211 = 0;
    InterfaceEntry *ie;
    InterfaceEntry *i_face;
    const char *name;
    for (int i = 0; i < ift->getNumInterfaces(); i++)
    {
        ie = ift->getInterface(i);
        name = ie->getInterfaceName();
        if (strstr(name, "wlan") != nullptr)
        {
            i_face = ie;
            num_80211++;
            interfaceId = i;
        }
    }

    if (num_80211 == 1)
    {
        interface80211ptr = i_face;
        interfaceId = interface80211ptr->getInterfaceId();
    }
    else
        throw cRuntimeError("Node has found %i 80211 interfaces", num_80211);

    scheduleAt(simTime() + uniform(0.0, par("maxVariance").doubleValue()), event);
}

double myApp::generateRandom()
{
    double lower_bound = 10000;
    double upper_bound = 100000;
    uniform_real_distribution<double> unif(lower_bound,upper_bound);
    default_random_engine re;
    double a_random_double = unif(re);
    return a_random_double;
}

void myApp::stop()
{
    cancelEvent(event);
    socket.close();
    delayActiveOperationFinish(par("stopOperationTimeout"));
}

void myApp::socketDataArrived(UdpSocket *socket, Packet *packet)
{
    emit(packetReceivedSignal, packet);
    EV_INFO << "Received packet: " << UdpSocket::getReceivedPacketInfo(packet) << endl;
}

void myApp::socketErrorArrived(UdpSocket *socket, Indication *indication)
{
    EV_WARN << "Ignoring UDP error report " << indication->getName() << endl;
    delete indication;
}

void myApp::socketClosed(UdpSocket *socket)
{
    if (operationalState == State::STOPPING_OPERATION)
            startActiveOperationExtraTimeOrFinish(par("stopOperationExtraTime"));
}

Error: NED type 'myApp' could not be fully resolved due to a missing base type or interface, at /home/bocuhra/Downloads/omnetpp-5.4.1/samples/SaaS/myApp.ned:18

myApp.cc
HelloMsg_m.cc
XedMsg_m.cc
Creating executable: out/gcc-release//SaaS
/usr/bin/ld: cannot find -lINET
collect2: error: ld returned 1 exit status
Makefile:104: recipe for target 'out/gcc-release//SaaS' failed
make: *** [out/gcc-release//SaaS] Error 1
</code>```

答:
I did solve the problem by adding all ned files in my .ini file.
ned-path = .;../inet/src/inet </p>

Body:
In my project,
I implement a new class called myApp which inherits from ApplicationBase and UdpSocket classes. When I build my project I get no error, but when I debug C/C++ application with the IDE, it displays the first error in errors section. And the command line display the second error when I run make :

Code of myApp.ned, myApp.h and myApp.cc in what follows :

I did include inet library in project references, and I tried the solution posted in The following NED types could not be fully resolved, due to a missing base type or interface.

import inet.applications.contract.IApp;

simple myApp like IApp
{
    parameters:
        int localPort = default(-1);  // local UDP port number (-1: use ephemeral port)
        int destPort; // remote UDP port number
        string packetName = default("myApp");
        string interfaceTableModule;   // The path to the InterfaceTable module
        double helloInterval @unit(s) = default(5s);  // how often hello messages should be sent out
        volatile double sendInterval @unit(s); // should usually be a random value, e.g. exponential(1)
        double startTime @unit(s) = default(this.sendInterval); // application start time (start of the first packet)
        double stopTime @unit(s) = default(-1s);  // time of finishing sending, -1s means forever
        double maxVariance = default(1); // This is the maximum of a random value to determine when the first hello message will be sent out
        volatile double broadcastDelay @unit(s) = default(uniform(0s,0.01s));
        int timeToLive = default(-1); // if not -1, set the TTL (IPv4) or Hop Limit (IPv6) field of sent packets to this value
        bool dontFragment = default(false); // if true, asks IP to not fragment the message during routing
        int typeOfService = default(-1); // if not -1, set the ToS (IPv4) or Traffic Class (IPv6) field of sent packets to this value
        string multicastInterface = default("");  // if not empty, set the multicast output interface option on the socket (interface name expected)
        bool receiveBroadcast = default(false); // if true, makes the socket receive broadcast packets
        bool joinLocalMulticastGroups = default(false); // if true, makes the socket receive packets from all multicast groups set on local interfaces
        @class(myApp);
    gates:
        input socketIn @labels(UdpControlInfo/up);
        output socketOut @labels(UdpControlInfo/down);
}

#ifndef MYAPP_H_
#define MYAPP_H_

#include "inet/common/INETDefs.h"

#include "inet/applications/base/ApplicationBase.h"
#include "inet/transportlayer/contract/udp/UdpSocket.h"
#include "inet/transportlayer/contract/udp/UdpControlInfo_m.h"
#include "inet/common/ModuleAccess.h"
#include "inet/common/TimeTag_m.h"
#include "inet/common/packet/Packet.h"
#include "inet/common/lifecycle/ModuleOperations.h"
#include "inet/common/IProtocolRegistrationListener.h"
#include "inet/common/ProtocolTag_m.h"
#include "inet/linklayer/common/InterfaceTag_m.h"
#include "inet/networklayer/contract/IInterfaceTable.h"
#include "inet/networklayer/contract/ipv4/Ipv4Address.h"
#include "inet/networklayer/ipv4/IIpv4RoutingTable.h"
#include "inet/networklayer/ipv4/Ipv4Header_m.h"
#include "inet/networklayer/ipv4/Ipv4InterfaceData.h"
#include "inet/networklayer/common/FragmentationTag_m.h"
#include "inet/networklayer/common/L3AddressResolver.h"

#include "HelloMsg_m.h"
#include "XedMsg_m.h"

#include <omnetpp.h>
#include <vector>
#include <random>
#include <algorithm>

using namespace omnetpp;
using namespace inet;
using namespace std;

class myApp : public ApplicationBase, public UdpSocket::ICallback
{
    protected:
        //enum SelfMsgKinds { START = 1, SEND, STOP };
        int localPort = -1, destPort = -1;
        bool dontFragment = false;
        const char *packetName = nullptr;

        simtime_t startTime;
        simtime_t stopTime;

        // state
        UdpSocket socket;
        cMessage *selfMsg = nullptr;
        cModule *host = nullptr;
        cMessage *event = nullptr;
        cPar *broadcastDelay = nullptr;
        unsigned int sequencenumber = 0;
        simtime_t helloInterval;
        IInterfaceTable *ift = nullptr;
        InterfaceEntry *interface80211ptr = nullptr;
        int interfaceId = -1;
        list<L3Address> neighbors;
        Ipv4Address source;

        /********** XED **********/
        class XED
        {
          public:
            L3Address originatorAddr, destinationAddr;
            unsigned int random;
            XED(const L3Address& originatorAddr, const L3Address& destinationAddr, unsigned int random)
            : originatorAddr(originatorAddr), destinationAddr(destinationAddr), random(random) {};
            bool operator==(const XED& other) const
            {
                return this->originatorAddr == other.originatorAddr && this->destinationAddr == other.destinationAddr
                        && this->random == other.random;
            }
        };

        list<XED> lr,ls;

        /********** MTLSD **********/
        class MTLSD
        {
          public:
            L3Address originatorAddr, destinationAddr;
            char *position;
            simtime_t time;
            MTLSD(const L3Address& originatorAddr, const L3Address& destinationAddr, char *position, simtime_t time)
            : originatorAddr(originatorAddr), destinationAddr(destinationAddr), position(position), time(time) {};
            bool operator==(const MTLSD& other) const
            {
                return this->originatorAddr == other.originatorAddr && this->destinationAddr == other.destinationAddr
                        && this->position == other.position && this->time == time;
            }
        };

    protected:
        virtual int numInitStages() const override { return NUM_INIT_STAGES; }
        virtual void initialize(int stage) override;
        virtual void handleMessageWhenUp(cMessage *msg) override;

        void handleSelfMessage(cMessage *msg);

        /*virtual void processStart();
        virtual void processSend();
        virtual void processStop();*/

        // lifecycle
        virtual void handleStartOperation(LifecycleOperation *operation) override { start(); }
        virtual void handleStopOperation(LifecycleOperation *operation) override { stop(); }
        virtual void handleCrashOperation(LifecycleOperation *operation) override  { stop(); }
        void start();
        void stop();

        virtual void socketDataArrived(UdpSocket *socket, Packet *packet) override;
        virtual void socketErrorArrived(UdpSocket *socket, Indication *indication) override;
        virtual void socketClosed(UdpSocket *socket) override;

        //virtual void generateMTLSDPacket();
        //virtual Packet *generateXEDPacket();
        virtual double generateRandom();

    public:
       myApp() {}
       ~myApp();
};

#endif /* MYAPP_H_ */

#include "myApp.h"
#include "inet/applications/base/ApplicationPacket_m.h"
#include "inet/applications/udpapp/UdpBasicApp.h"
#include "inet/common/TagBase_m.h"
#include "inet/networklayer/common/L3AddressTag_m.h"
#include <iterator>

using namespace std;
Define_Module(myApp);

myApp::~myApp()
{
    EV << "App destructor" << endl;
    cancelAndDelete(selfMsg);
}

void myApp::initialize(int stage)
{
    ApplicationBase::initialize(stage);

    if (stage == INITSTAGE_LOCAL)
    {
        sequencenumber = 0;
        ift = getModuleFromPar<IInterfaceTable>(par("interfaceTableModule"), this);
        event = new cMessage("event");
        broadcastDelay = &par("broadcastDelay");
        helloInterval = par("helloInterval");
        localPort = par("localPort");
        destPort = par("destPort");
        packetName = par("packetName");
        startTime = par("startTime");
        stopTime = par("stopTime");

    }
    else if (stage == INITSTAGE_ROUTING_PROTOCOLS)
    {
        registerService(Protocol::manet, nullptr, gate("socketIn"));
        registerProtocol(Protocol::manet, gate("socketOut"), nullptr);
    }
}

void myApp::handleSelfMessage(cMessage *msg)
{
    if (msg == event)
    {
        auto hello = makeShared<HelloMsg>();
        Ipv4Address source = (interface80211ptr->getProtocolData<Ipv4InterfaceData>()->getIPAddress());
        hello->setChunkLength(b(128));
        hello->setSrcAddress(source);
        sequencenumber += 2;
        hello->setSequencenumber(sequencenumber);
        hello->setNextAddress(source);
        hello->setHopdistance(1);
        auto packet = new Packet("Hello", hello);
        packet->addTagIfAbsent<L3AddressReq>()->setDestAddress(Ipv4Address(255, 255, 255, 255));
        packet->addTagIfAbsent<L3AddressReq>()->setSrcAddress(source);
        packet->addTagIfAbsent<InterfaceReq>()->setInterfaceId(interface80211ptr->getInterfaceId());
        packet->addTagIfAbsent<PacketProtocolTag>()->setProtocol(&Protocol::manet);
        packet->addTagIfAbsent<DispatchProtocolReq>()->setProtocol(&Protocol::ipv4);

        send(packet, "socketOut");
        packet = nullptr;
        hello = nullptr;

        scheduleAt(simTime()+helloInterval+broadcastDelay->doubleValue(), event);
    }
}

void myApp::handleMessageWhenUp(cMessage *msg)
{
    if (msg->isSelfMessage())
    {
        handleSelfMessage(msg);
    }
    else if (check_and_cast<Packet *>(msg)->getTag<PacketProtocolTag>()->getProtocol() == &Protocol::manet)
    {
        auto recHello = staticPtrCast<HelloMsg>(check_and_cast<Packet *>(msg)->peekData<HelloMsg>()->dupShared());
        if (msg->arrivedOn("socketIn"))
        {
            bubble("Received hello message");
            Ipv4Address source = interface80211ptr->getProtocolData<Ipv4InterfaceData>()->getIPAddress();
            Ipv4Address src;
            unsigned int msgsequencenumber;
            int numHops;
            Ipv4Address next;

            src = recHello->getSrcAddress();
            msgsequencenumber = recHello->getSequencenumber();
            next = recHello->getNextAddress();
            numHops = recHello->getHopdistance();

            if (src == source)
            {
                EV_INFO << "Hello msg dropped. This message returned to the original creator.\n";
                delete msg;
                return;
            }
            else
            {
                neighbors.push_back(src);
                /*list<XED>::iterator findIter = find(ls.begin()->destinationAddr, ls.end()->destinationAddr, src);
                if (findIter != ls.end()->destinationAddr)
                {

                }*/
                source = (interface80211ptr->getProtocolData<Ipv4InterfaceData>()->getIPAddress());
                //socket.bind(source, localPort);
                auto xed = makeShared<XedMsg>();
                xed->setChunkLength(b(128)); ///size of XED message in bits
                xed->setSrcAddress(source);
                xed->setDstAddress(src);
                double random = generateRandom();
                xed->setRandom(random);
                //XED item = XED(source, src, random);
                //ls.push_back(item);
                auto packet = new Packet("XED", xed);
                packet->addTagIfAbsent<L3AddressReq>()->setDestAddress(src);
                packet->addTagIfAbsent<L3AddressReq>()->setSrcAddress(source);
                packet->addTagIfAbsent<InterfaceReq>()->setInterfaceId(interfaceId);
                packet->addTagIfAbsent<PacketProtocolTag>()->setProtocol(&Protocol::ipv4);
                packet->addTagIfAbsent<DispatchProtocolReq>()->setProtocol(&Protocol::ipv4);

                socket.setOutputGate(gate("socketOut"));
                socket.setCallback(this);
                socket.bind(source, localPort);
                //emit(packetSentSignal, packet);
                socket.sendTo(packet, src, destPort);

                //send(packet, "socketOut");
                packet = nullptr;
                xed = nullptr;

                /*Ipv4Address source = (interface80211ptr->getProtocolData<Ipv4InterfaceData>()->getIPAddress());
                EV << "I am node " << source << ", my neighbors are : " << endl;
                list<L3Address>::iterator it;
                for (it = neighbors.begin(); it != neighbors.end(); ++it)
                {
                    EV << it. << endl;
                }
                for (auto const& i : neighbors)
                {
                    EV << i.str() << endl;
                }*/
                EV << "I am your neighbor " << src.str();
            }
            delete msg;
        }
        else if (check_and_cast<Packet *>(msg)->getTag<PacketProtocolTag>()->getProtocol() == &Protocol::ipv4)
        {
            EV << "Xed message received" << endl;
            //auto recXed = staticPtrCast<XedMsg>(check_and_cast<Packet *>(msg)->peekData<XedMsg>()->dupShared());
        }
        else
            throw cRuntimeError("Message arrived on unknown gate %s", msg->getArrivalGate()->getName());
    }
}

void myApp::start()
{
    /*socket.setOutputGate(gate("socketOut"));
    socket.setCallback(this);*/
    int  num_80211 = 0;
    InterfaceEntry *ie;
    InterfaceEntry *i_face;
    const char *name;
    for (int i = 0; i < ift->getNumInterfaces(); i++)
    {
        ie = ift->getInterface(i);
        name = ie->getInterfaceName();
        if (strstr(name, "wlan") != nullptr)
        {
            i_face = ie;
            num_80211++;
            interfaceId = i;
        }
    }

    if (num_80211 == 1)
    {
        interface80211ptr = i_face;
        interfaceId = interface80211ptr->getInterfaceId();
    }
    else
        throw cRuntimeError("Node has found %i 80211 interfaces", num_80211);

    scheduleAt(simTime() + uniform(0.0, par("maxVariance").doubleValue()), event);
}

double myApp::generateRandom()
{
    double lower_bound = 10000;
    double upper_bound = 100000;
    uniform_real_distribution<double> unif(lower_bound,upper_bound);
    default_random_engine re;
    double a_random_double = unif(re);
    return a_random_double;
}

void myApp::stop()
{
    cancelEvent(event);
    socket.close();
    delayActiveOperationFinish(par("stopOperationTimeout"));
}

void myApp::socketDataArrived(UdpSocket *socket, Packet *packet)
{
    emit(packetReceivedSignal, packet);
    EV_INFO << "Received packet: " << UdpSocket::getReceivedPacketInfo(packet) << endl;
}

void myApp::socketErrorArrived(UdpSocket *socket, Indication *indication)
{
    EV_WARN << "Ignoring UDP error report " << indication->getName() << endl;
    delete indication;
}

void myApp::socketClosed(UdpSocket *socket)
{
    if (operationalState == State::STOPPING_OPERATION)
            startActiveOperationExtraTimeOrFinish(par("stopOperationExtraTime"));
}

Error: NED type 'myApp' could not be fully resolved due to a missing base type or interface, at /home/bocuhra/Downloads/omnetpp-5.4.1/samples/SaaS/myApp.ned:18

myApp.cc
HelloMsg_m.cc
XedMsg_m.cc
Creating executable: out/gcc-release//SaaS
/usr/bin/ld: cannot find -lINET
collect2: error: ld returned 1 exit status
Makefile:104: recipe for target 'out/gcc-release//SaaS' failed
make: *** [out/gcc-release//SaaS] Error 1


来源: stackexchange

问:
Can't get asp .net core 2.2 to validate my JWT
(TL;DR: check the last update)

The first issue with this is that the API has changed between the different versions of .net core.

The second one is that every example I find online is slightly different with not real authoritative answer as to what does what; rather I keep finding posts with 'oh, changing this worked for me', but it looks like everyone is, like me, experimenting with it rather than having a full understanding.

Anyhow, here is the code:

```<code>        Services.AddAuthentication(A =>
        {
            A.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            A.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
        })
        .AddJwtBearer(O =>
        {
            O.RequireHttpsMetadata = false;
            O.SaveToken = true;
            O.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(AuthJWTPublicKey)),
                ValidateIssuer = false,
                ValidateAudience = false
            };
        });
</code>```

I have a valid JWT but any call to my controller results in an immediate error 401.

I have tried to decorate the controller with:

[Authorize]

[Authorize(Roles = "offline_access")]

[Authorize(AuthenticationSchemes =
  JwtBearerDefaults.AuthenticationScheme, Roles = "offline_access")]

but no luck

The JWT content is:

```<code>{
   "jti":"837c2dd1-cca5-491e-84a4-b17429366df5",
   "exp":1558355152,
   "nbf":0,
   "iat":1558354852,
   "iss":"xxxx",
   "aud":"account",
   "sub":"4ed1c313-c692-44db-86d3-7605f3e2c2c1",
   "typ":"Bearer",
   "azp":"test-app",
   "auth_time":1558354850,
   "session_state":"e40c9a95-ae8a-4d6e-b2a4-ad5e833867ea",
   "acr":"1",
   "realm_access":{
      "roles":[
         "offline_access",
         "uma_authorization"
      ]
   },
   "resource_access":{
      "account":{
         "roles":[
            "manage-account",
            "manage-account-links",
            "view-profile"
         ]
      }
   },
   "scope":"openid email profile",
   "email_verified":true,
   "name":"firstd6d05 last29954",
   "preferred_username":"xxxx",
   "given_name":"firstd6d05",
   "family_name":"last29954",
   "email":"xxxx",
   "group":[
      "/Administrators"
   ]
}
</code>```

My goal is purely to verify the signature of the JWT (and eventually it's expiration) and have access to the token in the controller.

I am passing the JWT through the header, under 'Authorization' and with the text 'Bearer' in front of the token.

What am I missing?

Following the answer below, I did the following change:

I added:

```<code>Services.AddTransient<IClaimsTransformation, ClaimsTransformer>();
</code>```

and then added the following class with a break

```<code>internal class ClaimsTransformer : IClaimsTransformation
{
    public Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal)
    {
        Debugger.Break();
    }
}
</code>```

but I am still getting a 401 with the Keycloak token; so it looks like it doesn't get to the claims transformer before being rejected.

I added the debug output of ASP.

It is at: https://pastebin.com/qvGsQG6j

The relevant part seems to be:

```<code>    info: Microsoft.AspNetCore.Authorization.DefaultAuthorizationService[2]
          => ConnectionId:0HLN4CPASJL8F => RequestId:0HLN4CPASJL8F:00000001 RequestPath:/helpers/log => Test.WebControllers.HelpersController.GetLog (Test)
          Authorization failed.
    Microsoft.AspNetCore.Authorization.DefaultAuthorizationService:Info:Authorization failed.
    Microsoft.AspNetCore.Authorization.DefaultAuthorizationService:Info:Authorization failed.
    info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[3]
          => ConnectionId:0HLN4CPASJL8F => RequestId:0HLN4CPASJL8F:00000001 RequestPath:/helpers/log => Test.WebControllers.HelpersController.GetLog (Test)
          Authorization failed for the request at filter 'Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter'.
    Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Info:Authorization failed for the request at filter 'Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter'.
    Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Info:Authorization failed for the request at filter 'Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter'.
    info: Microsoft.AspNetCore.Mvc.ChallengeResult[1]
          => ConnectionId:0HLN4CPASJL8F => RequestId:0HLN4CPASJL8F:00000001 RequestPath:/helpers/log => Test.WebControllers.HelpersController.GetLog (Test)
</code>```

This specific line may explain the issue:

Authorization failed for the request at filter 'Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter'

but 'failed' seems a bit vague to me.

Last test:

I have this token:

```<code>eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1lIjoibXkgbmFtZSIsImh0dHA6Ly9zY2hlbWFzLnhtbHNvYXAub3JnL3dzLzIwMDUvMDUvaWRlbnRpdHkvY2xhaW1zL2VtYWlsYWRkcmVzcyI6Im5vQGVtYWlsLmNvbSIsImh0dHA6Ly9zY2hlbWFzLm1pY3Jvc29mdC5jb20vd3MvMjAwOC8wNi9pZGVudGl0eS9jbGFpbXMvZXhwaXJhdGlvbiI6IjA1LzMxLzIwMTkgMDA6MTM6MjAiLCJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9zaWQiOiI3Y2FjZjdiNS04NjY5LTQ2OWUtOTg4NS1kNDgwNGYyOGNjNGEiLCJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA5LzA5L2lkZW50aXR5L2NsYWltcy9hY3RvciI6ImQyZjZiNzI0LWE0ZjktNGJkZC1hNjQ3LTRkM2UxYTU5NjhkZSIsIm5iZiI6MTU1OTE3NTIwMCwiZXhwIjoxNTU5MjYxNjAwLCJpc3MiOiJ0ZXN0IiwiYXVkIjoidGVzdC1hcHAifQ.y42RUvMM69aDTvCydoU3mOKu2giub6OvKpd-RNVmom4
</code>```

with the key:

```<code>MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAjayVuqZOuKK38rhsRwrRGzVcv/7b4fHXrzpol3K5TTAPttNUaQvCKQD7BQN+V8nvkBsQcxPk5ONnxzbFb/npENC4UtwK5J6iiVrinE7sDrWZQNo9LkwbuG9x0fuuf8U3H2CnwZEfFaf2kbU1v7XosNGi+aYASupvhwoiJtK+17ZPloxSQy3Qny2tQWi7Dh/Cr5+m5JBy6HeGLq2cq+oalFYzrGGmQXndLtJpBZgrPd7nR6lJSMiRcJtcpxTJbYTEVVXoB0SR1bPmYYB/6y7klVDVedTow+1mwZrDMrbRiTBPSifCIBs3rxLQaL207blg+kj+EVLED5fZSOBlOyTOYQIDAQAB
</code>```

it decodes to (as tested by jwt.io):

```<code>{
  "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name": "my name",
  "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress": "no@email.com",
  "http://schemas.microsoft.com/ws/2008/06/identity/claims/expiration": "05/31/2019 00:13:20",
  "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/sid": "7cacf7b5-8669-469e-9885-d4804f28cc4a",
  "http://schemas.xmlsoap.org/ws/2009/09/identity/claims/actor": "d2f6b724-a4f9-4bdd-a647-4d3e1a5968de",
  "nbf": 1559175200,
  "exp": 1559261600,
  "iss": "test",
  "aud": "test-app"
}
</code>```

it is generated by the following code:

```<code>        var Expiration = DateTime.UtcNow + TimeSpan.FromDays(1);
        var Identity = new ClaimsIdentity(new[]
        {
            new Claim(ClaimTypes.Name,          "my name"),
            new Claim(ClaimTypes.Email,         "no@email.com"),
            new Claim(ClaimTypes.Expiration,    Expiration.ToString(CultureInfo.InvariantCulture)),
            new Claim(ClaimTypes.Sid,           Guid.NewGuid().ToString()),
            new Claim(ClaimTypes.Actor,         Guid.NewGuid().ToString()),
        });

        var Token = new JwtSecurityToken
        (
            issuer:             "test",
            audience:           "test-app",
            claims:             Identity.Claims,
            notBefore:          DateTime.UtcNow,
            expires:            Expiration,
            signingCredentials: new SigningCredentials(new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_JwtRsaPublicKey)), SecurityAlgorithms.HmacSha256)
        );

        var TokenString = new JwtSecurityTokenHandler().WriteToken(Token);
        return TokenString;
</code>```

In asp, I have the following code:

```<code>                    Services.AddAuthentication(A =>
                    {
                        A.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                        A.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
                    })
                    .AddJwtBearer(O =>
                    {
                        O.RequireHttpsMetadata = false;
                        O.SaveToken = true;
                        O.IncludeErrorDetails = true;
                        O.TokenValidationParameters = new TokenValidationParameters
                        {
                            ValidateIssuerSigningKey = true,
                            IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(AuthJWTPublicKey)),
                            ValidateIssuer = false,
                            ValidateAudience = false
                        };
                    });
</code>```

and I have a controller method with:

```<code>{
   "jti":"837c2dd1-cca5-491e-84a4-b17429366df5",
   "exp":1558355152,
   "nbf":0,
   "iat":1558354852,
   "iss":"xxxx",
   "aud":"account",
   "sub":"4ed1c313-c692-44db-86d3-7605f3e2c2c1",
   "typ":"Bearer",
   "azp":"test-app",
   "auth_time":1558354850,
   "session_state":"e40c9a95-ae8a-4d6e-b2a4-ad5e833867ea",
   "acr":"1",
   "realm_access":{
      "roles":[
         "offline_access",
         "uma_authorization"
      ]
   },
   "resource_access":{
      "account":{
         "roles":[
            "manage-account",
            "manage-account-links",
            "view-profile"
         ]
      }
   },
   "scope":"openid email profile",
   "email_verified":true,
   "name":"firstd6d05 last29954",
   "preferred_username":"xxxx",
   "given_name":"firstd6d05",
   "family_name":"last29954",
   "email":"xxxx",
   "group":[
      "/Administrators"
   ]
}
</code>```0

But I keep getting a 401, no matter what I try, I get a 401...

Even if I set ValidateIssuerSigningKey to false. I get a 401

The setup is:

In ConfigureServices, I have:

```<code>{
   "jti":"837c2dd1-cca5-491e-84a4-b17429366df5",
   "exp":1558355152,
   "nbf":0,
   "iat":1558354852,
   "iss":"xxxx",
   "aud":"account",
   "sub":"4ed1c313-c692-44db-86d3-7605f3e2c2c1",
   "typ":"Bearer",
   "azp":"test-app",
   "auth_time":1558354850,
   "session_state":"e40c9a95-ae8a-4d6e-b2a4-ad5e833867ea",
   "acr":"1",
   "realm_access":{
      "roles":[
         "offline_access",
         "uma_authorization"
      ]
   },
   "resource_access":{
      "account":{
         "roles":[
            "manage-account",
            "manage-account-links",
            "view-profile"
         ]
      }
   },
   "scope":"openid email profile",
   "email_verified":true,
   "name":"firstd6d05 last29954",
   "preferred_username":"xxxx",
   "given_name":"firstd6d05",
   "family_name":"last29954",
   "email":"xxxx",
   "group":[
      "/Administrators"
   ]
}
</code>```1

In Configure, I have:

```<code>{
   "jti":"837c2dd1-cca5-491e-84a4-b17429366df5",
   "exp":1558355152,
   "nbf":0,
   "iat":1558354852,
   "iss":"xxxx",
   "aud":"account",
   "sub":"4ed1c313-c692-44db-86d3-7605f3e2c2c1",
   "typ":"Bearer",
   "azp":"test-app",
   "auth_time":1558354850,
   "session_state":"e40c9a95-ae8a-4d6e-b2a4-ad5e833867ea",
   "acr":"1",
   "realm_access":{
      "roles":[
         "offline_access",
         "uma_authorization"
      ]
   },
   "resource_access":{
      "account":{
         "roles":[
            "manage-account",
            "manage-account-links",
            "view-profile"
         ]
      }
   },
   "scope":"openid email profile",
   "email_verified":true,
   "name":"firstd6d05 last29954",
   "preferred_username":"xxxx",
   "given_name":"firstd6d05",
   "family_name":"last29954",
   "email":"xxxx",
   "group":[
      "/Administrators"
   ]
}
</code>```2

答:
According to dotnet/corefx:

```
public static class ClaimTypes
{
    internal const string ClaimTypeNamespace =<b>"http://schemas.microsoft.com/ws/2008/06/identity/claims";</b>
    ....
    public const string Role = <b>ClaimTypeNamespace + "/role";</b>
    ...
```

The const ClaimTypes.Role is http://schemas.microsoft.com/ws/2008/06/identity/claims/role

Note your controller requires a role of offline_access:

```<code>[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme, Roles = "offline_access")]
</code>```

In other words, it expects the decoded JWT has a property of http://schemas.microsoft.com/ws/2008/06/identity/claims/role to configure the roles:

```
{
  "nbf": ...,
  "exp": ...,
  "iss": ...,
  "aud": ...,
   ...,
  <b>"http://schemas.microsoft.com/ws/2008/06/identity/claims/role"</b>: [
    "offline_access",
    "...other roles"
  ],
}
```

However, you configure the roles in the following way:

```<code>   "realm_access":{
      "roles":[
         "offline_access",
         "uma_authorization"
      ]
   },
</code>```

The easiest way is rebuild the token to config a role of offline_access:

```<code>    ClaimsIdentity identity = new ClaimsIdentity(new[] {
        new Claim(ClaimTypes.Name,"1024"),
        new Claim(ClaimTypes.Role,"offline_access"),
        new Claim(ClaimTypes.Role,"...other roles"),
        // ... other claims
    });

    var token = new JwtSecurityToken
    (
        issuer: _issuer,
        audience: _audience,
        claims: identity.Claims,
        expires: expiry,
        notBefore: DateTime.UtcNow,
        signingCredentials: new SigningCredentials(new SymmetricSecurityKey(Encoding.UTF8.GetBytes(mykeyname)),
                SecurityAlgorithms.HmacSha256)
    );

    var tokenStr = tokenHandler.WriteToken(token);
</code>```

Or you could transform the keycloak's style claim to Microsoft's style by registering a custom IClaimsTransformation, see a Sample by ASP.NET Core Team https://github.com/aspnet/AspNetCore/blob/658b37d2bd3b0da2c07e25b53fa5c97ce8d656d3/src/Security/samples/ClaimsTransformation/Startup.cs#L34

ContentLicense: CC BY-SA 4.0

Body:
(TL;DR: check the last update)

The first issue with this is that the API has changed between the different versions of .net core.

The second one is that every example I find online is slightly different with not real authoritative answer as to what does what; rather I keep finding posts with 'oh, changing this worked for me', but it looks like everyone is, like me, experimenting with it rather than having a full understanding.

Anyhow, here is the code:

        Services.AddAuthentication(A =>
        {
            A.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            A.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
        })
        .AddJwtBearer(O =>
        {
            O.RequireHttpsMetadata = false;
            O.SaveToken = true;
            O.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(AuthJWTPublicKey)),
                ValidateIssuer = false,
                ValidateAudience = false
            };
        });

I have a valid JWT but any call to my controller results in an immediate error 401.

I have tried to decorate the controller with:

[Authorize]

[Authorize(Roles = "offline_access")]

[Authorize(AuthenticationSchemes =
  JwtBearerDefaults.AuthenticationScheme, Roles = "offline_access")]

but no luck

The JWT content is:

{
   "jti":"837c2dd1-cca5-491e-84a4-b17429366df5",
   "exp":1558355152,
   "nbf":0,
   "iat":1558354852,
   "iss":"xxxx",
   "aud":"account",
   "sub":"4ed1c313-c692-44db-86d3-7605f3e2c2c1",
   "typ":"Bearer",
   "azp":"test-app",
   "auth_time":1558354850,
   "session_state":"e40c9a95-ae8a-4d6e-b2a4-ad5e833867ea",
   "acr":"1",
   "realm_access":{
      "roles":[
         "offline_access",
         "uma_authorization"
      ]
   },
   "resource_access":{
      "account":{
         "roles":[
            "manage-account",
            "manage-account-links",
            "view-profile"
         ]
      }
   },
   "scope":"openid email profile",
   "email_verified":true,
   "name":"firstd6d05 last29954",
   "preferred_username":"xxxx",
   "given_name":"firstd6d05",
   "family_name":"last29954",
   "email":"xxxx",
   "group":[
      "/Administrators"
   ]
}

My goal is purely to verify the signature of the JWT (and eventually it's expiration) and have access to the token in the controller.

I am passing the JWT through the header, under 'Authorization' and with the text 'Bearer' in front of the token.

What am I missing?

Following the answer below, I did the following change:

I added:

Services.AddTransient<IClaimsTransformation, ClaimsTransformer>();

and then added the following class with a break

internal class ClaimsTransformer : IClaimsTransformation
{
    public Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal)
    {
        Debugger.Break();
    }
}

but I am still getting a 401 with the Keycloak token; so it looks like it doesn't get to the claims transformer before being rejected.

I added the debug output of ASP.

It is at: https://pastebin.com/qvGsQG6j

The relevant part seems to be:

    info: Microsoft.AspNetCore.Authorization.DefaultAuthorizationService[2]
          => ConnectionId:0HLN4CPASJL8F => RequestId:0HLN4CPASJL8F:00000001 RequestPath:/helpers/log => Test.WebControllers.HelpersController.GetLog (Test)
          Authorization failed.
    Microsoft.AspNetCore.Authorization.DefaultAuthorizationService:Info:Authorization failed.
    Microsoft.AspNetCore.Authorization.DefaultAuthorizationService:Info:Authorization failed.
    info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[3]
          => ConnectionId:0HLN4CPASJL8F => RequestId:0HLN4CPASJL8F:00000001 RequestPath:/helpers/log => Test.WebControllers.HelpersController.GetLog (Test)
          Authorization failed for the request at filter 'Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter'.
    Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Info:Authorization failed for the request at filter 'Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter'.
    Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Info:Authorization failed for the request at filter 'Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter'.
    info: Microsoft.AspNetCore.Mvc.ChallengeResult[1]
          => ConnectionId:0HLN4CPASJL8F => RequestId:0HLN4CPASJL8F:00000001 RequestPath:/helpers/log => Test.WebControllers.HelpersController.GetLog (Test)

This specific line may explain the issue:

Authorization failed for the request at filter 'Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter'

but 'failed' seems a bit vague to me.

Last test:

I have this token:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1lIjoibXkgbmFtZSIsImh0dHA6Ly9zY2hlbWFzLnhtbHNvYXAub3JnL3dzLzIwMDUvMDUvaWRlbnRpdHkvY2xhaW1zL2VtYWlsYWRkcmVzcyI6Im5vQGVtYWlsLmNvbSIsImh0dHA6Ly9zY2hlbWFzLm1pY3Jvc29mdC5jb20vd3MvMjAwOC8wNi9pZGVudGl0eS9jbGFpbXMvZXhwaXJhdGlvbiI6IjA1LzMxLzIwMTkgMDA6MTM6MjAiLCJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9zaWQiOiI3Y2FjZjdiNS04NjY5LTQ2OWUtOTg4NS1kNDgwNGYyOGNjNGEiLCJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA5LzA5L2lkZW50aXR5L2NsYWltcy9hY3RvciI6ImQyZjZiNzI0LWE0ZjktNGJkZC1hNjQ3LTRkM2UxYTU5NjhkZSIsIm5iZiI6MTU1OTE3NTIwMCwiZXhwIjoxNTU5MjYxNjAwLCJpc3MiOiJ0ZXN0IiwiYXVkIjoidGVzdC1hcHAifQ.y42RUvMM69aDTvCydoU3mOKu2giub6OvKpd-RNVmom4

with the key:

MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAjayVuqZOuKK38rhsRwrRGzVcv/7b4fHXrzpol3K5TTAPttNUaQvCKQD7BQN+V8nvkBsQcxPk5ONnxzbFb/npENC4UtwK5J6iiVrinE7sDrWZQNo9LkwbuG9x0fuuf8U3H2CnwZEfFaf2kbU1v7XosNGi+aYASupvhwoiJtK+17ZPloxSQy3Qny2tQWi7Dh/Cr5+m5JBy6HeGLq2cq+oalFYzrGGmQXndLtJpBZgrPd7nR6lJSMiRcJtcpxTJbYTEVVXoB0SR1bPmYYB/6y7klVDVedTow+1mwZrDMrbRiTBPSifCIBs3rxLQaL207blg+kj+EVLED5fZSOBlOyTOYQIDAQAB

it decodes to (as tested by jwt.io):

{
  "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name": "my name",
  "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress": "no@email.com",
  "http://schemas.microsoft.com/ws/2008/06/identity/claims/expiration": "05/31/2019 00:13:20",
  "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/sid": "7cacf7b5-8669-469e-9885-d4804f28cc4a",
  "http://schemas.xmlsoap.org/ws/2009/09/identity/claims/actor": "d2f6b724-a4f9-4bdd-a647-4d3e1a5968de",
  "nbf": 1559175200,
  "exp": 1559261600,
  "iss": "test",
  "aud": "test-app"
}

it is generated by the following code:

        var Expiration = DateTime.UtcNow + TimeSpan.FromDays(1);
        var Identity = new ClaimsIdentity(new[]
        {
            new Claim(ClaimTypes.Name,          "my name"),
            new Claim(ClaimTypes.Email,         "no@email.com"),
            new Claim(ClaimTypes.Expiration,    Expiration.ToString(CultureInfo.InvariantCulture)),
            new Claim(ClaimTypes.Sid,           Guid.NewGuid().ToString()),
            new Claim(ClaimTypes.Actor,         Guid.NewGuid().ToString()),
        });

        var Token = new JwtSecurityToken
        (
            issuer:             "test",
            audience:           "test-app",
            claims:             Identity.Claims,
            notBefore:          DateTime.UtcNow,
            expires:            Expiration,
            signingCredentials: new SigningCredentials(new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_JwtRsaPublicKey)), SecurityAlgorithms.HmacSha256)
        );

        var TokenString = new JwtSecurityTokenHandler().WriteToken(Token);
        return TokenString;

In asp, I have the following code:

                    Services.AddAuthentication(A =>
                    {
                        A.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                        A.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
                    })
                    .AddJwtBearer(O =>
                    {
                        O.RequireHttpsMetadata = false;
                        O.SaveToken = true;
                        O.IncludeErrorDetails = true;
                        O.TokenValidationParameters = new TokenValidationParameters
                        {
                            ValidateIssuerSigningKey = true,
                            IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(AuthJWTPublicKey)),
                            ValidateIssuer = false,
                            ValidateAudience = false
                        };
                    });

and I have a controller method with:

  [Authorize]

But I keep getting a 401, no matter what I try, I get a 401...

Even if I set ValidateIssuerSigningKey to false. I get a 401

The setup is:

In ConfigureServices, I have:

Services.AddMvc()
and the code above

In Configure, I have:

Application.UseAuthentication();
Application.UseMvc(Routes => { Routes.MapRoute("default_route", "{controller}/{action}/{id?}"); });

Body:
According to dotnet/corefx:

public static class ClaimTypes
{
    internal const string ClaimTypeNamespace ="http://schemas.microsoft.com/ws/2008/06/identity/claims";
    ....
    public const string Role = ClaimTypeNamespace + "/role";
    ...

The const ClaimTypes.Role is http://schemas.microsoft.com/ws/2008/06/identity/claims/role

Note your controller requires a role of offline_access:

[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme, Roles = "offline_access")]

In other words, it expects the decoded JWT has a property of http://schemas.microsoft.com/ws/2008/06/identity/claims/role to configure the roles:

{
  "nbf": ...,
  "exp": ...,
  "iss": ...,
  "aud": ...,
   ...,
  "http://schemas.microsoft.com/ws/2008/06/identity/claims/role": [
    "offline_access",
    "...other roles"
  ],
}

However, you configure the roles in the following way:

   "realm_access":{
      "roles":[
         "offline_access",
         "uma_authorization"
      ]
   },

The easiest way is rebuild the token to config a role of offline_access:

    ClaimsIdentity identity = new ClaimsIdentity(new[] {
        new Claim(ClaimTypes.Name,"1024"),
        new Claim(ClaimTypes.Role,"offline_access"),
        new Claim(ClaimTypes.Role,"...other roles"),
        // ... other claims
    });

    var token = new JwtSecurityToken
    (
        issuer: _issuer,
        audience: _audience,
        claims: identity.Claims,
        expires: expiry,
        notBefore: DateTime.UtcNow,
        signingCredentials: new SigningCredentials(new SymmetricSecurityKey(Encoding.UTF8.GetBytes(mykeyname)),
                SecurityAlgorithms.HmacSha256)
    );

    var tokenStr = tokenHandler.WriteToken(token);

Or you could transform the keycloak's style claim to Microsoft's style by registering a custom IClaimsTransformation, see a Sample by ASP.NET Core Team https://github.com/aspnet/AspNetCore/blob/658b37d2bd3b0da2c07e25b53fa5c97ce8d656d3/src/Security/samples/ClaimsTransformation/Startup.cs#L34


问:
Switching from dataflow sdk to beam sdk causing exceptions in URN lookup
We changed from the dataflow sdk (2.5.0) to apache beam sdk (2.12.0) with no changes in the code.

We get the following error message

Expected DoFn to be FunctionSpec with URN urn:beam:dofn:javasdk:0.1, but URN was

Is there any other setting that has to be done?

It seems to be failing for this line

pipeline.apply(<some code here>).watchForNewFiles(10, Watch.Growth.never()))

答: Downgrading the apache beam sdk to 2.10.0 worked for this one in the GCP environment. </p>


问:
how to check if there data range between 2 given dates?
I have start time and end time in my application. I now need to check if there is any time falling between those time in SQL Query.

How do I write the query.

Thanks

答:
This should work for you.</p>

```<code>Select * From MyTable
Where timecreated Between Cast('7/20/08 12:01:01' As DateTime) And Cast('7/20/09 12:01:01' as DateTime)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
This should work for you.

Select * From MyTable
Where timecreated Between Cast('7/20/08 12:01:01' As DateTime) And Cast('7/20/09 12:01:01' as DateTime)


问:
Checking if bitmap is recycled doesn't help to solve "RuntimeException: Canvas: trying to use a recycled bitmap"
I send bitmaps to my activity from Service (using LocalBroadcastManager and intent bitmap extra)

I set them to ImageView in activity like this:

```<code>if (!bitmap.isRecycled) {
    imageView.setImageBitmap(bitmap)
}
</code>```

When I don't need the service anymore I close it and release bitmap object kept in that service

But when I close the service I usually get the following error:

```<code>java.lang.RuntimeException: Canvas: trying to use a recycled bitmap android.graphics.Bitmap@fc4b896
</code>```

Sobitmap.isRecycled condition doesn't help here

Is there any safe method to set Bitmap to ImageView?

答:
You exception is telling you that bitmap is already recycled so no need to app check

```<code>java.lang.RuntimeException: Canvas: trying to use a recycled bitmap android.graphics.Bitmap@fc4b896
</code>```

instead just check for null value

Also check documentation why you got an error

https://developer.android.com/reference/android/graphics/Bitmap#isRecycled()

Body:
I send bitmaps to my activity from Service (using LocalBroadcastManager and intent bitmap extra)

I set them to ImageView in activity like this:

if (!bitmap.isRecycled) {
    imageView.setImageBitmap(bitmap)
}

When I don't need the service anymore I close it and release bitmap object kept in that service

But when I close the service I usually get the following error:

java.lang.RuntimeException: Canvas: trying to use a recycled bitmap android.graphics.Bitmap@fc4b896

Sobitmap.isRecycled condition doesn't help here

Is there any safe method to set Bitmap to ImageView?

Body:
You exception is telling you that bitmap is already recycled so no need to app check

java.lang.RuntimeException: Canvas: trying to use a recycled bitmap android.graphics.Bitmap@fc4b896

instead just check for null value

Also check documentation why you got an error

https://developer.android.com/reference/android/graphics/Bitmap#isRecycled()


问:
Manifest merger failed when using leakcanary 2.0 alpha 2
I am using leakcanary 1.6.3 in my project to find memory-leaks without any problem using:

```<code>debugImplementation 'com.squareup.leakcanary:leakcanary-android:1.6.3'
</code>```

Now I want to update it to leakcanary 2.0 alpha 2 using:

```<code>debugImplementation 'com.squareup.leakcanary:leakcanary-android:2.0-alpha-2
</code>```

But when I try to build project, it gives me manifest merger failed.

```<code>ERROR: Manifest merger failed : Attribute application@appComponentFactory value=(android.support.v4.app.CoreComponentFactory) from [com.android.support:support-compat:28.0.0] AndroidManifest.xml:22:18-91
is also present at [androidx.core:core:1.0.1] AndroidManifest.xml:22:18-86 value=(androidx.core.app.CoreComponentFactory).
Suggestion: add 'tools:replace="android:appComponentFactory"' to <application> element at AndroidManifest.xml:10:5-50:19 to override.
</code>```

How do I fix this error?

Update: I am using android.support libraries in my project.

答:
After some research in leakcanary 2.0 alpha 2 code, I found that the new version of library uses androidx libraries but I am using android.support libraries in my project. If I refactor my project to use androidx then no error occur.

It seems that:

A project using androidx can use a library that uses android.support

But a project using android.support can not use a library that uses androidx

This SO answer explain androidx and how to migrate your project to androidx.

Body:
I am using leakcanary 1.6.3 in my project to find memory-leaks without any problem using:

debugImplementation 'com.squareup.leakcanary:leakcanary-android:1.6.3'

Now I want to update it to leakcanary 2.0 alpha 2 using:

debugImplementation 'com.squareup.leakcanary:leakcanary-android:2.0-alpha-2

But when I try to build project, it gives me manifest merger failed.

ERROR: Manifest merger failed : Attribute application@appComponentFactory value=(android.support.v4.app.CoreComponentFactory) from [com.android.support:support-compat:28.0.0] AndroidManifest.xml:22:18-91
is also present at [androidx.core:core:1.0.1] AndroidManifest.xml:22:18-86 value=(androidx.core.app.CoreComponentFactory).
Suggestion: add 'tools:replace="android:appComponentFactory"' to <application> element at AndroidManifest.xml:10:5-50:19 to override.

How do I fix this error?

Update: I am using android.support libraries in my project.


问:
Why does my website looks different on mozilla firefox and chrome?
I've been doing my html and i always open it using Mozilla Firefox. It seems okay but when I open it with my localhost using Chrome, it looks different.

Firefox

Chrome

This is the part that it went different:

```<code><div class ="label">
  <li><a href="html/profiles.html"> Profiles</a></li>
  <li><a href="html/expertise.html"> Expertise</a></li>
  <li><a href="html/location.html"> Location</a></li>
</div>
</code>```

This is the css part:

.label
{
  display: inline-flex;

}

.label li a
{
  margin-right: -433px;
  margin-left: 490px;
  text-decoration: none;
  font-size: 20px;
  list-style: none;
  font-family:"Arial", Serif;
  font-weight: bold;
  color: #3b5998;
}
.label li{
  list-style: none;
}
```

答:
li does not work fine on different browsers without ul or li. You should enclose this with ol  or ul tags. Here is an example

 Profiles

 Expertise

 Location

```

Moreover, all browsers have a default styling for all HTML elements. these elements are rendered based on default styling unless and until browser does not find styling for that element in CSS.
If you want to make the look of lists in both chrome and firefox, you will need to write CSS for the list and list items.

Body:
I've been doing my html and i always open it using Mozilla Firefox. It seems okay but when I open it with my localhost using Chrome, it looks different.

Firefox

Chrome

This is the part that it went different:

 Profiles

 Expertise

 Location

This is the css part:

.label
{
  display: inline-flex;

}

.label li a
{
  margin-right: -433px;
  margin-left: 490px;
  text-decoration: none;
  font-size: 20px;
  list-style: none;
  font-family:"Arial", Serif;
  font-weight: bold;
  color: #3b5998;
}
.label li{
  list-style: none;
}

Body:
li does not work fine on different browsers without ul or li. You should enclose this with ol  or ul tags. Here is an example

<div class ="label">
<ul>
    <li><a href="html/profiles.html"> Profiles</a></li>
     <li><a href="html/expertise.html"> Expertise</a></li>
     <li><a href="html/location.html"> Location</a></li>
     </ul>
   </div>

Moreover, all browsers have a default styling for all HTML elements. these elements are rendered based on default styling unless and until browser does not find styling for that element in CSS.
If you want to make the look of lists in both chrome and firefox, you will need to write CSS for the list and list items.


问:
How to trigger an event when any jQuery UI dialog is closed?
I would like to make it so that when a jQuery UI dialog is closed, the document's focus event is fired. This would preferably not be tied to each dialog but to the page itself whenever any dialog closes.

How can I do this?

答:
Did you checked this</p>

```<code>$( ".selector" ).dialog({
   close: function(event, ui) { ... }
});
</code>```

Body:
Did you checked this

$( ".selector" ).dialog({
   close: function(event, ui) { ... }
});


问:
Entity framework Models Access entity from another model
I have a Model of MyQueue and Service I dunno how can I get the ServiceLetter on my Services model properly to render it on my view.

Here is my MyQueue Model.

```<code>public class MyQueue
{
    public int MyQueueId { get; set; }

    public string Name { get; set; }

    public string QueueNumber
    {
        get
        {

     return string.Format("{0}{1:000}", ServiceLetter ?? "?", MyQueueId);
        }
        set { }
    }

    public int ServiceId { get; set; }

    public string ServiceLetter { get; set; }

    public virtual Service Service { get; set; }
}
</code>```

here is my Service Model

```<code>public class Service
{
    public int ServiceId { get; set; }

    public string ServiceName { get; set; }

    public string ServiceLetter { get; set; }
}
</code>```

In my dbo.MyQueues my ServiceLetter data only shows number, I need it to become what ever letter I put on my Service

I want my MyQueue to be like this, ServiceLetter is Letter not Number,

MyQueueId - Name - QueueNumber - ServiceId - ServiceLetter

1 - JohnDoe - A001 - 1 - A

2 - DoeJogn - B002 - 2 - B

3 - JognDog - C002 - 3 - C

答:
This is most likely because you only look up the MyQueues data. You need to fetch the appropriate Service model.

When using Entityframework to interface with a database, you need to use the Include function. See: https://learn.microsoft.com/en-us/ef/ef6/querying/related-data

Also take a look at join. The example on the bottom seems to explain things nicely https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/join-clause

Body:
I have a Model of MyQueue and Service I dunno how can I get the ServiceLetter on my Services model properly to render it on my view.

Here is my MyQueue Model.

public class MyQueue
{
    public int MyQueueId { get; set; }

    public string Name { get; set; }

    public string QueueNumber
    {
        get
        {

     return string.Format("{0}{1:000}", ServiceLetter ?? "?", MyQueueId);
        }
        set { }
    }

    public int ServiceId { get; set; }

    public string ServiceLetter { get; set; }

    public virtual Service Service { get; set; }
}

here is my Service Model

public class Service
{
    public int ServiceId { get; set; }

    public string ServiceName { get; set; }

    public string ServiceLetter { get; set; }
}

In my dbo.MyQueues my ServiceLetter data only shows number, I need it to become what ever letter I put on my Service

I want my MyQueue to be like this, ServiceLetter is Letter not Number,

MyQueueId - Name - QueueNumber - ServiceId - ServiceLetter

1 - JohnDoe - A001 - 1 - A

2 - DoeJogn - B002 - 2 - B

3 - JognDog - C002 - 3 - C


问:
How to detect a link click with JavaScript/jQuery in a iFrame?
How can I detect a link click inside a iFrame?

The Frame source changes a lot of times and I need to detect all link click inside the iFrame.

I try that already: Javascript - click link in iframe

JS:

```<code>$("#Source a").click();
</code>```

HTML:

```<code><iframe src="" name="Source" id="Source" scrolling="" frameborder="0" title="Anzeigebereich"></iframe>
</code>```

答: If you trying to catch an event or do whatever inside the iframe from the oustide document, it isn't possible, the iframe is different context (different document) and this is not alowed. You can check a similar question here</p>

Body:
How can I detect a link click inside a iFrame?

The Frame source changes a lot of times and I need to detect all link click inside the iFrame.

I try that already: Javascript - click link in iframe

JS:

$("#Source a").click();

HTML:


问:
Can we use spring-boot external config file name with dash `-` or underscore `_`?
I am trying to running springboot-2.x fat jar in window by using external configuration.

I have three different external config file like:

```<code>C:\application-myconfig.yml
C:\application_myconfig.yml
C:\applicationmyconfig.yml
</code>```

the configuration is :

```<code>server:
  servlet:
    contextPath: /application1

mymessage: this is test message
</code>```

In my window, I run the following commend to run spring-boot fat jar.

Option-1

```<code>java -jar -Dspring.config.location=file:\\\C:/application-myconfig.yml aplication1.jar
</code>```

Option-2

```<code>java -jar -Dspring.config.location=file:\\\C:/application_myconfig.yml aplication1.jar
</code>```

Option-3

```<code>java -jar -Dspring.config.location=file:\\\C:/applicationmyconfig.yml aplication1.jar
</code>```

The strange thing is Option-1 and Option-2 does not work. It is cannot find/load config file.

Only Option-3 is work for me.

My question is Can we use spring-boot config file name with dash - or underscore _?

答:
when it comes to naming convention, you can use hyphen (-) in case of both yml and properties file for spring boot application, you can refer below the spring documentation. Refer to the section

24.7.4 YAML Shortcomings

Regarding naming convention of names in yml file, refer to the table

Table 24.1. relaxed binding

Link : https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html

Also refer below, spring says to quote

If you use environment variables rather than system properties, most operating systems disallow period-separated key names, but you can use underscores instead (for example, SPRING_CONFIG_NAME instead of spring.config.name)

Body:
I am trying to running springboot-2.x fat jar in window by using external configuration.

I have three different external config file like:

C:\application-myconfig.yml
C:\application_myconfig.yml
C:\applicationmyconfig.yml

the configuration is :

server:
  servlet:
    contextPath: /application1

mymessage: this is test message

In my window, I run the following commend to run spring-boot fat jar.

Option-1

java -jar -Dspring.config.location=file:\\\C:/application-myconfig.yml aplication1.jar

Option-2

java -jar -Dspring.config.location=file:\\\C:/application_myconfig.yml aplication1.jar

Option-3

java -jar -Dspring.config.location=file:\\\C:/applicationmyconfig.yml aplication1.jar

The strange thing is Option-1 and Option-2 does not work. It is cannot find/load config file.

Only Option-3 is work for me.

My question is Can we use spring-boot config file name with dash - or underscore _?


问:
Can't display 2 partials on one page
I’m trying to do the "simple todo list" task, but I don’t know how to display it on one page as on screenshot http://joxi.net/v29DKEVcBLB5mG (that is, there is a list of saved items and to the right is a form for adding a new one). If everything is separate it works for me, but when it renders 2 partial on one page - error undefined method each for #<Track:0x00007f8fc42c2698> (NoMethodError in Tracks#new)
Here is my new.html.erb

```<code><h1> Create a New Item!</h1>
<%= render 'table' %>
<%= render 'form' %>
</code>```

Table partial:

```<code><table border="1">
  <thead>
    <tr>
      <th>ID</th>
      <th>All Tracks</th>
      <th>It's description</th>
      <th>Priority</th>
      <th>Date</th>
      <th>Delete</th>
      <th>Restore</th>
    </tr>
  </thead>
  <tbody>
    <% @track.each do |track| %>
    <tr>
      <td> <%= track.id %> </td>
      <td> <%= link_to track.item, edit_track_path(track.id) %> </td>
      <td> <%= track.description %> </td>
      <td> <%= track.priority %> </td>
      <td> <%= track.created_at.strftime('%d/%m/%Y') %> </td>
      <td><%= button_to "Delete", track_path(track.id), method: :delete %></td>
      <td><%= button_to "Restore", track_path(track.id), method: :put %></td>
    </tr>
    <% end %>
  </tbody>
</table>
</code>```

And _form partial:

```<code>  <%= form_for @track do |f| %>
  <p>
    <%= f.label :item %><br>
    <%= f.text_field :item %>
  </p>
  <p>
    <%= f.label :description %><br>
    <%= f.text_area :description %>
  </p>
  <p>
    <%= f.select :priority, priorities,
        prompt: "Select priority" %>
  </p>
  <p>
    <%= f.submit %>
  </p>
  <% end %>
    <%= link_to 'Back', tracks_path %>
    <%= link_to 'Home', root_path %>
</code>```

And Tracks controller:

```<code>class TracksController < ApplicationController
  before_action :find_track, only: [:show, :edit, :update, :destroy]

  def index
    @track = Track.all
  end

  def show
  end

  def new
    @track = Track.new
  end

  def create
    @track = Track.new(track_params)
    if @track.save
      flash[:success] = "It works!"
      redirect_to tracks_path
    else
      flash[:success] = "Its wrong!"
      render 'new'
    end
  end

  def update
    if @track.update(track_params)
      redirect_to @track
    else
      render 'edit'
    end
  end

  def edit
  end

  def destroy
    @track.destroy
    redirect_to tracks_path
  end

private
  def track_params
    params.require(:track).permit(:item, :description, :priority)
  end

  def find_track
    @track = Track.find(params[:id])
  end
end
</code>```

Thanks in advance!

答:
In controller try to use @tracks for multiple records.

```<code>  def index
    @tracks = Track.all
  end
</code>```

In Table partial use the below

```<code><table border="1">
  <thead>
    <tr>
      <th>ID</th>
      <th>All Tracks</th>
      <th>It's description</th>
      <th>Priority</th>
      <th>Date</th>
      <th>Delete</th>
      <th>Restore</th>
    </tr>
  </thead>
  <tbody>
    <% @tracks.each do |track| %>
    <tr>
      <td> <%= track.id %> </td>
      <td> <%= link_to track.item, edit_track_path(track.id) %> </td>
      <td> <%= track.description %> </td>
      <td> <%= track.priority %> </td>
      <td> <%= track.created_at.strftime('%d/%m/%Y') %> </td>
      <td><%= button_to "Delete", track_path(track.id), method: :delete %></td>
      <td><%= button_to "Restore", track_path(track.id), method: :put %></td>
    </tr>
    <% end %>
  </tbody>
</table>
</code>```

You have used @track for single and multiple records. Try to use it @tracks for multiple records and @track for single object.

Title: Can't display 2 partials on one page

Body:
I’m trying to do the "simple todo list" task, but I don’t know how to display it on one page as on screenshot http://joxi.net/v29DKEVcBLB5mG (that is, there is a list of saved items and to the right is a form for adding a new one). If everything is separate it works for me, but when it renders 2 partial on one page - error undefined method each for #<Track:0x00007f8fc42c2698> (NoMethodError in Tracks#new)
Here is my new.html.erb

 Create a New Item!

<%= render 'table' %>
<%= render 'form' %>

Table partial:

      ID
      All Tracks
      It's description
      Priority
      Date
      Delete
      Restore

    <% @track.each do |track| %>

       <%= track.id %>
       <%= link_to track.item, edit_track_path(track.id) %>
       <%= track.description %>
       <%= track.priority %>
       <%= track.created_at.strftime('%d/%m/%Y') %>
      <%= button_to "Delete", track_path(track.id), method: :delete %>
      <%= button_to "Restore", track_path(track.id), method: :put %>

    <% end %>

And _form partial:

  <%= form_for @track do |f| %>

    <%= f.label :item %>

    <%= f.text_field :item %>

    <%= f.label :description %>

    <%= f.text_area :description %>

    <%= f.select :priority, priorities,
        prompt: "Select priority" %>

    <%= f.submit %>

  <% end %>
    <%= link_to 'Back', tracks_path %>
    <%= link_to 'Home', root_path %>

And Tracks controller:

class TracksController < ApplicationController
  before_action :find_track, only: [:show, :edit, :update, :destroy]

  def index
    @track = Track.all
  end

  def show
  end

  def new
    @track = Track.new
  end

  def create
    @track = Track.new(track_params)
    if @track.save
      flash[:success] = "It works!"
      redirect_to tracks_path
    else
      flash[:success] = "Its wrong!"
      render 'new'
    end
  end

  def update
    if @track.update(track_params)
      redirect_to @track
    else
      render 'edit'
    end
  end

  def edit
  end

  def destroy
    @track.destroy
    redirect_to tracks_path
  end

private
  def track_params
    params.require(:track).permit(:item, :description, :priority)
  end

  def find_track
    @track = Track.find(params[:id])
  end
end

Thanks in advance!

Body:
In controller try to use @tracks for multiple records.

  def index
    @tracks = Track.all
  end

In Table partial use the below

<table border="1">
  <thead>
    <tr>
      <th>ID</th>
      <th>All Tracks</th>
      <th>It's description</th>
      <th>Priority</th>
      <th>Date</th>
      <th>Delete</th>
      <th>Restore</th>
    </tr>
  </thead>
  <tbody>
    <% @tracks.each do |track| %>
    <tr>
      <td> <%= track.id %> </td>
      <td> <%= link_to track.item, edit_track_path(track.id) %> </td>
      <td> <%= track.description %> </td>
      <td> <%= track.priority %> </td>
      <td> <%= track.created_at.strftime('%d/%m/%Y') %> </td>
      <td><%= button_to "Delete", track_path(track.id), method: :delete %></td>
      <td><%= button_to "Restore", track_path(track.id), method: :put %></td>
    </tr>
    <% end %>
  </tbody>
</table>

You have used @track for single and multiple records. Try to use it @tracks for multiple records and @track for single object.


答:
```<code>  $("#image_div").dialog({
      height:500,
      width:600,
      maxHeight: 700,
      minWidth: 700,
      modal: true,
      title:'Crop Your Profile Image',
      close: function() {
        //your event
      },
      buttons : {...}
  });
</code>```

Title: How to trigger an event when any jQuery UI dialog is closed?

Body:
I would like to make it so that when a jQuery UI dialog is closed, the document's focus event is fired. This would preferably not be tied to each dialog but to the page itself whenever any dialog closes.

How can I do this?


问:
How to read a MutableList<String> to Parcelable?
I have a class User that implements the Parcelable interface. User also has a property of type MutableList<String>. I would like to know how to read/write this type for Parcelable.

Here's my code so far

```<code>data class User(
    val contactNumber: String,
    val email: String,
    val fullName: String,
    var instanceToken: String,
    val isAdmin: Boolean,
    val isValid: Boolean,
    val organization: String,
    val registrationTokens: MutableList<String>,
    val uid: String,
    val unitNumber: String
) : Parcelable {

    constructor(source: Parcel) : this(
        source.readString() ?: "",
        source.readString() ?: "",
        source.readString() ?: "",
        source.readString() ?: "",
        source.readBoolean(),
        source.readBoolean(),
            source.readString() ?: "",
            source.readStringList(),
            source.readString() ?: "",
        source.readString() ?: ""
    )

    override fun writeToParcel(dest: Parcel?, flags: Int) {
        dest?.let {
            it.writeString(contactNumber)
            it.writeString(email)
            it.writeString(fullName)
            it.writeString(instanceToken)
            it.writeBoolean(isAdmin)
            it.writeBoolean(isValid)
            it.writeString(organization)
            it.writeStringList(registrationTokens)
            it.writeString(uid)
            it.writeString(unitNumber)
        }

    }
</code>```

For the write part, there's a writeStringList() method which is convenient. But for the read part, the provided readStringList() does not actually return MutableList<String>. It only returns Unit / void. Hence, it spits out a compilation error.

What is the proper way of doing this?

答: Use createStringArrayList(). readStringList is intended to reuse a single List instead of creating a new one each time, this isn't what you want here.

Body:
I have a class User that implements the Parcelable interface. User also has a property of type MutableList<String>. I would like to know how to read/write this type for Parcelable.

Here's my code so far

data class User(
    val contactNumber: String,
    val email: String,
    val fullName: String,
    var instanceToken: String,
    val isAdmin: Boolean,
    val isValid: Boolean,
    val organization: String,
    val registrationTokens: MutableList<String>,
    val uid: String,
    val unitNumber: String
) : Parcelable {

    constructor(source: Parcel) : this(
        source.readString() ?: "",
        source.readString() ?: "",
        source.readString() ?: "",
        source.readString() ?: "",
        source.readBoolean(),
        source.readBoolean(),
            source.readString() ?: "",
            source.readStringList(),
            source.readString() ?: "",
        source.readString() ?: ""
    )

    override fun writeToParcel(dest: Parcel?, flags: Int) {
        dest?.let {
            it.writeString(contactNumber)
            it.writeString(email)
            it.writeString(fullName)
            it.writeString(instanceToken)
            it.writeBoolean(isAdmin)
            it.writeBoolean(isValid)
            it.writeString(organization)
            it.writeStringList(registrationTokens)
            it.writeString(uid)
            it.writeString(unitNumber)
        }

    }

For the write part, there's a writeStringList() method which is convenient. But for the read part, the provided readStringList() does not actually return MutableList<String>. It only returns Unit / void. Hence, it spits out a compilation error.

What is the proper way of doing this?


问:
ajaxControlToolkit additionalUploadFileExtensions where to position in web. config file
I need to be able to import .msg files with the ajaxToolkit:AjaxFileUpload control. I have read various articles saying that I need to add the following to my web.config file.

```<code><ajaxControlToolKit additionalUploadFileExtensions="msg" />
</code>```

I am not sure where to place it in the config file as where ever I try and add it I get the following error:

HTTP Error 500.19 - Internal Server Error

The requested page cannot be accessed because the related configuration data for the page is invalid.

TIA

```<code><?xml version="1.0" encoding="utf-8"?>

<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.6.1" />
    <httpRuntime targetFramework="4.6.1" />
    <sessionState mode="InProc" timeout="20" />
    <pages>
      <namespaces>
        <add namespace="System.Web.Optimization" />
      </namespaces>
      <controls>
        <add assembly="Microsoft.AspNet.Web.Optimization.WebForms" namespace="Microsoft.AspNet.Web.Optimization.WebForms" tagPrefix="webopt" />
      <add tagPrefix="ajaxToolkit" assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" /></controls>
    </pages>
    <httpModules>
      <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" />
    </httpModules>
    <customErrors mode="Off"></customErrors>
    <authentication mode="Windows"></authentication>
    <httpHandlers>
      <add verb="*" path="AjaxFileUploadHandler.axd"
        type="AjaxControlToolkit.AjaxFileUploadHandler,
          AjaxControlToolkit"/>
    </httpHandlers>
  </system.web>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="Newtonsoft.Json" culture="neutral" publicKeyToken="30ad4fe6b2a6aeed" />
        <bindingRedirect oldVersion="0.0.0.0-10.0.0.0" newVersion="10.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="WebGrease" culture="neutral" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-1.6.5135.21930" newVersion="1.6.5135.21930" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Diagnostics.DiagnosticSource" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-4.0.2.1" newVersion="4.0.2.1" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Antlr3.Runtime" publicKeyToken="eb42632606e9261f" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-3.5.0.2" newVersion="3.5.0.2" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
  <system.webServer>
    <validation validateIntegratedModeConfiguration="false" />
    <modules>
      <remove name="TelemetryCorrelationHttpModule" />
      <add name="TelemetryCorrelationHttpModule" type="Microsoft.AspNet.TelemetryCorrelation.TelemetryCorrelationHttpModule, Microsoft.AspNet.TelemetryCorrelation" preCondition="integratedMode,managedHandler" />
      <remove name="ApplicationInsightsWebTracking" />
      <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" preCondition="managedHandler" />
    </modules>
  <handlers>
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <remove name="OPTIONSVerbHandler" />
      <remove name="TRACEVerbHandler" />
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    <add name="AjaxFileUploadHandler" verb="*" path="AjaxFileUploadHandler.axd" type="AjaxControlToolkit.AjaxFileUploadHandler, AjaxControlToolkit" />
    </handlers>
  </system.webServer>
  <connectionStrings>
  </connectionStrings>

  <system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.7.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:1659;1699;1701" />
      <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.7.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+" />
    </compilers>
  </system.codedom>
  <system.net>
    <mailSettings>
      <smtp deliveryMethod="Network">
      </smtp>
    </mailSettings>
  </system.net>
  <appSettings>
  </appSettings>
  <ajaxControlToolkit additionalUploadFileExtensions="msg" />

</configuration>
</code>```

答:
You need to ad the config section in your web.config:</p>

```<code> <configSections>
<section name="ajaxControlToolkit" type="AjaxControlToolkit.AjaxControlToolkitConfigSection, AjaxControlToolkit" requirePermission="false"/>
</configSections>
<ajaxControlToolkit additionalUploadFileExtensions="msg" /> ```

</code>```

Body:
I need to be able to import .msg files with the ajaxToolkit:AjaxFileUpload control. I have read various articles saying that I need to add the following to my web.config file.

<ajaxControlToolKit additionalUploadFileExtensions="msg" />

I am not sure where to place it in the config file as where ever I try and add it I get the following error:

HTTP Error 500.19 - Internal Server Error

The requested page cannot be accessed because the related configuration data for the page is invalid.

TIA

<?xml version="1.0" encoding="utf-8"?>

<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.6.1" />
    <httpRuntime targetFramework="4.6.1" />
    <sessionState mode="InProc" timeout="20" />
    <pages>
      <namespaces>
        <add namespace="System.Web.Optimization" />
      </namespaces>
      <controls>
        <add assembly="Microsoft.AspNet.Web.Optimization.WebForms" namespace="Microsoft.AspNet.Web.Optimization.WebForms" tagPrefix="webopt" />
      <add tagPrefix="ajaxToolkit" assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" /></controls>
    </pages>
    <httpModules>
      <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" />
    </httpModules>
    <customErrors mode="Off"></customErrors>
    <authentication mode="Windows"></authentication>
    <httpHandlers>
      <add verb="*" path="AjaxFileUploadHandler.axd"
        type="AjaxControlToolkit.AjaxFileUploadHandler,
          AjaxControlToolkit"/>
    </httpHandlers>
  </system.web>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="Newtonsoft.Json" culture="neutral" publicKeyToken="30ad4fe6b2a6aeed" />
        <bindingRedirect oldVersion="0.0.0.0-10.0.0.0" newVersion="10.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="WebGrease" culture="neutral" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-1.6.5135.21930" newVersion="1.6.5135.21930" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Diagnostics.DiagnosticSource" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-4.0.2.1" newVersion="4.0.2.1" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Antlr3.Runtime" publicKeyToken="eb42632606e9261f" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-3.5.0.2" newVersion="3.5.0.2" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
  <system.webServer>
    <validation validateIntegratedModeConfiguration="false" />
    <modules>
      <remove name="TelemetryCorrelationHttpModule" />
      <add name="TelemetryCorrelationHttpModule" type="Microsoft.AspNet.TelemetryCorrelation.TelemetryCorrelationHttpModule, Microsoft.AspNet.TelemetryCorrelation" preCondition="integratedMode,managedHandler" />
      <remove name="ApplicationInsightsWebTracking" />
      <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" preCondition="managedHandler" />
    </modules>
  <handlers>
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <remove name="OPTIONSVerbHandler" />
      <remove name="TRACEVerbHandler" />
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    <add name="AjaxFileUploadHandler" verb="*" path="AjaxFileUploadHandler.axd" type="AjaxControlToolkit.AjaxFileUploadHandler, AjaxControlToolkit" />
    </handlers>
  </system.webServer>
  <connectionStrings>
  </connectionStrings>

  <system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.7.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:1659;1699;1701" />
      <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.7.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+" />
    </compilers>
  </system.codedom>
  <system.net>
    <mailSettings>
      <smtp deliveryMethod="Network">
      </smtp>
    </mailSettings>
  </system.net>
  <appSettings>
  </appSettings>
  <ajaxControlToolkit additionalUploadFileExtensions="msg" />

</configuration>

Body:
You need to ad the config section in your web.config:

 <configSections>
<section name="ajaxControlToolkit" type="AjaxControlToolkit.AjaxControlToolkitConfigSection, AjaxControlToolkit" requirePermission="false"/>
</configSections>
<ajaxControlToolkit additionalUploadFileExtensions="msg" /> ```


问:
Strawberry Perl - Search and replace in Windows
I am trying to execute the following command:

perl -pi -e 's,vaadin-element,color-picker,g' *.* demo/* test/* src/* theme/*/*

(following this document)

Unfortunately it seems that the window distribution of pearl I use has some issues with the command, as I get the following error:

```<code>Can't open *.*: Invalid argument.
Can't open demo/*: Invalid argument.
Can't open test/*: Invalid argument.
Can't open src/*: Invalid argument.
Can't open theme/*/*: Invalid argument.
</code>```

Any suggestions on how to fix that?
Thank you in advance!

Disclaimer: I never used pearl before and have absolutely no experience.

答:
In Unix-derived operating systems, the shell expands globs like *.*, and provides the command line as an array of strings to the program.

In Windows, the command line is a single string, and it is up to the program to interpret what it means, including things like quote characters and globs. If the program is a normal C program, the C runtime interprets command line, and expands the globs, and passes an array of strings to main. This is because the C standard requires this.

However Perl is not C. Use the File::Glob library to expand the arguments.

Body:
I am trying to execute the following command:

perl -pi -e 's,vaadin-element,color-picker,g' *.* demo/* test/* src/* theme/*/*

(following this document)

Unfortunately it seems that the window distribution of pearl I use has some issues with the command, as I get the following error:

Can't open *.*: Invalid argument.
Can't open demo/*: Invalid argument.
Can't open test/*: Invalid argument.
Can't open src/*: Invalid argument.
Can't open theme/*/*: Invalid argument.

Any suggestions on how to fix that?
Thank you in advance!

Disclaimer: I never used pearl before and have absolutely no experience.


问:
Not able to execute the Synchronous Request Response example in Siddhi
I'm trying to run the sample code given in the WSO2 Siddhi documentation.

I've replicated what was given there.

```<code>@App:name("Http_Request_Response_Tutorial")
@App:description("This app demonstrate the usage of http request sink and http response source")

@source(type='http-response' ,sink.id='cardTypeSink',
@map(type='xml', namespaces = "xmlns=http://localhost/SmartPayments/",
@attributes(creditCardNo = 'trp:creditCardNo',creditCardType = ".")))
@sink(type='log')
define stream EnrichedCreditCardStream (creditCardNo string,creditCardType string);

@sink(type='http-request',publisher.url='https://secure.ftipgw.com/ArgoFire/validate.asmx/GetCardType',method='POST', headers="'Content-Type:application/x-www-form-urlencoded'",
sink.id="cardTypeSink",
@map(type='keyvalue', @payload(CardNumber='{{creditCardNo}}')))
define stream CreditCardStream (creditCardNo string);
</code>```

In the Event Simulator tab, I passed the values given in the example namely: 154467847759 in the timestamp field and 5555555555554444 in the creditCardNo(STRING).

This is the error that's coming.

```<code>[2019-05-22_14-59-14_632] ERROR {org.wso2.extension.siddhi.io.http.source.HttpResponseMessageListener} - No source of type 'http-response' for status code '500' has been defined. Hence dropping the response message. (Encoded)
</code>```

答:
As per the error printed, the request sent to https://secure.ftipgw.com/ArgoFire/validate.asmx/GetCardType returns a 500 response.
As you don't have an http-response source to accept 500 responses, the response payload will be dropped.

The behavior you are observing is not reproducable from our end. The tutorial works correctly as demonstrated.

Below is an amended version of the tutorial sample with a dummy endpoint. You can try it.

```<code>@App:name("Http_Request_Response_Tutorial")
@App:description("This app demonstrate the usage of http request sink and http response source")

@source(type='http-response' ,sink.id='cardTypeSink',
@map(type='xml', namespaces = "xmlns=http://localhost/SmartPayments/",
@attributes(creditCardNo = 'trp:creditCardNo',creditCardType = ".")))
@sink(type='log')
define stream EnrichedCreditCardStream (creditCardNo string,creditCardType string);

@sink(type='http-request',publisher.url='http://www.mocky.io/v2/5cee2fa1300000013a6e9961',method='POST', headers="'Content-Type:application/x-www-form-urlencoded'",
sink.id="cardTypeSink",
@map(type='keyvalue', @payload(CardNumber='{{creditCardNo}}')))
define stream CreditCardStream (creditCardNo string);
</code>```

Body:
I'm trying to run the sample code given in the WSO2 Siddhi documentation.

I've replicated what was given there.

@App:name("Http_Request_Response_Tutorial")
@App:description("This app demonstrate the usage of http request sink and http response source")

@source(type='http-response' ,sink.id='cardTypeSink',
@map(type='xml', namespaces = "xmlns=http://localhost/SmartPayments/",
@attributes(creditCardNo = 'trp:creditCardNo',creditCardType = ".")))
@sink(type='log')
define stream EnrichedCreditCardStream (creditCardNo string,creditCardType string);

@sink(type='http-request',publisher.url='https://secure.ftipgw.com/ArgoFire/validate.asmx/GetCardType',method='POST', headers="'Content-Type:application/x-www-form-urlencoded'",
sink.id="cardTypeSink",
@map(type='keyvalue', @payload(CardNumber='{{creditCardNo}}')))
define stream CreditCardStream (creditCardNo string);

In the Event Simulator tab, I passed the values given in the example namely: 154467847759 in the timestamp field and 5555555555554444 in the creditCardNo(STRING).

This is the error that's coming.

[2019-05-22_14-59-14_632] ERROR {org.wso2.extension.siddhi.io.http.source.HttpResponseMessageListener} - No source of type 'http-response' for status code '500' has been defined. Hence dropping the response message. (Encoded)

Body:
As per the error printed, the request sent to https://secure.ftipgw.com/ArgoFire/validate.asmx/GetCardType returns a 500 response.
As you don't have an http-response source to accept 500 responses, the response payload will be dropped.

The behavior you are observing is not reproducable from our end. The tutorial works correctly as demonstrated.

Below is an amended version of the tutorial sample with a dummy endpoint. You can try it.

@App:name("Http_Request_Response_Tutorial")
@App:description("This app demonstrate the usage of http request sink and http response source")

@source(type='http-response' ,sink.id='cardTypeSink',
@map(type='xml', namespaces = "xmlns=http://localhost/SmartPayments/",
@attributes(creditCardNo = 'trp:creditCardNo',creditCardType = ".")))
@sink(type='log')
define stream EnrichedCreditCardStream (creditCardNo string,creditCardType string);

@sink(type='http-request',publisher.url='http://www.mocky.io/v2/5cee2fa1300000013a6e9961',method='POST', headers="'Content-Type:application/x-www-form-urlencoded'",
sink.id="cardTypeSink",
@map(type='keyvalue', @payload(CardNumber='{{creditCardNo}}')))
define stream CreditCardStream (creditCardNo string);