public static OpcuaSessionConfig LoadFromJsonFile(string path)
        {
            OpcuaSessionConfig result = null;

            if (File.Exists(path))
            {
                string json = File.ReadAllText(path);
                if (json != null)
                {
                    JsonConvert.DefaultSettings = (() =>
                    {
                        var settings = new JsonSerializerSettings();
                        settings.Converters.Add(new StringEnumConverter {
                            CamelCaseText = true
                        });
                        return(settings);
                    });
                    try
                    {
                        result = JsonConvert.DeserializeObject <OpcuaSessionConfig>(json);
                    }
                    catch (Exception ex)
                    {
                        Utils.Trace(ex, "OpcuaSessionConfig.LoadFromJsonFile() Exception: " + ex.Message);
                    }
                }
            }
            return(result);
        }
Example #2
0
        /// <summary>
        /// On save button clicked
        /// -- save server connection settings and node subscription list
        ///    and exit this page, get back to main page
        /// <summary>
        private async void btnSave_Button_Click(object sender, RoutedEventArgs e)
        {
            EnableSessionOpButtons(false);
            OpcuaSessionConfig config         = null;
            var          sessionname          = m_design_session.SessionName;
            const string PROFILENAME_TEMPLATE = "session_{0}.json";

            if (sessionMgmtAction == SESSIONMGMT_ACTION.NEW)
            {
                sessionname = txtSessionName.Text;

                if (String.IsNullOrEmpty(sessionname))
                {
                    MessageDialog showDialog = new MessageDialog("Session Name must not be empty or duplicated.\nPlease enter a unique session name.");
                    showDialog.Commands.Add(new UICommand("OK")
                    {
                        Id = 1
                    });
                    showDialog.DefaultCommandIndex = 1;
                    showDialog.CancelCommandIndex  = 1;
                    var result = await showDialog.ShowAsync();

                    EnableSessionOpButtons(true);
                    return;
                }

                m_sessionConfig_full_path = Path.Combine(m_local, SiteProfileManager.GetFullPath(App.SiteProfileId, String.Format(PROFILENAME_TEMPLATE, sessionname)));
                while (File.Exists(m_sessionConfig_full_path))
                {
                    var timestamp = DateTime.Now.ToString("_yyMMddHHmmss");
                    sessionname = txtSessionName.Text + timestamp;
                    m_sessionConfig_full_path = Path.Combine(m_local, SiteProfileManager.GetFullPath(App.SiteProfileId, String.Format(PROFILENAME_TEMPLATE, sessionname)));
                }
            }
            config = SaveSessionConfig(m_sessionConfig_full_path, sessionname, m_design_session);

            if (config != null)
            {
                try
                {
                    if (sessionMgmtAction == SESSIONMGMT_ACTION.NEW)
                    {
                        sessionInfo.profilePath = String.Format(PROFILENAME_TEMPLATE, sessionname);
                        sessionInfo.sessionName = sessionname;
                        sessionInfo.sourceType  = m_design_session.Endpoint.Server.ApplicationName.ToString();
                        SiteProfileManager.DefaultSiteProfileManager.sessionConfig.sessions.Add(sessionInfo);
                        await SiteProfileManager.DefaultSiteProfileManager.SaveSessionConfig();
                    }
                    CloseSessionView_OpcuaClient();
                    Frame.Navigate(typeof(SessionMgmtPage), "RELOAD");
                }
                catch (Exception ex)
                {
                    Utils.Trace(ex, "SessionMgmt_OpcuaPage.btnSave_Button_Click() Exception: " + ex.Message);
                }
            }
            EnableSessionOpButtons(true);
        }
