tjanczuk / edge

Run .NET and Node.js code in-process on Windows, MacOS, and Linux
http://tjanczuk.github.io/edge
Other
5.42k stars 641 forks source link

Could not load type 'Startup' from assembly #702

Closed gokturk413 closed 4 years ago

gokturk413 commented 4 years ago

Error: Could not load type 'Startup' from assembly 'nj5lcfow, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. at Object.exports.func (C:\Users\Administrator\Desktop\edgejs\edge-js-master\edge-js-master\lib\edge.js:182:17) at Object. (C:\Users\Administrator\Desktop\edgejs\edge-js-master\edge-js-master\samples\test2.js:3:24) at Module._compile (module.js:653:30) at Object.Module._extensions..js (module.js:664:10) at Module.load (module.js:566:32) at tryModuleLoad (module.js:506:12) at Function.Module._load (module.js:498:3) at Function.Module.runMain (module.js:694:10) at startup (bootstrap_node.js:204:16) at bootstrap_node.js:625:3

for my code var edge = require('../lib/edge');

var inlineC = edge.func({
    source: function () {/* 

    using System;

using Opc.Ua; // Install-Package OPCFoundation.NetStandard.Opc.Ua using Opc.Ua.Client; using Opc.Ua.Configuration; //using System.Windows.Forms; using System.Collections;

class Program
{
    //private const string DiscoveryUrl = "opc.tcp://172.16.10.62:4846";
    //private const string DiscoveryUrl = "opc.tcp://DESKTOP-35D3VE0:48010";
    //private const string DiscoveryUrl = "opc.tcp://172.16.10.65:4846";
    private const string DiscoveryUrl = "opc.tcp://desktop-pbant82:62541";

    static int lineCount = 0;
    static int totalNodes = 0;
    static int netCalls = 0;
    static int reconnectPeriod_ = 0;
    static DateTime startTime;
    static DateTime lastCheckTime;

    private static Hashtable m_hashAttributeNames = null;
    static Subscription subscription;
    private static MonitoredItem monitoredItem;
    static BrowseResultCollection nodeList = new BrowseResultCollection();
    static SessionReconnectHandler reconnectHandler_;
    static Session session;
    private static DataValueCollection m_currentValues;
    static  ReferenceDescriptionCollection  refdescriptioncollist;
    static void Main(string[] args)
    {

        Console.WriteLine("Create application configuration and certificate, start connection and extraction...");
        var config = new ApplicationConfiguration()
        {
            ApplicationName = "UABenchMarks",
            ApplicationUri = Utils.Format(@"urn:{0}:UABenchMarks", System.Net.Dns.GetHostName()),
            ApplicationType = ApplicationType.Client,
            ServerConfiguration = new ServerConfiguration
            {
                MaxSubscriptionCount = 100000,
                MaxMessageQueueSize = 1000000,
                MaxNotificationQueueSize = 1000000,
                MaxPublishRequestCount = 10000000,
            },
            SecurityConfiguration = new SecurityConfiguration
            {
                ApplicationCertificate = new CertificateIdentifier { StoreType = @"Directory", StorePath = @"%CommonApplicationData%\OPC Foundation\CertificateStores\MachineDefault", SubjectName = Utils.Format(@"CN={0}, DC={1}", "MyHomework", System.Net.Dns.GetHostName()) },
                TrustedIssuerCertificates = new CertificateTrustList { StoreType = @"Directory", StorePath = @"%CommonApplicationData%\OPC Foundation\CertificateStores\UA Certificate Authorities" },
                TrustedPeerCertificates = new CertificateTrustList { StoreType = @"Directory", StorePath = @"%CommonApplicationData%\OPC Foundation\CertificateStores\UA Applications" },
                RejectedCertificateStore = new CertificateTrustList { StoreType = @"Directory", StorePath = @"%CommonApplicationData%\OPC Foundation\CertificateStores\RejectedCertificates" },
                AutoAcceptUntrustedCertificates = true,
                AddAppCertToTrustedStore = true
            },
            TransportConfigurations = new TransportConfigurationCollection(),
            TransportQuotas = new TransportQuotas {
                OperationTimeout = 6000000,
                MaxStringLength = int.MaxValue,
                MaxByteStringLength = int.MaxValue,
                MaxArrayLength = 65535,
                MaxMessageSize = 419430400,
                MaxBufferSize = 65535,
                ChannelLifetime = -1,
                SecurityTokenLifetime = -1
            },
            ClientConfiguration = new ClientConfiguration {
                DefaultSessionTimeout = -1,
                MinSubscriptionLifetime = -1,
            },
            TraceConfiguration = new TraceConfiguration()
        };
        config.Validate(ApplicationType.Client).GetAwaiter().GetResult();
        if (config.SecurityConfiguration.AutoAcceptUntrustedCertificates)
        {
            config.CertificateValidator.CertificateValidation += (s, e) => { e.Accept = (e.Error.StatusCode == StatusCodes.BadCertificateUntrusted); };
        }

        var application = new ApplicationInstance
        {
            ApplicationName = "UABenchMarks",
            ApplicationType = ApplicationType.Client,
            ApplicationConfiguration = config
        };
        application.CheckApplicationInstanceCertificate(false, 2048).GetAwaiter().GetResult();

        var selectedEndpoint = CoreClientUtils.SelectEndpoint(DiscoveryUrl, useSecurity: false, operationTimeout: 15000);

        session = Session.Create(config, new ConfiguredEndpoint(null, selectedEndpoint, EndpointConfiguration.Create(config)), false, "", 60000, null, null).GetAwaiter().GetResult();

        Browse();
        session.KeepAlive += new KeepAliveEventHandler(Session_KeepAlive);
        session.Notification += new NotificationEventHandler(Session_Notification);

        //Console.WriteLine("Step 4 - Create a subscription. Set a faster publishing interval if you wish.");

            //UpdateCurrentValues();
            MonitoredItems();
            //WriteValues();
        //UpdateCurrentValues();
            //Browse();
        //Console.WriteLine("Step 5 - Add a list of items you wish to monitor to the subscription.");

        //Console.WriteLine("Step 6 - Add the subscription to the session.");
        //session.AddSubscription(subscription);
        //subscription.Create();

        //Console.WriteLine("Press any key to remove subscription...");
        //Console.ReadKey(true);

        //session.KeepAlive += OnSessionKeepAliveEvent;

        Console.WriteLine("Press any key to exit...");
        Console.ReadKey(true);
    }

    private static void Session_KeepAlive(object sender, KeepAliveEventArgs e)
    {
        int reconnectPeriod_ = 10;
        Session session = (Session)sender;
        if (sender != null && session.Endpoint != null)
        {

            Console.WriteLine("Keepalive");
        }
        if (e != null && session != null)
        {
            if (ServiceResult.IsGood(e.Status))
            {
                Console.WriteLine(Utils.Format(
                "Server Status: {0} {1:yyyy-MM-dd HH:mm:ss} {2}/{3}",
                e.CurrentState,
                e.CurrentTime.ToLocalTime(),
                session.OutstandingRequestCount,
                session.DefunctRequestCount));
            }
            else
            {
                Console.WriteLine(String.Format(
                "{0} {1}/{2}", e.Status,
                session.OutstandingRequestCount,
                session.DefunctRequestCount));                  
                if (reconnectPeriod_ <= 0)
                {
                    return;
                }

                if (reconnectHandler_ == null && reconnectPeriod_ > 0)
                {
                    reconnectHandler_ = new SessionReconnectHandler();
                    reconnectHandler_.BeginReconnect(session, reconnectPeriod_ * 1000, OnServerReconnectComplete);
                }
            }
        }
    }

    private static void OnServerReconnectComplete(object sender, EventArgs e)
    {
        try
        {
            // ignore callbacks from discarded objects.
            if (!Object.ReferenceEquals(sender, reconnectHandler_))
            {
                return;
            }
            session = reconnectHandler_.Session;
            reconnectHandler_.Dispose();
            reconnectHandler_ = null;
            Session_KeepAlive(session, null);
        }
        catch (Exception exception)
        {
            //GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception);
        }
    }

    public static void Browse()
    {

        var browser = new Browser(session)
        {
            BrowseDirection = BrowseDirection.Forward,
            ReferenceTypeId = ReferenceTypeIds.HierarchicalReferences,
            IncludeSubtypes = true,
            NodeClassMask = 0,
            ContinueUntilDone = false,
        };
        // Browse from the RootFolder
        ReferenceDescriptionCollection references = browser.Browse(Objects.ObjectsFolder);
        GetElements(session, browser, 0, references);            
    }

    private static void GetElements(Session session, Browser browser, uint level, ReferenceDescriptionCollection references)
    {
        var spaces = "";
        for (int i = 0; i <= level; i++)
        {
            spaces += " ";
        }
        // Iterate through the references and print the variables
        foreach (ReferenceDescription reference in references)
        {
            // make sure the type definition is in the cache.
            session.NodeCache.Find(reference.ReferenceTypeId);
            switch (reference.NodeClass)
            {
                case NodeClass.Object:
                    Console.WriteLine(spaces + "+ " + reference.DisplayName);
                    break;
                default:
                    Console.WriteLine(spaces + "- " + reference.DisplayName);
                    break;
            }
            if (reference.DisplayName.Text=="Omni")
            {
                refdescriptioncollist = browser.Browse((NodeId)reference.NodeId);

                level += 1;
                GetElements(session, browser, level, refdescriptioncollist);
                level -= 1;
            }
            var subReferences = browser.Browse((NodeId)reference.NodeId);
            level += 1;
            GetElements(session, browser, level, subReferences);
            level -= 1;
        }
    }

    private static void MonitoredItems()
    {
        try
        {
            // Retrieve the event data and create the according nodeid. 
            String sNodeId = "ns=2;1100_bool"; //(String)e.Data.GetData(typeof(System.String));
            NodeId nodeId = new NodeId(sNodeId);

            // Create the subscription if it does not already exist.
            if (subscription == null)
            {
                subscription = new Subscription(session.DefaultSubscription)
                {
                    DisplayName = "My Subscription Name",
                    PublishingEnabled = true,
                    PublishingInterval = 100, // in milliseconds.
                    KeepAliveCount = 10,   // 10*UaRefreshRate  = 5s if UaRefreshRate = 500
                    LifetimeCount = 100,  // UaRefreshRate*100 = 50s if UaRefreshRate = 500;
                    MaxNotificationsPerPublish = 100
                };
                // Associate the subscription with the session.            
                session.AddSubscription(subscription);
                // Call the server and create the subscription.
                subscription.Create();
                // At this point the subscription is sending publish requests at the keep alive rate.
                // Use the Notification event the session to receive updates when a publish completes.

            }
            // Add the attribute name/value to the list view.
            //ListViewItem item = new ListViewItem(sNodeId);
            object serverHandle = null;

            try
            {
                if (monitoredItem == null)
                {
                    foreach (var descrpt in refdescriptioncollist) 
                    {
                        string abc = descrpt.NodeId.ToString();

                        monitoredItem = new MonitoredItem(subscription.DefaultItem);
                        monitoredItem.StartNodeId = descrpt.NodeId.ToString();
                        monitoredItem.AttributeId = Attributes.Value;
                        monitoredItem.MonitoringMode = MonitoringMode.Reporting;
                        monitoredItem.SamplingInterval = 100;
                        monitoredItem.QueueSize = 0;
                        monitoredItem.DiscardOldest = true;
                        // define event handler for this item, and then add to subscription
                        monitoredItem.Notification += new MonitoredItemNotificationEventHandler(monitoring_Notification);
                        subscription.AddItem(monitoredItem);
                        subscription.ApplyChanges();
                    }
                }
            }
            catch (ServiceResultException monitoredItemResult)
            {

            }

        }
        catch (Exception exception)
        {

        }
    }

    static void monitoring_Notification(MonitoredItem monitoredItem, MonitoredItemNotificationEventArgs e)
    {
        try
        {

            MonitoredItemNotification datachange = e.NotificationValue as MonitoredItemNotification;

            if (datachange == null)
            {
                return;
            }

            Console.WriteLine(monitoredItem.StartNodeId + " : " + datachange.Value.WrappedValue.ToString());
        }
        catch (Exception exception)
        {
            //ClientUtils.HandleException(this.Text, exception);
        }

    }

    private static void Session_Notification(Session session, NotificationEventArgs e)
    {
        NotificationMessage message = e.NotificationMessage;

        // Check for keep alive.
        if (message.NotificationData.Count == 0)
        {
            return;
        }

        // Get the data changes (oldest to newest).
        foreach (MonitoredItemNotification datachange in message.GetDataChanges(false))
        {
            // Lookup the monitored item.
            MonitoredItem monitoredItem = e.Subscription.FindItemByClientHandle(datachange.ClientHandle);

            if (monitoredItem == null)
            {
                continue;
            }

            //ClientMonitoredItemData clientData = monitoredItem.Handle as ClientMonitoredItemData;

            //clientData.callback(clientData.clientHandle, datachange.Value);
        }
    }

}

*/},
    references: ['BouncyCastle.Crypto.dll','OPC.UA.Core.dll','Opc.Ua.Client.dll','Opc.Ua.Configuration.dll','System.IdentityModel.dll','System.Xml.dll']
});

var add7 = edge.func('OPC.UA.Core.dll');

inlineC (null, function (e, r) {
    if (e) throw error;
    console.log(r);
});
hilaliMoncef commented 4 years ago

Hi!

I am having the exact same issue. Any idea of how to solve this ? Thanks.

gokturk413 commented 4 years ago

I correct this error like this i create in my dll such method

And my namespace is

namespace KonsoleBrowseDll { public class Program { public async Task Invoke(dynamic input) { return "test"; } } } then you insert in nodejs function typeName: "KonsoleBrowseDll.Program", methodName: "Invoke",