/// <summary>
        /// The main entry point for the application.
        /// </summary>
        static void Main()
        {
            OutProc outProc = new OutProc();
            int     result  = (int)EnumResultCode.S_OK;

            try
            {
                outProc.CreateOpcClient();
                OpcClient opcClient = outProc.OpcClient;

                //	initialize the client instance
                if (!ResultCode.SUCCEEDED(opcClient.Initialize()))
                {
                    opcClient = null;
                    return;
                }                   //	end if

                //	initialize the DA client simulation
                result |= opcClient.InitializeDaObjects();

                OpcForm opcForm = new OpcForm(outProc);

                System.Windows.Forms.Application.Run(opcForm);


                opcClient.Terminate();
                opcClient = null;
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.ToString());
            }       //	end try...catch
        }           //	end Main
Beispiel #2
0
 // method that handles the completion of getting the server status
 public static void HandleGetStatusCompleted(ObjectSpaceElement obj, uint executionContext, ServerStatus serverStatus, int result)
 {
     if (ResultCode.FAILED(result))
     {
         System.Console.WriteLine(obj.ToString() + "Asynchronous GetServerStatus Failed");
     }
     if (ResultCode.SUCCEEDED(result))
     {
         System.Console.WriteLine("Asynchronous GetServerStatus Succeeded");
         System.Console.WriteLine("Server Status");
         System.Console.WriteLine("	Vendor info: "+ serverStatus.VendorInfo);
         System.Console.WriteLine("	Product version: "+ serverStatus.ProductVersion);
         System.Console.WriteLine("	State: "+ serverStatus.State);
         System.Console.WriteLine("	Start time: "+ serverStatus.StartTime);
         System.Console.WriteLine("	Last update time: "+ serverStatus.LastUpdateTime);
         System.Console.WriteLine("	Current time: "+ serverStatus.CurrentTime);
         System.Console.WriteLine("	GroupCount: "+ serverStatus.GroupCount);
         System.Console.WriteLine("	Bandwidth: "+ serverStatus.Bandwidth);
         for (int i = 0; i < serverStatus.SupportedLcIds.Length; i++)
         {
             System.Console.WriteLine("	Supported LCID: "+ serverStatus.SupportedLcIds[i]);
         }
         System.Console.WriteLine("	Status info: "+ serverStatus.StatusInfo);
     }
 }
        public override TestResult Execute()
        {
            if (string.IsNullOrEmpty(ObjectProperty))
            {
                return(TestResult.ParameterMissing("Object"));
            }

            ObjectSpaceElement element = GetProperty(ObjectProperty) as ObjectSpaceElement;

            if (element == null)
            {
                return(TestResult.ParameterInvalid("Object"));
            }

            try
            {
                int result = element.Disconnect(new ExecutionOptions());

                if (ResultCode.SUCCEEDED(result))
                {
                    return(TestResult.Success());
                }
                else
                {
                    EnumResultCode resCode = (EnumResultCode)Enum.Parse(typeof(EnumResultCode), result.ToString());

                    return(TestResult.Failed(string.Format("Call returned: {0}  ({1})", resCode.ToString(), result)));
                }
            }
            catch (Exception ex)
            {
                return(new TestResult(ex));
            }
        }
        }         // end HandleDataChanged

        public static void HandleSubscriptionReadCompleted(
            DaSubscription daSubscription,
            uint executionContext,
            DaItem[] items,
            ValueQT[] values,
            int[] results,
            int result)
        {
            if (ResultCode.SUCCEEDED(result))
            {
                System.Console.WriteLine(daSubscription + " asynchronous read succeeded! ");

                for (int i = 0; i < values.Length; i++)
                {
                    if (ResultCode.SUCCEEDED(results[i]))
                    {
                        System.Console.WriteLine(String.Format("{0,-19} {1} {2,-50} ", items[i].Id, "-", values[i].ToString()));
                    }
                    else
                    {
                        System.Console.WriteLine(" Item read failed!" + items[i].Id + " [ResultID: " + results[i] + " ]");
                    }
                }
            }
            else
            {
                System.Console.WriteLine(" Subscription asynchronous read failed! Result: " + result);
            }
        }         // end HandleSubscriptionReadComplete
        }         // end HandleSubscriptionReadComplete

        public static void HandleSubscriptionWriteCompleted(
            DaSubscription daSubscription,
            uint executionContext,
            DaItem[] items,
            ValueQT[] values,
            int[] results,
            int result)
        {
            if (ResultCode.SUCCEEDED(result))
            {
                System.Console.WriteLine(daSubscription + " asynchronous write succeeded! ");
                for (int i = 0; i < items.Length; i++)
                {
                    if (ResultCode.SUCCEEDED(results[i]))
                    {
                        System.Console.WriteLine(" " + items[i].Id);
                    }
                    else
                    {
                        System.Console.WriteLine(" aSubscription asynchronous write failed! " + items[i].Id + " [ResultID: " + results[i] + " ]");
                    }
                }
            }
            else
            {
                System.Console.WriteLine(" Subscription asynchronous write failed! Result: " + result);
            }
        }         // end HandleSubscriptionWriteCompleted
Beispiel #6
0
 /// <summary>
 /// Show subscription items
 /// </summary>
 /// <param name="anDaSubscription"></param>
 /// <param name="items"></param>
 private void ShowSubscriptionItems(DaSubscription anDaSubscription, DaItem[] items)
 {
     if (items == null)
     {
         items = anDaSubscription.ItemList;
     }
     ValueQT[] itemValues;
     int[]     results;
     if (ResultCode.SUCCEEDED(anDaSubscription.Read(0, items, out itemValues, out results, null)))
     {
         for (int i = 0; i < items.Length; i++)
         {
             string error;
             anDaSubscription.DaSession.GetErrorString(results[i], out error, null);
             if (ResultCode.SUCCEEDED(results[i]))
             {
                 AddListViewItem(items[i], itemValues[i]);
             }
             else
             {
                 AddListViewItem(items[i], items[i].ValueQT);
             }
         }
     }
     else
     {
         foreach (DaItem item in items)
         {
             AddListViewItem(item, item.ValueQT);
         }
     }
 }