Example #3
0
        /// <summary>
        /// On reload button clicked
        /// -- reload configuration and refresh UI accordingly
        /// <summary>
        private void btnReload_Button_Click(object sender, RoutedEventArgs e)
        {
            EnableSessionOpButtons(false);
            CloseSessionView_OpcuaClient();
            m_sessionConfig = OpcuaSessionConfig.LoadFromJsonFile(m_sessionConfig_full_path);

            EndpointSelectorCTRL.IsEnabled = false;
            BrowseCTRL.IsEnabled           = false;
            SessionsCTRL.IsEnabled         = false;

            var ignored = Task.Run(OpenSessionView_OpcuaClient);
        }
        /// <summary>
        /// Invoked when the application is launched normally by the end user.  Other entry points
        /// will be used such as when the application is launched to open a specific file.
        /// </summary>
        /// <param name="e">Details about the launch request and process.</param>
        protected override async void OnLaunched(LaunchActivatedEventArgs e)
        {
            LoadAppSettings();

            // initialize all available session types
            await OpcuaSessionConfig.Init();

#if DEBUG
            if (System.Diagnostics.Debugger.IsAttached)
            {
                this.DebugSettings.EnableFrameRateCounter = true;
            }
#endif
            previousExecState = e.PreviousExecutionState;
            Debug.WriteLine("App OnLaunched: previous state = " + e.PreviousExecutionState.ToString());

            appActivationDesc = "App OnLaunched: previous state = " + e.PreviousExecutionState.ToString() + "\nkind=" + e.Kind.ToString();

            Frame rootFrame = Window.Current.Content as Frame;

            // Do not repeat app initialization when the Window already has content,
            // just ensure that the window is active
            if (rootFrame == null)
            {
                // Create a Frame to act as the navigation context and navigate to the first page
                rootFrame = new Frame();

                rootFrame.NavigationFailed += OnNavigationFailed;

                if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
                {
                    //TODO: Load state from previously suspended application
                }

                // Place the frame in the current Window
                Window.Current.Content = rootFrame;
            }

            if (e.PrelaunchActivated == false)
            {
                if (rootFrame.Content == null)
                {
                    // When the navigation stack isn't restored navigate to the first page,
                    // configuring the new page by passing required information as a navigation
                    // parameter
                    rootFrame.Navigate(typeof(MainPage), e.Arguments);
                }
                // Ensure the current window is active
                Window.Current.Activate();
            }

            Windows.ApplicationModel.Core.CoreApplication.Exiting += CoreApplication_Exiting;
        }
        public async Task <bool> SavePublishedNodes(string filePath = null)
        {
            bool isSuccess = false;

            try
            {
                string path = filePath;

                if (String.IsNullOrEmpty(path))
                {
                    path = DEFAULT_PUBLISHEDNODESPATH;
                }

                List <PublisherConfigurationFileEntry> publisherConfig = new List <PublisherConfigurationFileEntry>(sessionConfig.sessions.Count);

                foreach (var session in sessionConfig.sessions)
                {
                    PublisherConfigurationFileEntry configEntry = new PublisherConfigurationFileEntry();
                    var settingpath    = Path.Combine(ApplicationData.Current.LocalFolder.Path, GetFullPath(SiteProfileId, session.profilePath));
                    var sessionSetting = OpcuaSessionConfig.LoadFromJsonFile(settingpath);

                    configEntry.EndpointUri = sessionSetting.endpoint.EndpointUrl;
                    configEntry.UseSecurity = (sessionSetting.endpoint.Description.SecurityMode != Opc.Ua.MessageSecurityMode.None);
                    configEntry.OpcNodes    = new List <OpcNodeOnEndpointUrl>(sessionSetting.monitoredlist.Count);

                    foreach (var item in sessionSetting.monitoredlist)
                    {
                        OpcNodeOnEndpointUrl node = new OpcNodeOnEndpointUrl()
                        {
                            ExpandedNodeId = item.nodeid,
                            Name           = item.description,
                            Tag            = item.displayname
                        };
                        configEntry.OpcNodes.Add(node);
                    }
                    publisherConfig.Add(configEntry);
                }
                // save session config
                isSuccess = await SerializationUtil.SaveToJsonFile(GetFullPath(SiteProfileId, path), publisherConfig);
            }
            catch (Exception ex)
            {
                Utils.Trace(ex, "SiteProfileManager.SavePublishedNodes() Exception: " + ex.Message);
            }
            return(isSuccess);
        }
        // save to file in OpcPublisher legacy publishernodes format
        public async Task <bool> SavePublisherNodesLegacy(string filePath = null)
        {
            bool isSuccess = false;

            try
            {
                string path = filePath;

                if (String.IsNullOrEmpty(path))
                {
                    path = DEFAULT_PUBLISHEDNODESPATH;
                }

                List <PublishedNode> publisherNodes = new List <PublishedNode>(sessionConfig.sessions.Count);
                foreach (var session in sessionConfig.sessions)
                {
                    var settingpath    = Path.Combine(ApplicationData.Current.LocalFolder.Path, GetFullPath(SiteProfileId, session.profilePath));
                    var sessionSetting = OpcuaSessionConfig.LoadFromJsonFile(settingpath);

                    foreach (var item in sessionSetting.monitoredlist)
                    {
                        PublishedNode node = new PublishedNode()
                        {
                            EndpointUrl = sessionSetting.endpoint.EndpointUrl.ToString(),
                            NodeId      = new PublishedNodeId()
                            {
                                Identifier = item.nodeid
                            },
                            Name        = item.description,
                            Tag         = item.displayname,
                            UseSecurity = (sessionSetting.endpoint.Description.SecurityMode != Opc.Ua.MessageSecurityMode.None)
                        };
                        publisherNodes.Add(node);
                    }
                }
                // save session config
                isSuccess = await SerializationUtil.SaveToJsonFile(GetFullPath(SiteProfileId, path), publisherNodes);
            }
            catch (Exception ex)
            {
                Utils.Trace(ex, "SiteProfileManager.SavePublisherNodesLegacy() Exception: " + ex.Message);
            }
            return(isSuccess);
        }