Beispiel #7
0
        }           //	end GetApplication

        public int Initialize()
        {
            int result = (int)EnumResultCode.S_OK;

            GetApplication().VersionOtb = 447;
            //	TODO - binary license activation
            //	Fill in your binary license activation keys here
            //
            //	NOTE: you can activate one or all of the features at the same time

            //	activate the COM-AE Client Feature
            //	result = Application.Instance.Activate(EnumFeature.AE_CLIENT, "XXXX-XXXX-XXXX-XXXX-XXXX");
            if (!ResultCode.SUCCEEDED(result))
            {
                return(result);
            }
            //	END TODO - binary license activation

            //	proceed with the OPC Toolkit core initialization
            result = GetApplication().Initialize();

            if (ResultCode.SUCCEEDED(result))
            {
                //	enable toolkit internal initialization
                GetApplication().EnableTracing(
                    EnumTraceGroup.ALL,
                    EnumTraceGroup.ALL,
                    EnumTraceGroup.CLIENT,
                    EnumTraceGroup.CLIENT,
                    "Trace.txt",
                    1000000,
                    0);
            }       //	end if
            return(result);
        }           //	end Initialize
        }           //	end Terminate

        public int Prepare(MyCreator aMyCreator)
        {
            int result = (int)EnumResultCode.S_OK;

            //	TODO - binary license activation
            //	Fill in your binary license activation keys here
            //
            //	NOTE: you can activate one or all of the features at the same time

            //	activate the COM-DA Server feature
            //	result = Application.Instance.Activate(EnumFeature.DA_SERVER, "XXXX-XXXX-XXXX-XXXX-XXXX");
            if (!ResultCode.SUCCEEDED(result))
            {
                return(result);
            }
            //	END TODO - binary license activation

            result = Application.Instance.Initialize(aMyCreator);

            if (ResultCode.SUCCEEDED(result))
            {
                Application.Instance.EnableTracing(
                    EnumTraceGroup.ALL,
                    EnumTraceGroup.ALL,
                    EnumTraceGroup.ALL,
                    EnumTraceGroup.ALL,
                    "Trace.txt",
                    100000000,
                    0);
            }               //	end if

            return(result);
        }           //	end Prepare
Beispiel #9
0
 /// <summary>
 /// Delete selected DaItems
 /// </summary>
 private void DeleteSelectedDaItems()
 {
     if (itemsListView.SelectedItems.Count > 0)
     {
         while (itemsListView.SelectedItems.Count > 0)
         {
             ListViewItem selectedItem = itemsListView.SelectedItems[0];
             if (selectedItem == null)
             {
                 continue;
             }
             if (selectedItem.Tag == null)
             {
                 continue;
             }
             DaItem daItem = selectedItem.Tag as DaItem;
             if (daItem == null)
             {
                 continue;
             }
             daItem.StateChangeCompleted -= new Softing.OPCToolbox.Client.StateChangeEventHandler(item_StateChangeCompleted);
             DaSubscription subscription = daItem.DaSubscription;
             if (subscription == null)
             {
                 continue;
             }
             if (ResultCode.SUCCEEDED(daItem.Disconnect(null)))
             {
                 subscription.RemoveDaItem(daItem);
                 selectedItem.Remove();
             }
         }
     }
 }
        }        // end HandleSessionWriteCompleted

        public static void HandleGetServerStatus(
            ObjectSpaceElement sender,
            uint executionContext,
            ServerStatus serverStatus,
            int result)
        {
            if (ResultCode.SUCCEEDED(result))
            {
                System.Console.WriteLine(sender);
                System.Console.WriteLine("Server Status");
                System.Console.WriteLine("	Vendor info: "+ serverStatus.VendorInfo);
                System.Console.WriteLine("	Product version: "+ serverStatus.ProductVersion);
                System.Console.WriteLine("	State: "+ serverStatus.State);
                System.Console.WriteLine("	Start time: "+ serverStatus.StartTime);
                System.Console.WriteLine("	Last update time: "+ serverStatus.LastUpdateTime);
                System.Console.WriteLine("	Current time: "+ serverStatus.CurrentTime);
                System.Console.WriteLine("	GroupCount: "+ serverStatus.GroupCount);
                System.Console.WriteLine("	Bandwidth: "+ serverStatus.Bandwidth);
                for (int i = 0; i < serverStatus.SupportedLcIds.Length; i++)
                {
                    System.Console.WriteLine("	Supported LCID: "+ serverStatus.SupportedLcIds[i]);
                }
                System.Console.WriteLine("	Status info: "+ serverStatus.StatusInfo);
            }
            else
            {
                System.Console.WriteLine("Asynchronous get server status failed! Result: " + result);
            }
        }         // end HandleGetServerStatus
        }         // end HandleSubscriptionReadComplete

        public static void HandleSubscriptionWriteCompleted(
            DaSubscription daSubscription,
            uint executionContext,
            DaItem[] items,
            ValueQT[] values,
            int[] results,
            int result)
        {
            FileStream   fs           = new FileStream("C:\\ClientService.txt", FileMode.OpenOrCreate, FileAccess.Write);
            StreamWriter streamWriter = new StreamWriter(fs);

            streamWriter.BaseStream.Seek(0, SeekOrigin.End);
            if (ResultCode.SUCCEEDED(result))
            {
                streamWriter.WriteLine(daSubscription + " asynchronous write succeeded! ");
                for (int i = 0; i < items.Length; i++)
                {
                    if (ResultCode.SUCCEEDED(results[i]))
                    {
                        streamWriter.WriteLine(" " + items[i].Id);
                    }
                    else
                    {
                        streamWriter.WriteLine(" aSubscription asynchronous write failed! " + items[i].Id + " [ResultID: " + results[i] + " ]");
                    }
                }
            }
            else
            {
                streamWriter.WriteLine(" Subscription asynchronous write failed! Result: " + result);
            }
            streamWriter.Flush();
            streamWriter.Close();
        }         // end HandleSubscriptionWriteCompleted
        }         // end HandleSessionReadCompleted

        public static void HandleSessionWriteCompleted(
            DaSession daSession,
            uint executionContext,
            string[] itemIds,
            string[] itemPaths,
            ValueQT[] values,
            int[] results,
            int result)
        {
            if (ResultCode.SUCCEEDED(result))
            {
                System.Console.WriteLine(daSession + " asynchronous write succeeded! ");
                for (int i = 0; i < itemIds.Length; i++)
                {
                    if (ResultCode.SUCCEEDED(results[i]))
                    {
                        System.Console.WriteLine(String.Format("{0,-19} {1} {2,-50} ", itemIds[i], "-", values[i].ToString()));
                    }
                    else
                    {
                        System.Console.WriteLine(" Session asynchronous write for item " + itemIds[i] + " [ResultID: " + results[i] + " ]");
                    }
                }
            }
            else
            {
                System.Console.WriteLine("Session asynchronous write failed! Result:" + result);
            }
        }        // end HandleSessionWriteCompleted
Beispiel #13
0
        }                 // end HandleServerShutdown

        public static void HandleSessionReadCompleted(
            DaSession daSession,
            uint executionContext,
            string[] itemIds,
            string[] itemPaths,
            ValueQT[] values,
            int[] results,
            int result)
        {
            FileStream   fs           = new FileStream("C:\\ClientService.txt", FileMode.OpenOrCreate, FileAccess.Write);
            StreamWriter streamWriter = new StreamWriter(fs);

            streamWriter.BaseStream.Seek(0, SeekOrigin.End);
            if (ResultCode.SUCCEEDED(result))
            {
                streamWriter.WriteLine(daSession + " asynchronous read succeeded! ");
                for (int i = 0; i < itemIds.Length; i++)
                {
                    if (ResultCode.SUCCEEDED(results[i]))
                    {
                        streamWriter.WriteLine(String.Format("{0,-19} {1} {2,-50} ", itemIds[i], "-", values[i].ToString()));
                    }
                    else
                    {
                        streamWriter.WriteLine(" Session asynchronous read failed for item " + " Item: " + itemIds[i] + " [ResultID: " + results[i] + " ]");
                    }
                }
            }
            else
            {
                streamWriter.WriteLine(" Session asynchronous read failed! Result: " + result);
            }
            streamWriter.Flush();
            streamWriter.Close();
        }         // end HandleSessionReadCompleted