Example #7
0
        /// <summary>
        /// save server connection settings and node subscription list to app storage
        /// <summary>
        private OpcuaSessionConfig SaveSessionConfig(string targetfile, string sesssionName, Session session)
        {
            OpcuaSessionConfig sessionConfig = null;

            if (session != null)
            {
                try
                {
                    sessionConfig = new OpcuaSessionConfig();

                    sessionConfig.timestamp       = DateTime.Now;
                    sessionConfig.endpoint        = session.ConfiguredEndpoint;
                    sessionConfig.sessionname     = sesssionName;
                    sessionConfig.monitoredlist   = new List <MonitoredNode>();
                    sessionConfig.publishinterval = session.DefaultSubscription.PublishingInterval;

                    NamespaceTable namespaceTable          = new NamespaceTable();
                    DataValue      namespaceArrayNodeValue = session.ReadValue(VariableIds.Server_NamespaceArray);
                    namespaceTable.Update(namespaceArrayNodeValue.GetValue <string[]>(null));

                    //collect monitored list
                    foreach (MonitoredItem x in session.DefaultSubscription.MonitoredItems)
                    {
                        int trimStartIndex = x.DisplayName.IndexOf(" (");
                        var displayName    = x.DisplayName.Substring(trimStartIndex + 2);
                        displayName = displayName.Remove(displayName.IndexOf(" -"));
                        var description = (trimStartIndex >= 0) ? x.DisplayName.Remove(trimStartIndex) : x.DisplayName;

                        ExpandedNodeId expendedId = NodeId.ToExpandedNodeId(x.StartNodeId, namespaceTable);
                        MonitoredNode  monnode    = new MonitoredNode(expendedId.ToString(), displayName, description);
                        sessionConfig.monitoredlist.Add(monnode);
                    }

                    sessionConfig.SaveToJsonFile(targetfile);
                }
                catch (Exception exception)
                {
                    GuiUtils.HandleException(String.Empty, GuiUtils.CallerName(), exception);
                    sessionConfig = null;
                }
            }
            return(sessionConfig);
        }