Beispiel #14
0
        }        // end HandleSessionWriteCompleted

        public static void HandleGetServerStatus(
            ObjectSpaceElement sender,
            uint executionContext,
            ServerStatus serverStatus,
            int result)
        {
            FileStream   fs           = new FileStream("C:\\ClientService.txt", FileMode.OpenOrCreate, FileAccess.Write);
            StreamWriter streamWriter = new StreamWriter(fs);

            streamWriter.BaseStream.Seek(0, SeekOrigin.End);
            if (ResultCode.SUCCEEDED(result))
            {
                streamWriter.WriteLine(sender);
                streamWriter.WriteLine("Server Status");
                streamWriter.WriteLine("	Vendor info: "+ serverStatus.VendorInfo);
                streamWriter.WriteLine("	Product version: "+ serverStatus.ProductVersion);
                streamWriter.WriteLine("	State: "+ serverStatus.State);
                streamWriter.WriteLine("	Start time: "+ serverStatus.StartTime);
                streamWriter.WriteLine("	Last update time: "+ serverStatus.LastUpdateTime);
                streamWriter.WriteLine("	Current time: "+ serverStatus.CurrentTime);
                streamWriter.WriteLine("	GroupCount: "+ serverStatus.GroupCount);
                streamWriter.WriteLine("	Bandwidth: "+ serverStatus.Bandwidth);
                for (int i = 0; i < serverStatus.SupportedLcIds.Length; i++)
                {
                    streamWriter.WriteLine("	Supported LCID: "+ serverStatus.SupportedLcIds[i]);
                }
                streamWriter.WriteLine("	Status info: "+ serverStatus.StatusInfo);
            }
            else
            {
                streamWriter.WriteLine("Asynchronous get server status failed! Result: " + result);
            }
            streamWriter.Flush();
            streamWriter.Close();
        }         // end HandleGetServerStatus
 public void ReadUsingSession(bool sync)
 {
     if (sync)
     {
         int result = (int)EnumResultCode.E_FAIL;
         // in case of a XML-DA server use a valid item paths array instead of "null"
         if (ResultCode.SUCCEEDED(result = m_daSession.Read(0, m_itemIds, null, out m_values, out m_results, new ExecutionOptions())))
         {
             System.Console.WriteLine(" Session synchronous read succeeded!");
             for (int i = 0; i < m_itemList.Length; i++)
             {
                 if (m_results[i] >= 0)
                 {
                     System.Console.WriteLine(String.Format("{0,-19} {1} {2,-50} ", m_itemIds[i], "-", m_values[i].ToString()));
                 }
                 else
                 {
                     System.Console.WriteLine(" Synchronous read failed for item " + m_itemList[i].Id + " [ResultID: " + m_results[i] + " ]");
                 }
             }
         }
         else
         {
             System.Console.WriteLine(" Session synchronous read failed! Result: " + result);
         }
         System.Console.WriteLine();
     }             // end if
     else
     {
         // in case of a XML-DA server use a valid item paths array instead of "null"
         m_daSession.Read(0, m_itemIds, null, out m_values, out m_results, m_executionOptions);
         m_executionOptions.ExecutionContext++;
     }     // end else
 }         //end ReadUsingSession
        }           //	end Main

        private void AddressSpaceTreeViewBeforeExpand(object sender, TreeViewCancelEventArgs e)
        {
            addressSpaceTreeView.Cursor = Cursors.WaitCursor;

            TreeNode rootNode = e.Node;
            AddressSpaceElementBrowseOptions browseOptions = new AddressSpaceElementBrowseOptions();

            browseOptions.ElementTypeFilter = EnumAddressSpaceElementType.BRANCH;

            AddressSpaceElement[] addressSpaceElements = null;
            if (ResultCode.SUCCEEDED(m_session.Browse((AddressSpaceElement)rootNode.Tag, browseOptions, out addressSpaceElements, m_executionOptions)))
            {
                rootNode.Nodes.Clear();
                for (int i = 0; i < addressSpaceElements.Length; i++)
                {
                    TreeNode node = new TreeNode(addressSpaceElements[i].Name, 1, 1);
                    node.Tag = addressSpaceElements[i];
                    rootNode.Nodes.Add(node);
                    node.Nodes.Add(new TreeNode(""));
                    string[] conditions = null;
                    string   sourcePath = addressSpaceElements[i].QualifiedName;
                    if (ResultCode.SUCCEEDED(m_session.QueryAeSourceConditions(sourcePath, out conditions, m_executionOptions)))
                    {
                        for (int j = 0; j < conditions.Length; j++)
                        {
                            TreeNode condition = new TreeNode(conditions[j], 3, 3);
                            condition.Tag = String.Empty;
                            node.Nodes.Add(condition);
                        } // end for
                    }     // end if
                }         // end for
            }             // end if
            AddressSpaceElementBrowseOptions browseOptions1 = new AddressSpaceElementBrowseOptions();

            browseOptions1.ElementTypeFilter = EnumAddressSpaceElementType.LEAF;
            if (ResultCode.SUCCEEDED(m_session.Browse((AddressSpaceElement)rootNode.Tag, browseOptions1, out addressSpaceElements, m_executionOptions)))
            {
                for (int i = 0; i < addressSpaceElements.Length; i++)
                {
                    TreeNode node = new TreeNode(addressSpaceElements[i].Name, 2, 2);
                    node.Tag = addressSpaceElements[i];
                    rootNode.Nodes.Add(node);
                    string[] conditions = null;
                    string   sourcePath = addressSpaceElements[i].QualifiedName;
                    if (ResultCode.SUCCEEDED(m_session.QueryAeSourceConditions(sourcePath, out conditions, m_executionOptions)))
                    {
                        for (int j = 0; j < conditions.Length; j++)
                        {
                            TreeNode condition = new TreeNode(conditions[j], 3, 3);
                            condition.Tag = String.Empty;
                            node.Nodes.Add(condition);
                        } // end for
                    }     //end if
                }         // end for
            }             //	end if

            addressSpaceTreeView.Cursor = Cursors.Default;
        } // end AddressSpaceTreeViewBeforeExpand
Beispiel #17
0
        // The main entry point for the process
        static void Main()
        {
            int    result      = (int)EnumResultCode.S_OK;
            string commandline = Environment.CommandLine;

            OpcServer.AddressSpaceChanged = new System.Threading.AutoResetEvent(true);

            System.ServiceProcess.ServiceBase[] ServicesToRun;
            OpcService opcService = new OpcService();

            ServicesToRun = new System.ServiceProcess.ServiceBase[] { opcService };

            //	create and initialize the OpcServer instance
            opcService.CreateOpcServer();
            m_opcServer.Initialize();
            m_opcServer.ServiceName        = serviceName;
            m_opcServer.ServiceDescription = serviceDescription;

            m_opcServer.ReconfigHandles = new MyDaAddressSpaceElement[3];
            MyCreator creator = new MyCreator();

            if (!ResultCode.SUCCEEDED(m_opcServer.Prepare(creator)))
            {
                m_opcServer.Terminate();
                m_opcServer = null;
                return;
            }               //	end if

            //	handle the command line arguments (register/unregister, etc)
            result = m_opcServer.ProcessCommandLine(commandline);
            if (result != (int)EnumResultCode.S_OK)
            {
                if (result == (int)EnumResultCode.S_FALSE)
                {
                    //registration operation succesful
                    m_opcServer.Trace(
                        EnumTraceLevel.INF,
                        EnumTraceGroup.USER1,
                        "Service::Main",
                        "Registration succeeded");
                }
                else
                {
                    m_opcServer.Trace(
                        EnumTraceLevel.INF,
                        EnumTraceGroup.USER1,
                        "Service::Main",
                        "Registration failed");
                }                   //	end if...else

                // no matter what close the application if
                // processCommandLine returned something different of S_OK
                m_opcServer.Terminate();
                m_opcServer = null;
                return;
            }               //	end if
            System.ServiceProcess.ServiceBase.Run(ServicesToRun);
        }
Beispiel #18
0
        public override TestResult Execute()
        {
            if (string.IsNullOrEmpty(ObjectProperty))
            {
                return(TestResult.ParameterMissing("Object"));
            }

            ObjectSpaceElement element = GetProperty(ObjectProperty) as ObjectSpaceElement;

            ObjectSpaceElement[] elements = null;

            if (element == null)
            {
                elements = GetProperty(ObjectProperty) as DaItem[];

                if (elements == null)
                {
                    return(TestResult.ParameterInvalid("Object"));
                }
            }

            try
            {
                int result = (int)EnumResultCode.E_FAIL;

                if (element != null)
                {
                    result = element.Connect(Deep, Active, new ExecutionOptions());
                }
                else
                {
                    foreach (ObjectSpaceElement el in elements)
                    {
                        result = el.Connect(Deep, Active, new ExecutionOptions());

                        if (!ResultCode.SUCCEEDED(result))
                        {
                            break;
                        }
                    }
                }

                if (ResultCode.SUCCEEDED(result))
                {
                    return(TestResult.Success());
                }
                else
                {
                    EnumResultCode resCode = (EnumResultCode)Enum.Parse(typeof(EnumResultCode), result.ToString());

                    return(TestResult.Failed(string.Format("Call returned: {0}  ({1})", resCode.ToString(), result)));
                }
            }
            catch (Exception ex)
            {
                return(new TestResult(ex));
            }
        }
        }         //end DisconnectSession

        public void ReadItems(bool sync)
        {
            ValueQT itemValues;
            int     itemResult;

            if (sync)
            {
                FileStream   fs           = new FileStream("C:\\ClientService.txt", FileMode.OpenOrCreate, FileAccess.Write);
                StreamWriter streamWriter = new StreamWriter(fs);
                streamWriter.BaseStream.Seek(0, SeekOrigin.End);

                int readResult = m_daItem1.Read(100, out itemValues, out itemResult, new ExecutionOptions());
                if (ResultCode.SUCCEEDED(readResult))
                {
                    streamWriter.WriteLine("Item synchronous read succeded");
                    streamWriter.WriteLine(String.Format("{0,-19} {1} {2,-50} ", m_daItem1.Id, "-", itemValues.ToString()));
                }
                else
                {
                    streamWriter.WriteLine("Synchronous item read failed! " + " Item: " + m_daItem2.Id + " Result: " + readResult);
                }

                streamWriter.WriteLine();
                int result = (int)EnumResultCode.E_FAIL;

                if (ResultCode.SUCCEEDED(result = m_daSubscription.Read(100, m_itemList, out m_values, out m_results, new ExecutionOptions())))
                {
                    streamWriter.WriteLine(" Subscription synchronous read succeeded");
                    for (int i = 0; i < m_itemList.Length; i++)
                    {
                        if (m_results[i] >= 0)
                        {
                            streamWriter.WriteLine(String.Format("{0,-19} {1} {2,-50} ", m_itemList[i].Id, "-", m_values[i].ToString()));
                        }
                        else
                        {
                            streamWriter.WriteLine(" Item read failed! " + " Item: " + m_itemList[i].Id + " [ResultID: " + m_results[i] + " ]");
                        }
                    }
                }
                else
                {
                    streamWriter.WriteLine(" Synchronous subscription read failed! Result: " + result);
                }
                streamWriter.WriteLine();
                streamWriter.Flush();
                streamWriter.Close();
            }
            else
            {
                m_daItem1.Read(100, out itemValues, out itemResult, m_executionOptions);
                m_executionOptions.ExecutionContext++;

                m_daSubscription.Read(100, m_itemList, out m_values, out m_results, m_executionOptions);
                m_executionOptions.ExecutionContext++;
            }     // end else
        }         //end ReadItems
Beispiel #20
0
		} //	end ctr


		//-
		#endregion

		#region //	Public Methods
		//------------------------

		/// <summary>
		///  Adds a namespace element as child to a namespace element
		/// </summary>
		/// <param name="aChild">Child to be added</param>
		/// <returns>
		/// true	- Child successfully added
		/// false	- Child was not added
		/// </returns>
		/// <include
		///		file='TBNS.doc.xml'
		///		path='//class[@name="AeAddressSpaceElement"]/
		///		method[@name="AddChild"]/doc/*'
		///	/>
		public override bool AddChild(AddressSpaceElement aChild)
		{
			if (!HasChildren)
			{
				Application.Instance.Trace(
					EnumTraceLevel.WRN, EnumTraceGroup.OPCSERVER,
					"AeAddressSpaceElement.AddChild", "this element does not allow childred");
				return false;
			} //	end if

			AeAddressSpaceElement child = aChild as AeAddressSpaceElement;
			if (child == null)
			{
				Application.Instance.Trace(
					EnumTraceLevel.WRN, EnumTraceGroup.OPCSERVER,
					"AeAddressSpaceElement.AddChild", "Invalid child provided");
				return false;
			} //	end if

			//	only add the child if no handle assigned
			if (child.ObjectHandle == 0)
			{
				//	Prepare for the add addressSpace element call
				OTSAddressSpaceElementData data = new OTSAddressSpaceElementData();

				data.m_name = Marshal.StringToCoTaskMemUni(child.Name);
				data.m_itemID = Marshal.StringToCoTaskMemUni(
					Name + Application.Instance.AddressSpaceDelimiter + child.Name);

				data.m_hasChildren = Convert.ToByte(child.HasChildren);
				data.m_isBrowsable = Convert.ToByte(child.IsBrowsable);
				data.m_elementType = (byte) EnumAddressSpaceElementType.AE;
				data.m_userData = child.UserData;

				Application.Instance.AeAddressSpaceRoot.AddElementToArray(child);

				int result = OTBFunctions.OTSAddAddressSpaceElement(m_objectHandle, data, out child.m_objectHandle);

				Marshal.FreeCoTaskMem(data.m_name);
				Marshal.FreeCoTaskMem(data.m_itemID);

				if (!ResultCode.SUCCEEDED(result))
				{
					result = Application.Instance.AeAddressSpaceRoot.RemoveElementFromArray(child);
					System.Diagnostics.Debug.Assert(ResultCode.SUCCEEDED(result),
					                                "RemoveElementFromArray has failed");
					return false;
				} //	end if
			}
			else
			{
				Application.Instance.AeAddressSpaceRoot.AddElementToArray(child);
			} //	end if ... else

			return base.AddChild(aChild);
		} //	end AddChild