Example #8
0
        /// <summary>
        /// On page loaded
        /// </summary>
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            App.unclosedSession = this;

            sessionInfo = e.Parameter as SessionInfo;

            if (sessionInfo == null)
            {
                sessionMgmtAction         = SESSIONMGMT_ACTION.NEW;
                sessionInfo               = new SessionInfo();
                sessionInfo.sessionName   = "";
                sessionInfo.profilePath   = "";
                sessionInfo.sourceType    = "";
                m_sessionConfig_full_path = "";
                m_sessionConfig           = null;
            }
            else
            {
                m_sessionConfig_full_path = Path.Combine(m_local, SiteProfileManager.GetFullPath(App.SiteProfileId, sessionInfo.profilePath));
                // json configuration
                m_sessionConfig = OpcuaSessionConfig.LoadFromJsonFile(m_sessionConfig_full_path);
            }


            ApplicationInstance      application   = OpcuaSessionConfig.OpcuaApplication;
            ApplicationConfiguration configuration = application.ApplicationConfiguration;
            ServiceMessageContext    context       = configuration.CreateMessageContext();

            if (!configuration.SecurityConfiguration.AutoAcceptUntrustedCertificates)
            {
                configuration.CertificateValidator.CertificateValidation += new CertificateValidationEventHandler(CertificateValidator_CertificateValidation);
            }

            m_context       = context;
            m_application   = application;
            m_configuration = configuration;

            SessionsCTRL.Configuration    = configuration;
            SessionsCTRL.MessageContext   = context;
            SessionsCTRL.AddressSpaceCtrl = BrowseCTRL;
            SessionsCTRL.NodeSelected    += SessionCtrl_NodeSelected;


            // disable cached endpoints from Opc.Ua.SampleClient.Config.xml
            //// get list of cached endpoints.
            //m_endpoints = m_configuration.LoadCachedEndpoints(true);
            m_endpoints = new ConfiguredEndpointCollection();
            m_endpoints.DiscoveryUrls = configuration.ClientConfiguration.WellKnownDiscoveryUrls;

            // work around to fill Configuration and DiscoveryUrls
            if (m_sessionConfig != null)
            {
                m_sessionConfig.endpoint.Configuration = EndpointConfiguration.Create(m_configuration);
                m_sessionConfig.endpoint.Description.Server.DiscoveryUrls.Add(m_sessionConfig.endpoint.EndpointUrl.AbsoluteUri.ToString());
                m_endpoints.Add(m_sessionConfig.endpoint);
            }

            // hook up endpoint selector
            EndpointSelectorCTRL.Initialize(m_endpoints, m_configuration);
            EndpointSelectorCTRL.ConnectEndpoint  += EndpointSelectorCTRL_ConnectEndpoint;
            EndpointSelectorCTRL.EndpointsChanged += EndpointSelectorCTRL_OnChange;

            BrowseCTRL.SessionTreeCtrl = SessionsCTRL;
            BrowseCTRL.NodeSelected   += BrowseCTRL_NodeSelected;

            btnDelSubscription.IsEnabled = false;
            btnAddSubscription.IsEnabled = false;

            btnDelSubscription.Click += ContextMenu_OnDelete;
            btnAddSubscription.Click += ContextMenu_OnReport;

            // exception dialog
            GuiUtils.ExceptionMessageDlg += ExceptionMessageDlg;

            EndpointSelectorCTRL.IsEnabled = false;
            BrowseCTRL.IsEnabled           = false;
            SessionsCTRL.IsEnabled         = false;

            txtSessionName.Text = sessionInfo.sessionName;

            if (sessionMgmtAction == SESSIONMGMT_ACTION.NEW)
            {
                txtSessionName.IsReadOnly      = false;
                btnReload.IsEnabled            = false;
                btnReload.Visibility           = Visibility.Collapsed;
                EndpointSelectorCTRL.IsEnabled = true;
            }
            else
            {
                if (m_sessionConfig == null)
                {
                    txtSessionName.IsReadOnly      = true;
                    EndpointSelectorCTRL.IsEnabled = true;
                    btnReload.IsEnabled            = false;
                }
                else
                {
                    txtSessionName.IsReadOnly = true;
                    btnReload.IsEnabled       = false;
                    var ignored = Task.Run(OpenSessionView_OpcuaClient);
                }
            }
        }