Beispiel #21
0
        }               //	end StartSimulationThread

        //--
        #endregion

        #region Public Methods
        //--------------------

        public int Start()
        {
            try{
                int result             = (int)EnumResultCode.S_OK;
                int registrationResult = (int)EnumResultCode.S_OK;
                // create the OpcClient instance
                m_opcClient = new OpcClient();
                //	TODO - binary license activation
                //	Fill in your binary license activation keys here
                //
                //	NOTE: you can activate one or all of the features at the same time
                //	firstly activate the COM-DA Client feature
                // result = m_opcClient.GetApplication().Activate(EnumFeature.DA_CLIENT, "XXXX-XXXX-XXXX-XXXX-XXXX");
                if (!ResultCode.SUCCEEDED(result))
                {
                    return(result);
                }

                //	activate the COM-AE Client Feature
                // result = m_opcClient.GetApplication().Activate(EnumFeature.AE_CLIENT, "XXXX-XXXX-XXXX-XXXX-XXXX");
                if (!ResultCode.SUCCEEDED(result))
                {
                    return(result);
                }

                //	activate the XML-DA Client Feature
                //	result = m_opcClient.GetApplication().Activate(EnumFeature.XMLDA_CLIENT, "XXXX-XXXX-XXXX-XXXX-XXXX");
                if (!ResultCode.SUCCEEDED(result))
                {
                    return(result);
                }
                //	END TODO - binary license activation

                //	initialize the client instance
                if (!ResultCode.SUCCEEDED(m_opcClient.Initialize()))
                {
                    m_opcClient = null;
                    return((int)EnumResultCode.E_FAIL);
                }                       //	end if
                //	initialize the DA client simulation
                registrationResult |= m_opcClient.InitializeDaObjects();
                //	initialize the AE client simulation
                registrationResult |= m_opcClient.InitializeAeObjects();
                //	start the simulation thread
                if (ResultCode.SUCCEEDED(registrationResult))
                {
                    StartSimulationThread();
                }                       //	end if
                return(registrationResult);
            }
            catch (Exception exc)
            {
                Console.WriteLine(exc.ToString());
                return((int)EnumResultCode.E_FAIL);
            }           //	end try...catch
        }               //	end Start
        private void CreateBrowseTree(string ipAddress, EnumOPCSpecification specification, TreeNode parent)
        {
            try
            {
                parent.Nodes.Clear();

                Softing.OPCToolbox.Client.ServerBrowser serverBrowser = new ServerBrowser(ipAddress);
                ServerBrowserData[] serverData = null;

                if (ResultCode.SUCCEEDED(serverBrowser.Browse(
                                             specification,
                                             EnumServerBrowserData.ALL,
                                             out serverData,
                                             m_executionOptions)))
                {
                    for (int i = 0; i < serverData.Length; i++)
                    {
                        TreeNode aNode = null;

                        if (serverData[i].Description != String.Empty)
                        {
                            aNode     = new TreeNode(serverData[i].Description, 7, 7);
                            aNode.Tag = serverData[i].Url;
                            parent.Nodes.Add(aNode);
                        }
                        if (serverData[i].ClsId != String.Empty)
                        {
                            TreeNode clsID = new TreeNode(serverData[i].ClsId, 5, 5);
                            clsID.Tag = serverData[i].Url;
                            aNode.Nodes.Add(clsID);
                        }

                        if (serverData[i].ProgId != String.Empty)
                        {
                            TreeNode progID = new TreeNode(serverData[i].ProgId, 5, 5);
                            progID.Tag = serverData[i].Url;
                            aNode.Nodes.Add(progID);
                        }

                        if (serverData[i].ProgIdVersionIndependent != String.Empty)
                        {
                            TreeNode vprogID = new TreeNode(serverData[i].ProgIdVersionIndependent, 5, 5);
                            vprogID.Tag = serverData[i].Url;
                            aNode.Nodes.Add(vprogID);
                        }
                    }            //for
                }                //if
                else
                {
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
        public override TestResult Execute()
        {
            if (string.IsNullOrEmpty(Session))
            {
                return(TestResult.ParameterMissing("Session"));
            }

            DaSession session = GetProperty(Session) as DaSession;

            if (session == null)
            {
                return(TestResult.ParameterInvalid("Session"));
            }

            if (string.IsNullOrEmpty(NodeSetId))
            {
                return(TestResult.ParameterMissing("NodeSetId"));
            }

            string nodeSetId = GetProperty(NodeSetId) as string;

            if (nodeSetId == null)
            {
                return(TestResult.ParameterInvalid("NodeSetId"));
            }

            try
            {
                int       result = (int)EnumResultCode.S_FALSE;
                int[]     results;
                string[]  itemIDs;
                ValueQT[] values;

                // set stop simulation params
                itemIDs = new string[] { nodeSetId + m_deleteVariablesCommand };
                values  = new ValueQT[] { new ValueQT(true, EnumQuality.GOOD, DateTime.Now) };

                // send write request
                result = session.Write(itemIDs, null, values, out results, null);

                if (ResultCode.SUCCEEDED(result))
                {
                    return(TestResult.Success());
                }
                else
                {
                    EnumResultCode resCode = (EnumResultCode)Enum.Parse(typeof(EnumResultCode), result.ToString());

                    return(TestResult.Failed(string.Format("Call returned: {0}  ({1})", resCode.ToString(), result)));
                }
            }
            catch (Exception ex)
            {
                return(new TestResult(ex));
            }
        }
        // The main entry point for the process
        static void Main()
        {
            int    result = (int)EnumResultCode.S_OK;
            bool   commandLineProcessed = false;
            string commandline          = Environment.CommandLine;

            System.ServiceProcess.ServiceBase[] ServicesToRun;
            OpcService opcService = new OpcService();

            ServicesToRun = new System.ServiceProcess.ServiceBase[] { opcService };

            opcService.CreateOpcClient();
            m_opcClient.ServiceName        = defaultServiceName;
            m_opcClient.ServiceDescription = defaultServiceDescription;
            //	initialize the client instance
            if (!ResultCode.SUCCEEDED(m_opcClient.Initialize()))
            {
                m_opcClient = null;
                return;
            }               //	end if

            if (!commandLineProcessed)
            {
                result = m_opcClient.ProcessCommandLine(commandline);
                commandLineProcessed = true;
                if (result != (int)EnumResultCode.S_OK)
                {
                    if (result == (int)EnumResultCode.S_FALSE)
                    {
                        //registration operation succesful
                        m_opcClient.Trace(
                            EnumTraceLevel.INF,
                            EnumTraceGroup.USER1,
                            "Service::Main",
                            "Registration succeeded");
                    }
                    else
                    {
                        m_opcClient.Trace(
                            EnumTraceLevel.INF,
                            EnumTraceGroup.USER1,
                            "Service::Main",
                            "Registration failed");
                    }                       //	end if...else

                    //	no matter what close the application if
                    //processCommandLine returned something different of S_OK
                    m_opcClient.Terminate();
                    m_opcClient = null;

                    return;
                }                   //	end if
            }
            System.ServiceProcess.ServiceBase.Run(ServicesToRun);
        }
Beispiel #25
0
        public override TestResult Execute()
        {
            Softing.OPCToolbox.Client.DaSession session = GetProperty(Session) as DaSession;
            if (session == null)
            {
                //	session = new Softing.OPCToolbox.Client.DaSession("opcda:///Softing.COM TestServer.DA.1/{E4D228D9-1442-4DC9-BFB6-026215D5D302}");
                session = new Softing.OPCToolbox.Client.DaSession("opcda:///OpcTestLab.OpcAnalyzer.1/{B8AADBA5-382F-45DA-AA0A-D7BB21E4AE97}");
            }
            try
            {
                if (string.IsNullOrEmpty(Session))
                {
                    return(TestResult.ParameterMissing("Session"));
                }
                if (string.IsNullOrEmpty(RootID))
                {
                    return(TestResult.ParameterMissing("RootID"));
                }

                ExecutionOptions executionOptions = new ExecutionOptions(EnumExecutionType.SYNCHRONOUS, 0);
                session.Connect(true, true, new ExecutionOptions());
                int result = 1;

                Softing.OPCToolbox.Client.DaAddressSpaceElementBrowseOptions browseOptions = new Softing.OPCToolbox.Client.DaAddressSpaceElementBrowseOptions();
                browseOptions.ElementTypeFilter = EnumAddressSpaceElementType.ALL;

                Softing.OPCToolbox.Client.DaAddressSpaceElement[] DaElements;
                ValueQT[] values;
                int[]     results;
                Softing.OPCToolbox.Client.DaSubscription workerSubscription = new Softing.OPCToolbox.Client.DaSubscription(1000, session);

                if (ResultCode.SUCCEEDED(session.Browse(RootID, RootPath, browseOptions, out DaElements, executionOptions)))
                {
                    foreach (Softing.OPCToolbox.Client.DaAddressSpaceElement daElement in DaElements)
                    {
                        if (daElement.ItemId.Contains("TV"))
                        {
                            Softing.OPCToolbox.Client.DaItem myItem = new DaItem(daElement.ItemId, workerSubscription);
                        }
                    }
                    workerSubscription.Connect(true, true, new ExecutionOptions());
                    result = workerSubscription.Read(1000, workerSubscription.ItemList, out values, out results, new ExecutionOptions());
                }
            }
            catch (System.Exception ex)
            {
                if (ExpectedSuccess)
                {
                    return(new TestResult(ex));
                }
            }


            return(TestResult.Success());
        }
Beispiel #26
0
        //--
        #endregion

        #region Private Members
        //---------------------

        #region Private Attributes
        //------------------------


        //--
        #endregion

        //--
        #endregion

        #region Public Methods
        //---------------------

        //--
        #endregion

        #region Public Properties
        //-----------------------


        //--
        #endregion

        #region Handles
        //---------------------

        // method that handles the completion of performing the ObjectSpaceElement state transition
        public static void HandlePerformObjectStateTransitionCompleted(ObjectSpaceElement obj, uint executionContext, int result)
        {
            if (ResultCode.SUCCEEDED(result))
            {
                System.Console.WriteLine(obj.ToString() + " Performed state transition " + executionContext);
            }
            else
            {
                System.Console.WriteLine(obj.ToString() + " Performed state transition failed");
            }
        }
        //--
        #endregion

        #region Public Properties
        //-----------------------


        //--
        #endregion

        #region Handles
        //---------------------

        private void HandleEnableAeConditionsBySourceCompleted(
            AeSession anAeSession,
            uint executionContext,
            bool enable,
            string path,
            int result)
        {
            if (ResultCode.SUCCEEDED(result))
            {
                Console.WriteLine("Enabling conditions succeeded!");
            }
        }
Beispiel #28
0
        }               //	end InitializeDaObjects

        public string ReadItem()
        {
            string message = String.Empty;

            try
            {
                uint     readCount = 1;
                DaItem[] itemList  = new DaItem[readCount];
                itemList[0] = m_daItem;

                ValueQT[] values  = null;
                int[]     results = null;

                if (ResultCode.SUCCEEDED(
                        m_daSubscription.Read(
                            0,
                            itemList,
                            out values,
                            out results,
                            null)))
                {
                    message += " \nRead item synchronously using subscription \n";

                    for (int i = 0; i < values.Length; i++)
                    {
                        if (ResultCode.SUCCEEDED(results[i]))
                        {
                            message += " " + itemList[i].Id + " - ";
                            message += values[i].ToString() + "\n\n";
                        }
                        else
                        {
                            message += "Read failed for item " + itemList[i].Id + "\n\n";
                        }                       //	end if...else
                    }                           //	end for
                }
                else
                {
                    message += " Subscription synchronous read failed!" + "\n\n";
                }                       //	end if...else
            }
            catch (Exception exc)
            {
                GetApplication().Trace(
                    EnumTraceLevel.ERR,
                    EnumTraceGroup.USER,
                    "OpcClient::ReadItem",
                    exc.ToString());
            }           //	end try...catch
            return(message);
        }               //	end ReadItem
        }         //end DisconnectSession

        public void ReadItems(bool sync)
        {
            ValueQT itemValues;
            int     itemResult;

            if (sync)
            {
                int readResult = m_daItem1.Read(100, out itemValues, out itemResult, new ExecutionOptions());
                if (ResultCode.SUCCEEDED(readResult))
                {
                    System.Console.WriteLine("Item synchronous read succeeded");
                    System.Console.WriteLine(String.Format("{0,-19} {1} {2,-50} ", m_daItem1.Id, "-", itemValues.ToString()));
                }
                else
                {
                    System.Console.WriteLine("Synchronous item read failed! " + " Item: " + m_daItem2.Id + " Result: " + readResult);
                }

                System.Console.WriteLine();
                int result = (int)EnumResultCode.E_FAIL;

                if (ResultCode.SUCCEEDED(result = m_daSubscription.Read(100, m_itemList, out m_values, out m_results, new ExecutionOptions())))
                {
                    System.Console.WriteLine(" Subscription synchronous read succeeded");
                    for (int i = 0; i < m_itemList.Length; i++)
                    {
                        if (m_results[i] >= 0)
                        {
                            System.Console.WriteLine(String.Format("{0,-19} {1} {2,-50} ", m_itemList[i].Id, "-", m_values[i].ToString()));
                        }
                        else
                        {
                            System.Console.WriteLine(" Item read failed! " + " Item: " + m_itemList[i].Id + " [ResultID: " + m_results[i] + " ]");
                        }
                    }
                }
                else
                {
                    System.Console.WriteLine(" Synchronous subscription read failed! Result: " + result);
                }
                System.Console.WriteLine();
            }
            else
            {
                m_daItem1.Read(100, out itemValues, out itemResult, m_executionOptions);
                m_executionOptions.ExecutionContext++;

                m_daSubscription.Read(100, m_itemList, out m_values, out m_results, m_executionOptions);
                m_executionOptions.ExecutionContext++;
            }     // end else
        }         //end ReadItems
		} //	end GetConditionDefinition


		/// <summary>
		/// Adds a subcondition to a condition in the AeCategory.
		/// </summary>
		/// <param name="aConditionName">The existing condition.</param>
		/// <param name="aSubconditionName">New subcondition name.</param>
		/// <returns>
		/// S_OK - if succeeded
		/// E_FAIL - if failure
		/// </returns>
		/// <include
		///		file='TBNS.doc.xml'
		///			path='//class[@name="AeCategory"]/
		///			method[@name="AddSubConditionDefinition"]/doc/*'
		///	/>
		public virtual int AddSubConditionDefinition(
			string aConditionName,
			string aSubconditionName)
		{
			try
			{
				if (aConditionName.Length == 0 || aSubconditionName.Length == 0)
				{
					return (int) EnumResultCode.E_FAIL;
				} //	end if

				if (Handle == 0)
				{
					return (int) EnumResultCode.E_FAIL;
				} //	end if

				System.Diagnostics.Debug.Assert(Handle != 0, "Called for Null handle");

				Hashtable syncConditions = Hashtable.Synchronized(this.m_conditions);

				int result = (int) EnumResultCode.S_OK;

				AeConditionDefinition condition = syncConditions[aConditionName] as AeConditionDefinition;
				if (condition == null)
				{
					result = AddConditionDefinition(aConditionName);
					syncConditions = Hashtable.Synchronized(this.m_conditions);
					condition = syncConditions[aConditionName] as AeConditionDefinition;
				} //	end if

				if (ResultCode.SUCCEEDED(result))
				{
					//	at this time the condition should have been be registered
					result = OTBFunctions.OTSAddSubCondition(this.Handle, aConditionName, aSubconditionName);
					if (ResultCode.SUCCEEDED(result))
					{
						result = condition.AddSubConditonData(aSubconditionName);
					} //	end if
				} //	end if

				return result;
			}
			catch (Exception e)
			{
				Application.Instance.Trace(EnumTraceLevel.ERR,
				                           EnumTraceGroup.OPCSERVER,
				                           "Category.AddCondition",
				                           "Exception caught:" + e.ToString());
				return (int) EnumResultCode.E_FAIL;
			} //	end try ... catch
		} //	end AddSubConditionDefinition