/// <summary> /// read History data /// </summary> /// <param name="tag">节点的索引</param> /// <param name="start">开始时间</param> /// <param name="end">结束时间</param> /// <param name="count">读取的个数</param> /// <param name="containBound">是否包含边界</param> /// <returns>读取的数据列表</returns> public IEnumerable <DataValue> ReadHistoryRawDataValues(string tag, DateTime start, DateTime end, uint count = 1, bool containBound = false) { HistoryReadValueId m_nodeToContinue = new HistoryReadValueId( ) { NodeId = new NodeId(tag), }; ReadRawModifiedDetails m_details = new ReadRawModifiedDetails { StartTime = start, EndTime = end, NumValuesPerNode = count, IsReadModified = false, ReturnBounds = containBound }; HistoryReadValueIdCollection nodesToRead = new HistoryReadValueIdCollection( ); nodesToRead.Add(m_nodeToContinue); m_session.HistoryRead( null, new ExtensionObject(m_details), TimestampsToReturn.Both, false, nodesToRead, out HistoryReadResultCollection results, out DiagnosticInfoCollection diagnosticInfos); ClientBase.ValidateResponse(results, nodesToRead); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead); if (StatusCode.IsBad(results[0].StatusCode)) { throw new ServiceResultException(results[0].StatusCode); } HistoryData values = ExtensionObject.ToEncodeable(results[0].HistoryData) as HistoryData; foreach (var value in values.DataValues) { yield return(value); } }
/// <summary> /// Fetches the recent history. /// </summary> private void ReadProcessed() { AvailableAggregate aggregate = (AvailableAggregate)AggregateCB.SelectedItem; ReadProcessedDetails details = new ReadProcessedDetails(); details.StartTime = StartTimeDP.Value.ToUniversalTime(); details.EndTime = EndTimeDP.Value.ToUniversalTime(); details.ProcessingInterval = (double)ResampleIntervalNP.Value; details.AggregateType.Add(aggregate.NodeId); details.AggregateConfiguration.UseServerCapabilitiesDefaults = true; HistoryReadValueIdCollection nodesToRead = new HistoryReadValueIdCollection(); HistoryReadValueId nodeToRead = new HistoryReadValueId(); nodeToRead.NodeId = m_nodeId; nodesToRead.Add(nodeToRead); HistoryReadResultCollection results = null; DiagnosticInfoCollection diagnosticInfos = null; m_session.HistoryRead( null, new ExtensionObject(details), TimestampsToReturn.Both, false, nodesToRead, out results, out diagnosticInfos); ClientBase.ValidateResponse(results, nodesToRead); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead); if (StatusCode.IsBad(results[0].StatusCode)) { throw new ServiceResultException(results[0].StatusCode); } HistoryData values = ExtensionObject.ToEncodeable(results[0].HistoryData) as HistoryData; DisplayResults(values); // save any continuation point. SaveContinuationPoint(details, nodeToRead, results[0].ContinuationPoint); }
public string AddRide(Ride ride) { string query = "insert into Ride(Id,PublisherId,PickUp,[Drop],StartDate,NumberOfSeats,Price,VehicleId,AutoApproveRide,StatusId) " + "values(@Id,@PublisherId,@PickUp,@Drop,@StartDate,@NumberOfSeats,@Price,@VehicleId,@AutoApproveRide,@Status)"; DynamicParameters parameters = new DynamicParameters(); ride.Id = Guid.NewGuid().ToString(); string statusQuery = "select * from Status where Type='Ride' and Value='Not Started'"; ExtensionObject statusExtensionObject = new ExtensionObject() { Query = statusQuery, ConnectionString = connectionString }; string rideStatusId = statusExtensionObject.GetItem <Status>().Id; ride.AutoApproveRide = false; parameters.Add("Id", ride.Id); parameters.Add("PublisherId", ride.Publisher.Id); parameters.Add("PickUp", ride.PickUp.ToLower()); parameters.Add("Drop", ride.Drop.ToLower()); parameters.Add("StartDate", ride.StartDate); parameters.Add("NumberOfSeats", ride.NumberOfSeats); //parameters.Add("AvailableSeats", ride.AvailableSeats); parameters.Add("Price", ride.Price); parameters.Add("VehicleId", ride.Vehicle.Id); parameters.Add("AutoApproveRide", ride.AutoApproveRide); parameters.Add("Status", rideStatusId); ExtensionObject extensionObject = new ExtensionObject() { Query = query, ConnectionString = connectionString }; if (extensionObject.AddOrUpdateItem <Ride>(parameters)) { return(ride.Id); } else { return(null); } }
/// <summary> /// Fetches the recent history. /// </summary> private void ReadAtTime() { ReadAtTimeDetails details = new ReadAtTimeDetails(); // generate times DateTime startTime = StartTimeDP.Value.ToUniversalTime(); for (int ii = 0; ii < MaxReturnValuesNP.Value; ii++) { details.ReqTimes.Add(startTime.AddMilliseconds((double)(ii * TimeStepNP.Value))); } HistoryReadValueIdCollection nodesToRead = new HistoryReadValueIdCollection(); HistoryReadValueId nodeToRead = new HistoryReadValueId(); nodeToRead.NodeId = m_nodeId; nodesToRead.Add(nodeToRead); HistoryReadResultCollection results = null; DiagnosticInfoCollection diagnosticInfos = null; m_session.HistoryRead( null, new ExtensionObject(details), TimestampsToReturn.Both, false, nodesToRead, out results, out diagnosticInfos); ClientBase.ValidateResponse(results, nodesToRead); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead); if (StatusCode.IsBad(results[0].StatusCode)) { throw new ServiceResultException(results[0].StatusCode); } HistoryData values = ExtensionObject.ToEncodeable(results[0].HistoryData) as HistoryData; DisplayResults(values); // save any continuation point. SaveContinuationPoint(details, nodeToRead, results[0].ContinuationPoint); }
public List <Ride> FindRide(string from, string to) { from = from.ToLower(); to = to.ToLower(); List <Ride> requiredRides = new List <Ride>(); int availableSeats = 0; IBookingService bookingService = new BookingService(configuration); IViaPointService viaPointService = new ViaPointService(configuration); string query = "select * from Ride"; ExtensionObject extensionObject = new ExtensionObject() { Query = query, ConnectionString = connectionString }; List <Ride> rides = extensionObject.GetAllItems <Ride>(); foreach (Ride ride in rides) { availableSeats = bookingService.AvailableSeats(ride, from, to); if (availableSeats > 0) { ride.AvailableSeats = availableSeats; query = "select id,name,phoneNumber from [User] where Id= (select publisherId from Ride where Id='" + ride.Id + "')"; ExtensionObject publisherExtensionObject = new ExtensionObject() { Query = query, ConnectionString = connectionString }; ride.Publisher = publisherExtensionObject.GetItem <User>(); query = "select value from Status where Id=(select statusId from Ride where Id='" + ride.Id + "')"; ExtensionObject statusExtensionObject = new ExtensionObject() { Query = query, ConnectionString = connectionString }; ride.Status = statusExtensionObject.GetItem <Status>(); requiredRides.Add(ride); } } return(requiredRides); }
/// <summary> /// Converts a remote ExtensionObject to a local ExtensionObject. /// </summary> private ExtensionObject ToExtensionObject(ExtensionObject extension, int[] namespaceIndexes) { if (ExtensionObject.IsNull(extension)) { return(extension); } Argument argument = extension.Body as Argument; if (argument != null) { Argument argument2 = (Argument)argument.MemberwiseClone(); argument2.DataType = ToId(argument.DataType, namespaceIndexes); return(new ExtensionObject(null, argument2)); } return(extension); }
public ExtensionObject[] ReadExtensionObjectArray(string fieldName) { int num = this.ReadArrayLength(); if (num == -1) { return(null); } var list = new ExtensionObject[num]; for (int i = 0; i < num; i++) { list[i] = this.ReadExtensionObject(null); } return(list); }
public bool LogException(string exception, string methodName) { string query = "insert into Log(Id,Method,Exception,TimeStamp) values(@Id,@Method,@Exception,@TimeStamp)"; DynamicParameters parameters = new DynamicParameters(); parameters.Add("Id", Guid.NewGuid().ToString()); parameters.Add("Method", methodName); parameters.Add("Exception", exception); parameters.Add("Timestamp", DateTime.Now); ExtensionObject extensionObject = new ExtensionObject() { Query = query, ConnectionString = connectionString }; return(extensionObject.AddOrUpdateItem <Log>(parameters)); }
private void ShowResults() { GoBTN.Visible = (m_result == null || m_result.ContinuationPoint == null || m_result.ContinuationPoint.Length == 0); NextBTN.Visible = !GoBTN.Visible; StopBTN.Enabled = (m_result != null && m_result.ContinuationPoint != null && m_result.ContinuationPoint.Length > 0); if (m_result == null) { return; } HistoryData results = ExtensionObject.ToEncodeable(m_result.HistoryData) as HistoryData; if (results == null) { return; } for (int ii = 0; ii < results.DataValues.Count; ii++) { StatusCode status = results.DataValues[ii].StatusCode; string index = Utils.Format("[{0}]", m_index++); string timestamp = results.DataValues[ii].SourceTimestamp.ToLocalTime().ToString("yyyy-MM-dd hh:mm:ss"); string value = Utils.Format("{0}", results.DataValues[ii].WrappedValue); string quality = Utils.Format("{0}", (StatusCode)status.CodeBits); string historyInfo = Utils.Format("{0:X2}", (int)status.AggregateBits); ListViewItem item = new ListViewItem(index); item.SubItems.Add(timestamp); item.SubItems.Add(value); item.SubItems.Add(quality); item.SubItems.Add(historyInfo); ResultsLV.Items.Add(item); } // adjust width of all columns. for (int ii = 0; ii < ResultsLV.Columns.Count; ii++) { ResultsLV.Columns[ii].Width = -2; } }
/// <summary> /// Fetches the recent history. /// </summary> private void ReadRaw(bool isReadModified) { ReadRawModifiedDetails details = new ReadRawModifiedDetails(); details.StartTime = (StartTimeCK.Checked)?StartTimeDP.Value.ToUniversalTime():DateTime.MinValue; details.EndTime = (EndTimeCK.Checked)?EndTimeDP.Value.ToUniversalTime():DateTime.MinValue; details.NumValuesPerNode = (MaxReturnValuesCK.Checked)?(uint)MaxReturnValuesNP.Value:0; details.IsReadModified = isReadModified; details.ReturnBounds = (isReadModified)?false:ReturnBoundsCK.Checked; HistoryReadValueIdCollection nodesToRead = new HistoryReadValueIdCollection(); HistoryReadValueId nodeToRead = new HistoryReadValueId(); nodeToRead.NodeId = m_nodeId; nodesToRead.Add(nodeToRead); HistoryReadResultCollection results = null; DiagnosticInfoCollection diagnosticInfos = null; m_session.HistoryRead( null, new ExtensionObject(details), TimestampsToReturn.Both, false, nodesToRead, out results, out diagnosticInfos); ClientBase.ValidateResponse(results, nodesToRead); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead); if (StatusCode.IsBad(results[0].StatusCode)) { throw new ServiceResultException(results[0].StatusCode); } HistoryData values = ExtensionObject.ToEncodeable(results[0].HistoryData) as HistoryData; DisplayResults(values); // save any continuation point. SaveContinuationPoint(details, nodeToRead, results[0].ContinuationPoint); }
public bool IsExistingUser(string email) { string query = "select * from [User] where Email='" + email + "'"; ExtensionObject extensionObject = new ExtensionObject() { Query = query, ConnectionString = connectionString }; User user = extensionObject.GetItem <User>(); if (user == null) { return(false); } else { return(true); } }
public bool UpdateUser(User user) { string query = "update [User] set Name=@Name,Email=@Email,PhoneNumber=@PhoneNumber,Address=@Address,Password=@Password where Id=@Id"; DynamicParameters parameters = new DynamicParameters(); parameters.Add("Id", user.Id); parameters.Add("Name", user.Name); parameters.Add("Email", user.Email); parameters.Add("PhoneNumber", user.PhoneNumber); parameters.Add("Address", user.Address); parameters.Add("Password", user.Password); ExtensionObject extensionObject = new ExtensionObject() { Query = query, ConnectionString = connectionString }; return(extensionObject.AddOrUpdateItem <User>(parameters)); }
/// <summary> /// Get the application record. /// </summary> /// <param name="applicationId">The application id.</param> /// <returns>The application record for the specified application id.</returns> public ApplicationRecordDataType GetApplication(NodeId applicationId) { if (!IsConnected) { Connect(); } var outputArguments = Session.Call( ExpandedNodeId.ToNodeId(Opc.Ua.Gds.ObjectIds.Directory, Session.NamespaceUris), ExpandedNodeId.ToNodeId(Opc.Ua.Gds.MethodIds.Directory_GetApplication, Session.NamespaceUris), applicationId); if (outputArguments.Count >= 1) { return(ExtensionObject.ToEncodeable(outputArguments[0] as ExtensionObject) as ApplicationRecordDataType); } return(null); }
internal static bool SaveDescription(Extensions form, ExtensionObjectList extensionObjectList) { TreeView extensionTreeView = form.extensionTreeView; TextBox descriptionTextBox = form.descriptionTextBox; if (String.IsNullOrEmpty(descriptionTextBox.Text)) { WindowManager.ShowAlertBox(form, LanguageUtil.GetCurrentLanguageString("ExtensionNameNotEmpty", className)); descriptionTextBox.Focus(); return(true); } ExtensionObject selectedExtensionObject = null; foreach (ExtensionObject extensionObject in extensionObjectList) { if (extensionObject.Description != extensionTreeView.SelectedNode.Text && extensionObject.Description == descriptionTextBox.Text) { WindowManager.ShowAlertBox(form, LanguageUtil.GetCurrentLanguageString("AlreadyExists", className)); descriptionTextBox.Focus(); return(true); } if (extensionObject.Description == extensionTreeView.SelectedNode.Text) { selectedExtensionObject = extensionObject; } } if (selectedExtensionObject == null) { String error = LanguageUtil.GetCurrentLanguageString("Saving", className); ExtensionException exception = new ExtensionException(error); WindowManager.ShowErrorBox(form, error, exception); return(false); } selectedExtensionObject.Description = descriptionTextBox.Text; extensionTreeView.SelectedNode.Text = selectedExtensionObject.Description; return(true); }
/// <summary>读取一连串的历史数据,并将其转化成指定的类型</summary> /// <param name="url">节点的索引</param> /// <param name="start">开始时间</param> /// <param name="end">结束时间</param> /// <param name="count">读取的个数</param> /// <param name="containBound">是否包含边界</param> /// <returns></returns> public IEnumerable <T> ReadHistoryRawDataValues <T>(string url, DateTime start, DateTime end, uint count = 1, bool containBound = false) { HistoryReadValueId m_nodeToContinue = new HistoryReadValueId() { NodeId = new NodeId(url) }; ReadRawModifiedDetails rawModifiedDetails = new ReadRawModifiedDetails(); rawModifiedDetails.StartTime = start.ToUniversalTime(); rawModifiedDetails.EndTime = end.ToUniversalTime(); rawModifiedDetails.NumValuesPerNode = count; int num1 = 0; rawModifiedDetails.IsReadModified = num1 != 0; int num2 = containBound ? 1 : 0; rawModifiedDetails.ReturnBounds = num2 != 0; ReadRawModifiedDetails m_details = rawModifiedDetails; HistoryReadValueIdCollection nodesToRead = new HistoryReadValueIdCollection(); nodesToRead.Add(m_nodeToContinue); HistoryReadResultCollection results; DiagnosticInfoCollection diagnosticInfos; this.m_session.HistoryRead((RequestHeader)null, new ExtensionObject((object)m_details), TimestampsToReturn.Both, false, nodesToRead, out results, out diagnosticInfos); ClientBase.ValidateResponse((IList)results, (IList)nodesToRead); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, (IList)nodesToRead); if (StatusCode.IsBad(results[0].StatusCode)) { throw new ServiceResultException((ServiceResult)results[0].StatusCode); } HistoryData values = ExtensionObject.ToEncodeable(results[0].HistoryData) as HistoryData; foreach (DataValue dataValue in (List <DataValue>)values.DataValues) { DataValue value = dataValue; yield return((T)value.Value); value = (DataValue)null; } List <DataValue> .Enumerator enumerator = new List <DataValue> .Enumerator(); }
public bool UpdateVehicle(Vehicle vehicle) { string query = "update Vehicle set Model=@Model,Number=@Number,VehicleTypeId=@vehicleTypeId,IsActive=@IsActive where Id=@Id)"; vehicle.Id = Guid.NewGuid().ToString(); DynamicParameters parameters = new DynamicParameters(); parameters.Add("Id", vehicle.Id); parameters.Add("Model", vehicle.Model); parameters.Add("Number", vehicle.Number); parameters.Add("VehicleTypeId", vehicle.VehicleType.Id); parameters.Add("IsActive", vehicle.IsActive); ExtensionObject extensionObject = new ExtensionObject() { Query = query, ConnectionString = connectionString }; return(extensionObject.AddOrUpdateItem <Vehicle>(parameters)); }
/// <summary> /// Create an enum type from an EnumDefinition in an ExtensionObject. /// Available since OPC UA V1.04 in the DataTypeDefinition attribute. /// </summary> public Type AddEnumType(QualifiedName typeName, ExtensionObject typeDefinition) { if (!(typeDefinition.Body is EnumDefinition enumDefinition)) { throw new ArgumentNullException(nameof(typeDefinition)); } var enumBuilder = m_moduleBuilder.DefineEnum( GetFullQualifiedTypeName(typeName), TypeAttributes.Public, typeof(int)); enumBuilder.DataContractAttribute(m_targetNamespace); foreach (var enumValue in enumDefinition.Fields) { var newEnum = enumBuilder.DefineLiteral(enumValue.Name, (int)enumValue.Value); newEnum.EnumMemberAttribute(enumValue.Name, (int)enumValue.Value); } return(enumBuilder.CreateTypeInfo()); }
internal static ExtensionObjectList GetExtensionObjectListFromExFile() { ExtensionObjectList extensionObjectList = new ExtensionObjectList(); String fileContent = FileUtil.ReadToEndWithStandardEncoding(Path.Combine(ConstantUtil.ApplicationExecutionPath(), ConstantUtil.exFile)); String[] separator = { Environment.NewLine }; String[] splittedFileContent = fileContent.Split(separator, StringSplitOptions.RemoveEmptyEntries); foreach (String extensionString in splittedFileContent) { separator[0] = "|"; String[] splittedExtensionContent = extensionString.Split(separator, StringSplitOptions.RemoveEmptyEntries); ExtensionObject extensionObject = new ExtensionObject(splittedExtensionContent[0], splittedExtensionContent[1], Convert.ToBoolean(splittedExtensionContent[2])); extensionObjectList.Add(extensionObject); } return(extensionObjectList); }
/// <summary> /// Queries the GDS for any servers matching the criteria. /// </summary> /// <param name="startingRecordId">The id of the first record to return.</param> /// <param name="maxRecordsToReturn">The max records to return.</param> /// <param name="applicationName">The filter applied to the application name.</param> /// <param name="applicationUri">The filter applied to the application uri.</param> /// <param name="applicationType">The filter applied to the application uri.</param> /// <param name="productUri">The filter applied to the product uri.</param> /// <param name="serverCapabilities">The filter applied to the server capabilities.</param> /// <param name="lastCounterResetTime">The time when the counter was last changed.</param> /// <param name="nextRecordId">The id of the next record.</param> /// <returns>A enumerator used to access the results.</returns> public IList <ApplicationDescription> QueryApplications( uint startingRecordId, uint maxRecordsToReturn, string applicationName, string applicationUri, uint applicationType, string productUri, IList <string> serverCapabilities, out DateTime lastCounterResetTime, out uint nextRecordId) { lastCounterResetTime = DateTime.MinValue; nextRecordId = 0; if (!IsConnected) { Connect(); } var outputArguments = Session.Call( ExpandedNodeId.ToNodeId(Opc.Ua.Gds.ObjectIds.Directory, Session.NamespaceUris), ExpandedNodeId.ToNodeId(Opc.Ua.Gds.MethodIds.Directory_QueryApplications, Session.NamespaceUris), startingRecordId, maxRecordsToReturn, applicationName, applicationUri, applicationType, productUri, serverCapabilities); ApplicationDescription[] applications = null; if (outputArguments.Count >= 3) { lastCounterResetTime = (DateTime)outputArguments[0]; nextRecordId = (uint)outputArguments[1]; applications = (ApplicationDescription[])ExtensionObject.ToArray(outputArguments[2] as ExtensionObject[], typeof(ApplicationDescription)); } return(applications); }
public static List <T> GetAllItems <T>(this ExtensionObject extensionObject) { try { using (var connection = new SqlConnection(extensionObject.ConnectionString)) { if (connection.State == ConnectionState.Closed) { connection.Open(); } return(connection.Query <T>(extensionObject.Query).ToList()); } } catch (Exception exception) { LogService logService = new LogService(extensionObject.ConnectionString); logService.LogException(exception.GetType().ToString(), "GetAll" + typeof(T).Name.ToString()); return(null); } }
/// <summary> /// Initialize Conection properties from connection configuration object /// </summary> private void Initialize() { NetworkAddressUrlDataType networkAddressUrlState = ExtensionObject.ToEncodeable(PubSubConnectionConfiguration.Address) as NetworkAddressUrlDataType; if (networkAddressUrlState == null) { Utils.Trace(Utils.TraceMasks.Error, "The configuration for connection {0} has invalid Address configuration.", PubSubConnectionConfiguration.Name); return; } // set properties NetworkInterfaceName = networkAddressUrlState.NetworkInterface; NetworkAddressEndPoint = UdpClientCreator.GetEndPoint(networkAddressUrlState.Url); if (NetworkAddressEndPoint == null) { Utils.Trace(Utils.TraceMasks.Error, "The configuration for connection {0} with Url:'{1}' resulted in an invalid endpoint.", PubSubConnectionConfiguration.Name, networkAddressUrlState.Url); } }
public static T GetItem <T>(this ExtensionObject extensionObject) { try { using (var connection = new SqlConnection(extensionObject.ConnectionString)) { if (connection.State == ConnectionState.Closed) { connection.Open(); } return(connection.Query <T>(extensionObject.Query).FirstOrDefault()); } } catch (Exception exception) { LogService logService = new LogService(extensionObject.ConnectionString); logService.LogException(exception.GetType().ToString(), "Get" + typeof(T).Name.ToString()); return(default(T)); } }
/// <summary> /// Finds the applications with the specified application uri. /// </summary> /// <param name="applicationUri">The application URI.</param> /// <returns>The matching application.</returns> public ApplicationRecordDataType[] FindApplication(string applicationUri) { if (!IsConnected) { Connect(); } var outputArguments = Session.Call( ExpandedNodeId.ToNodeId(Opc.Ua.Gds.ObjectIds.Directory, Session.NamespaceUris), ExpandedNodeId.ToNodeId(Opc.Ua.Gds.MethodIds.Directory_FindApplications, Session.NamespaceUris), applicationUri); ApplicationRecordDataType[] applications = null; if (outputArguments.Count > 0) { applications = (ApplicationRecordDataType[])ExtensionObject.ToArray(outputArguments[0] as ExtensionObject[], typeof(ApplicationRecordDataType)); } return(applications); }
/// <summary> /// Returns the server status as a structure. /// </summary> public object GetServerStatus() { lock (m_lock) { // update the current time. m_serverStatus.CurrentTime = DateTime.UtcNow; // The server status is a structure type that must be wrapped with an ExtensionObject // The TypeId tells the receiver what is contained in the Body of the ExtensionObject // In this case the body contains the ServerStatus serialized as an XML document. // The schema for the ServerStatusDataType is defined in Opc.Ua.Types.cs but any // schema can be used. The identifier is a Node in the address space. ExtensionObject extension = new ExtensionObject( new ExpandedNodeId(Objects.ServerStatusDataType_Encoding_DefaultXml), m_serverStatus); // return the extension. return(extension); } }
public void WriteExtensionObject(string fieldName, ExtensionObject value) { if (value == null || value.BodyType == BodyType.None) { this.WriteNodeId(null, NodeId.Null); this.WriteByte(null, 0x00); return; } if (value.BodyType == BodyType.ByteString) { this.WriteNodeId(null, ExpandedNodeId.ToNodeId(value.TypeId, this.channel?.NamespaceUris)); this.WriteByte(null, 0x01); this.WriteByteString(null, (byte[])value.Body); return; } if (value.BodyType == BodyType.XmlElement) { this.WriteNodeId(null, ExpandedNodeId.ToNodeId(value.TypeId, this.channel?.NamespaceUris)); this.WriteByte(null, 0x02); this.WriteXElement(null, (XElement)value.Body); return; } if (value.BodyType == BodyType.Encodable) { this.WriteNodeId(null, ExpandedNodeId.ToNodeId(value.TypeId, this.channel?.NamespaceUris)); this.WriteByte(null, 0x01); // BodyType Encodable is encoded as ByteString. var pos0 = this.writer.BaseStream.Position; this.WriteInt32(null, -1); var pos1 = this.writer.BaseStream.Position; ((IEncodable)value.Body).Encode(this); var pos2 = this.writer.BaseStream.Position; this.writer.Seek((int)pos0, SeekOrigin.Begin); this.WriteInt32(null, (int)(pos2 - pos1)); this.writer.Seek((int)pos2, SeekOrigin.Begin); return; } }
/// <see cref="BaseListCtrl.UpdateItem" /> protected override void UpdateItem(ListViewItem listItem, object item) { ItemData itemData = item as ItemData; if (itemData == null) { base.UpdateItem(listItem, item); return; } int events = 0; int datachanges = 0; int notifications = 0; foreach (ExtensionObject notification in itemData.NotificationMessage.NotificationData) { notifications++; if (ExtensionObject.IsNull(notification)) { continue; } DataChangeNotification datachangeNotification = notification.Body as DataChangeNotification; if (datachangeNotification != null) { datachanges += datachangeNotification.MonitoredItems.Count; } EventNotificationList EventNotification = notification.Body as EventNotificationList; if (EventNotification != null) { events += EventNotification.Events.Count; } } listItem.Tag = item; }
public void ValidateUdpPubSubConnectionCreateNetworkMessage() { Assert.IsNotNull(m_udpPublisherConnection, "The UADP connection from standard configuration is invalid."); //Arrange WriterGroupDataType writerGroup0 = m_udpPublisherConnection.PubSubConnectionConfiguration.WriterGroups.First(); UadpWriterGroupMessageDataType messageSettings = ExtensionObject.ToEncodeable(writerGroup0.MessageSettings) as UadpWriterGroupMessageDataType; //Act m_udpPublisherConnection.ResetSequenceNumber(); var networkMessages = m_udpPublisherConnection.CreateNetworkMessages(writerGroup0, new WriterGroupPublishState()); Assert.IsNotNull(networkMessages, "connection.CreateNetworkMessages shall not return null"); var networkMessagesNetworkType = networkMessages.FirstOrDefault(net => net.IsMetaDataMessage == false); Assert.IsNotNull(networkMessagesNetworkType, "connection.CreateNetworkMessages shall return only one network message"); UadpNetworkMessage networkMessage0 = networkMessagesNetworkType as UadpNetworkMessage; Assert.IsNotNull(networkMessage0, "networkMessageEncode should not be null"); //Assert Assert.IsNotNull(networkMessage0, "CreateNetworkMessage did not return an UadpNetworkMessage."); Assert.AreEqual(networkMessage0.DataSetClassId, Guid.Empty, "UadpNetworkMessage.DataSetClassId is invalid."); Assert.AreEqual(networkMessage0.WriterGroupId, writerGroup0.WriterGroupId, "UadpNetworkMessage.WriterGroupId is invalid."); Assert.AreEqual(networkMessage0.UADPVersion, 1, "UadpNetworkMessage.UADPVersion is invalid."); Assert.AreEqual(networkMessage0.SequenceNumber, 1, "UadpNetworkMessage.SequenceNumber is not 1."); Assert.AreEqual(networkMessage0.GroupVersion, messageSettings.GroupVersion, "UadpNetworkMessage.GroupVersion is not valid."); Assert.AreEqual(networkMessage0.PublisherId, m_udpPublisherConnection.PubSubConnectionConfiguration.PublisherId.Value, "UadpNetworkMessage.PublisherId is not valid."); Assert.IsNotNull(networkMessage0.DataSetMessages, "UadpNetworkMessage.UadpDataSetMessages is null."); Assert.AreEqual(networkMessage0.DataSetMessages.Count, 3, "UadpNetworkMessage.UadpDataSetMessages.Count is not 3."); //validate flags Assert.AreEqual((uint)networkMessage0.NetworkMessageContentMask, messageSettings.NetworkMessageContentMask, "UadpNetworkMessage.messageSettings.NetworkMessageContentMask is not valid."); }
public static bool AddOrUpdateItem <T>(this ExtensionObject extensionObject, DynamicParameters parameters) { try { using (var connection = new SqlConnection(extensionObject.ConnectionString)) { if (connection.State == ConnectionState.Closed) { connection.Open(); } connection.Execute(extensionObject.Query, parameters); return(true); } } catch (Exception exception) { LogService logService = new LogService(extensionObject.ConnectionString); logService.LogException(exception.GetType().ToString(), "Add" + typeof(T).Name.ToString()); return(false); } }
/// <summary> /// Activates the session. /// </summary> public byte[] Activate( SignatureData signature, ListOfString localeIds, ExtensionObject userIdentityToken, SignatureData userTokenSignature) { lock (m_lock) { if (m_clientCertificate != null) { // validate the client's signature. byte[] dataToSign = SecurityUtils.Append(m_endpoint.ServerCertificate, m_serverNonce); bool valid = SecurityUtils.Verify( m_clientCertificate, m_endpoint.SecurityPolicyUri, dataToSign, signature); if (!valid) { throw new StatusCodeException( StatusCodes.BadSecurityChecksFailed, "Client did not provide a correct signature for the nonce data provided by the server."); } } m_activated = true; m_localeIds = localeIds; // TBD - validate the user identity token. // return a new nonce. RNGCryptoServiceProvider random = new RNGCryptoServiceProvider(); random.GetBytes(m_serverNonce); return(m_serverNonce); } }
public int GetBookingsCount(string rideId, string from, string to) { string query = "select NumberOfSeatsBooked from Booking where StatusId in (select Id from Status where Type='Booking' and Value='Approved') and RideId='" + rideId + "' and PickUp='" + from + "' and [Drop]='" + to + "'"; ExtensionObject extensionObject = new ExtensionObject() { Query = query, ConnectionString = connectionString }; List <Booking> approvedBookings = extensionObject.GetAllItems <Booking>(); int count = 0; if (approvedBookings == null) { return(count); } foreach (Booking booking in approvedBookings) { count += booking.NumberOfSeatsBooked; } return(count); }
/// <summary> /// Invokes the ActivateSession service. /// </summary> /// <param name="requestHeader">The request header.</param> /// <param name="clientSignature">The client signature.</param> /// <param name="clientSoftwareCertificates">The client software certificates.</param> /// <param name="localeIds">The locale ids.</param> /// <param name="userIdentityToken">The user identity token.</param> /// <param name="userTokenSignature">The user token signature.</param> /// <param name="serverNonce">The server nonce.</param> /// <param name="results">The results.</param> /// <param name="diagnosticInfos">The diagnostic infos.</param> /// <returns> /// Returns a <see cref="ResponseHeader"/> object /// </returns> public override ResponseHeader ActivateSession( RequestHeader requestHeader, SignatureData clientSignature, SignedSoftwareCertificateCollection clientSoftwareCertificates, StringCollection localeIds, ExtensionObject userIdentityToken, SignatureData userTokenSignature, out byte[] serverNonce, out StatusCodeCollection results, out DiagnosticInfoCollection diagnosticInfos) { serverNonce = null; results = null; diagnosticInfos = null; OperationContext context = ValidateRequest(requestHeader, RequestType.ActivateSession); try { // validate client's software certificates. List<SoftwareCertificate> softwareCertificates = new List<SoftwareCertificate>(); if (context.SecurityPolicyUri != SecurityPolicies.None) { bool diagnosticsExist = false; if ((context.DiagnosticsMask & DiagnosticsMasks.OperationAll) != 0) { diagnosticInfos = new DiagnosticInfoCollection(); } results = new StatusCodeCollection(); diagnosticInfos = new DiagnosticInfoCollection(); foreach (SignedSoftwareCertificate signedCertificate in clientSoftwareCertificates) { SoftwareCertificate softwareCertificate = null; ServiceResult result = SoftwareCertificate.Validate( new CertificateValidator(), signedCertificate.CertificateData, out softwareCertificate); if (ServiceResult.IsBad(result)) { results.Add(result.Code); // add diagnostics if requested. if ((context.DiagnosticsMask & DiagnosticsMasks.OperationAll) != 0) { DiagnosticInfo diagnosticInfo = ServerUtils.CreateDiagnosticInfo(ServerInternal, context, result); diagnosticInfos.Add(diagnosticInfo); diagnosticsExist = true; } } else { softwareCertificates.Add(softwareCertificate); results.Add(StatusCodes.Good); // add diagnostics if requested. if ((context.DiagnosticsMask & DiagnosticsMasks.OperationAll) != 0) { diagnosticInfos.Add(null); } } } if (!diagnosticsExist && diagnosticInfos != null) { diagnosticInfos.Clear(); } } // check if certificates meet the server's requirements. ValidateSoftwareCertificates(softwareCertificates); // activate the session. bool identityChanged = ServerInternal.SessionManager.ActivateSession( context, requestHeader.AuthenticationToken, clientSignature, softwareCertificates, userIdentityToken, userTokenSignature, localeIds, out serverNonce); if (identityChanged) { // TBD - call Node Manager and Subscription Manager. } Utils.Trace("Server - SESSION ACTIVATED."); return CreateResponse(requestHeader, StatusCodes.Good); } catch (ServiceResultException e) { Utils.Trace("Server - SESSION ACTIVATE failed. {0}", e.Message); lock (ServerInternal.DiagnosticsLock) { ServerInternal.ServerDiagnostics.RejectedRequestsCount++; if (IsSecurityError(e.StatusCode)) { ServerInternal.ServerDiagnostics.SecurityRejectedRequestsCount++; } } throw TranslateException((DiagnosticsMasks)requestHeader.ReturnDiagnostics, localeIds, e); } finally { OnRequestComplete(context); } }
/// <summary> /// Invokes the HistoryRead service. /// </summary> /// <param name="requestHeader">The request header.</param> /// <param name="historyReadDetails">The history read details.</param> /// <param name="timestampsToReturn">The timestamps to return.</param> /// <param name="releaseContinuationPoints">if set to <c>true</c> continuation points are released.</param> /// <param name="nodesToRead">The nodes to read.</param> /// <param name="results">The results.</param> /// <param name="diagnosticInfos">The diagnostic information for the results.</param> /// <returns> /// Returns a <see cref="ResponseHeader"/> object /// </returns> public override ResponseHeader HistoryRead( RequestHeader requestHeader, ExtensionObject historyReadDetails, TimestampsToReturn timestampsToReturn, bool releaseContinuationPoints, HistoryReadValueIdCollection nodesToRead, out HistoryReadResultCollection results, out DiagnosticInfoCollection diagnosticInfos) { OperationContext context = ValidateRequest(requestHeader, RequestType.HistoryRead); try { if (nodesToRead == null || nodesToRead.Count == 0) { throw new ServiceResultException(StatusCodes.BadNothingToDo); } m_serverInternal.NodeManager.HistoryRead( context, historyReadDetails, timestampsToReturn, releaseContinuationPoints, nodesToRead, out results, out diagnosticInfos); return CreateResponse(requestHeader, context.StringTable); } catch (ServiceResultException e) { lock (ServerInternal.DiagnosticsLock) { ServerInternal.ServerDiagnostics.RejectedRequestsCount++; if (IsSecurityError(e.StatusCode)) { ServerInternal.ServerDiagnostics.SecurityRejectedRequestsCount++; } } throw TranslateException(context, e); } finally { OnRequestComplete(context); } }
/// <summary> /// Activates the session. /// </summary> public byte[] Activate( SignatureData signature, ListOfString localeIds, ExtensionObject userIdentityToken, SignatureData userTokenSignature) { lock (m_lock) { if (m_clientCertificate != null) { // validate the client's signature. byte[] dataToSign = SecurityUtils.Append(m_endpoint.ServerCertificate, m_serverNonce); bool valid = SecurityUtils.Verify( m_clientCertificate, m_endpoint.SecurityPolicyUri, dataToSign, signature); if (!valid) { throw new StatusCodeException( StatusCodes.BadSecurityChecksFailed, "Client did not provide a correct signature for the nonce data provided by the server."); } } m_activated = true; m_localeIds = localeIds; // TBD - validate the user identity token. // return a new nonce. RNGCryptoServiceProvider random = new RNGCryptoServiceProvider(); random.GetBytes(m_serverNonce); return m_serverNonce; } }
/// <summary> /// Validates the identity token supplied by the client. /// </summary> private UserIdentityToken ValidateUserIdentityToken( ExtensionObject identityToken, SignatureData userTokenSignature, out UserTokenPolicy policy ) { policy = null; // check for empty token. if (identityToken == null || identityToken.Body == null) { // not changing the token if already activated. if (m_activated) { return null; } // check if an anonymous login is permitted. if (m_endpoint.UserIdentityTokens != null && m_endpoint.UserIdentityTokens.Count > 0) { bool found = false; for (int ii = 0; ii < m_endpoint.UserIdentityTokens.Count; ii++) { if (m_endpoint.UserIdentityTokens[ii].TokenType == UserTokenType.Anonymous) { found = true; policy = m_endpoint.UserIdentityTokens[ii]; break; } } if (!found) { throw ServiceResultException.Create(StatusCodes.BadUserAccessDenied, "Anonymous user token policy not supported."); } } // create an anonymous token to use for subsequent validation. AnonymousIdentityToken anonymousToken = new AnonymousIdentityToken(); anonymousToken.PolicyId = policy.PolicyId; return anonymousToken; } UserIdentityToken token = null; // check for unrecognized token. if (!typeof( UserIdentityToken ).IsInstanceOfType( identityToken.Body )) { //handle the use case when the UserIdentityToken is binary encoded over xml message encoding if (identityToken.Encoding == ExtensionObjectEncoding.Binary && typeof( byte[] ).IsInstanceOfType( identityToken.Body )) { UserIdentityToken newToken = BaseVariableState.DecodeExtensionObject( null, typeof( UserIdentityToken ), identityToken, false ) as UserIdentityToken; if (newToken == null) { throw ServiceResultException.Create( StatusCodes.BadUserAccessDenied, "Invalid user identity token provided." ); } policy = m_endpoint.FindUserTokenPolicy( newToken.PolicyId ); if (policy == null) { throw ServiceResultException.Create( StatusCodes.BadUserAccessDenied, "User token policy not supported.", "Opc.Ua.Server.Session.ValidateUserIdentityToken" ); } switch (policy.TokenType) { case UserTokenType.Anonymous: token = BaseVariableState.DecodeExtensionObject( null, typeof( AnonymousIdentityToken ), identityToken, true ) as AnonymousIdentityToken; break; case UserTokenType.UserName: token = BaseVariableState.DecodeExtensionObject( null, typeof( UserNameIdentityToken ), identityToken, true ) as UserNameIdentityToken; break; case UserTokenType.Certificate: token = BaseVariableState.DecodeExtensionObject( null, typeof( X509IdentityToken ), identityToken, true ) as X509IdentityToken; break; case UserTokenType.IssuedToken: token = BaseVariableState.DecodeExtensionObject( null, typeof( IssuedIdentityToken ), identityToken, true ) as IssuedIdentityToken; break; default: throw ServiceResultException.Create( StatusCodes.BadUserAccessDenied, "Invalid user identity token provided." ); } } else { throw ServiceResultException.Create( StatusCodes.BadUserAccessDenied, "Invalid user identity token provided." ); } } else { // get the token. token = (UserIdentityToken) identityToken.Body; } // find the user token policy. policy = m_endpoint.FindUserTokenPolicy( token.PolicyId ); if (policy == null) { throw ServiceResultException.Create(StatusCodes.BadIdentityTokenInvalid, "User token policy not supported."); } // determine the security policy uri. string securityPolicyUri = policy.SecurityPolicyUri; if (String.IsNullOrEmpty( securityPolicyUri )) { securityPolicyUri = m_endpoint.SecurityPolicyUri; } if (ServerBase.RequireEncryption(m_endpoint)) { // decrypt the token. if (m_serverCertificate == null) { m_serverCertificate = CertificateFactory.Create(m_endpoint.ServerCertificate, true); // check for valid certificate. if (m_serverCertificate == null) { throw ServiceResultException.Create(StatusCodes.BadConfigurationError, "ApplicationCertificate cannot be found."); } } try { token.Decrypt(m_serverCertificate, m_serverNonce, securityPolicyUri); } catch (Exception e) { if (e is ServiceResultException) { throw; } throw ServiceResultException.Create(StatusCodes.BadIdentityTokenInvalid, e, "Could not decrypt identity token."); } // verify the signature. if (securityPolicyUri != SecurityPolicies.None) { byte[] dataToSign = Utils.Append(m_serverCertificate.RawData, m_serverNonce); if (!token.Verify(dataToSign, userTokenSignature, securityPolicyUri)) { throw new ServiceResultException(StatusCodes.BadUserSignatureInvalid, "Invalid user signature!"); } } } // validate user identity token. return token; }
/// <summary> /// Activates the session and binds it to the current secure channel. /// </summary> public void ValidateBeforeActivate( OperationContext context, SignatureData clientSignature, List<SoftwareCertificate> clientSoftwareCertificates, ExtensionObject userIdentityToken, SignatureData userTokenSignature, StringCollection localeIds, byte[] serverNonce, out UserIdentityToken identityToken, out UserTokenPolicy userTokenPolicy) { lock (m_lock) { // verify that a secure channel was specified. if (context.ChannelContext == null) { throw new ServiceResultException(StatusCodes.BadSecureChannelIdInvalid); } // verify that the same security policy has been used. EndpointDescription endpoint = context.ChannelContext.EndpointDescription; if (endpoint.SecurityPolicyUri != m_endpoint.SecurityPolicyUri || endpoint.SecurityMode != m_endpoint.SecurityMode) { throw new ServiceResultException(StatusCodes.BadSecurityPolicyRejected); } // verify the client signature. if (m_clientCertificate != null) { byte[] dataToSign = Utils.Append(m_serverCertificate.RawData, m_serverNonce); if (!SecurityPolicies.Verify(m_clientCertificate, m_endpoint.SecurityPolicyUri, dataToSign, clientSignature)) { throw new ServiceResultException(StatusCodes.BadApplicationSignatureInvalid); } } if (!m_activated) { // must active the session on the channel that was used to create it. if (m_secureChannelId != context.ChannelContext.SecureChannelId) { throw new ServiceResultException(StatusCodes.BadSecureChannelIdInvalid); } } else { // cannot change the certificates after activation. if (clientSoftwareCertificates != null && clientSoftwareCertificates.Count > 0) { throw new ServiceResultException(StatusCodes.BadInvalidArgument); } } // validate the user identity token. identityToken = ValidateUserIdentityToken(userIdentityToken, userTokenSignature, out userTokenPolicy); TraceState("VALIDATED"); } }
/// <summary> /// Creates and queues a new transaction. /// </summary> private int[] CreateTransaction( TransationType transationType, int transactionId, ExtensionObject details, List<HdaReadRequest> requests, bool asyncReportErrors, out int cancelId) { lock (Lock) { cancelId = ++m_lastCancelId; // create the transaction. ReadRequestTransaction transaction = new ReadRequestTransaction(); transaction.TransationType = transationType; transaction.TransactionId = transactionId; transaction.CancelId = cancelId; transaction.Details = details; transaction.Requests = new List<HdaReadRequest>(); // keep only the valid requests. int[] errors = new int[requests.Count]; for (int ii = 0; ii < requests.Count; ii++) { if (!asyncReportErrors) { errors[ii] = requests[ii].Error; if (errors[ii] < 0) { continue; } } transaction.Requests.Add(requests[ii]); } // queue the transaction. if (transaction.Requests.Count > 0) { m_transactions.Add(transaction.CancelId, transaction); ThreadPool.QueueUserWorkItem(DoRead, transaction); } // return the error list. return errors; } }
/// <summary> /// Checks if the subscription is ready to publish and returns a notification message. /// </summary> public NotificationMessage Publish() { lock (m_lock) { long currentTime = DateTime.UtcNow.Ticks / TimeSpan.TicksPerMillisecond; // check of it is time for a publish. if (m_lastPublishTime + m_publishingInterval < currentTime) { ListOfMonitoredItemNotification notifications = new ListOfMonitoredItemNotification(); ListOfDiagnosticInfo diagnosticInfos = new ListOfDiagnosticInfo(); // check each monitored item for data changes to send. foreach (MonitoredItem monitoredItem in m_monitoredItems.Values) { while (monitoredItem.Values.Count > 0) { MonitoredItemNotification notification = new MonitoredItemNotification(); notification.ClientHandle = monitoredItem.Parameters.ClientHandle; notification.Value = monitoredItem.Values.Dequeue(); notifications.Add(notification); diagnosticInfos.Add(monitoredItem.DiagnosticInfos.Dequeue()); } } // check if any notifications were found. if (notifications.Count > 0) { // subscriptions can produce different types of notifications so the notification parameter // is an extensible parameter. This means the object must be manually serialized and wrapped in // an ExtensionObject which specifies the type of data contained in the Body. The complete // UA SDK takes care this housekeeping and will serialize extensible parameters automatically. DataChangeNotification body = new DataChangeNotification(); body.MonitoredItems = notifications; body.DiagnosticInfos = diagnosticInfos; ExtensionObject extension = new ExtensionObject( new ExpandedNodeId(Objects.DataChangeNotification_Encoding_DefaultXml), body); // construct the message and assign a new sequence number. NotificationMessage message = new NotificationMessage(); message.SequenceNumber = ++m_nextSequenceNumber; message.PublishTime = DateTime.UtcNow; message.NotificationData = new ListOfExtensionObject(); message.NotificationData.Add(extension); m_lastPublishTime = currentTime; m_nextKeepAliveTime = (long)(currentTime + m_publishingInterval * m_keepAliveCount); return message; } } // check if it is time for a keep alive. if (m_nextKeepAliveTime < currentTime) { NotificationMessage message = new NotificationMessage(); message.SequenceNumber = m_nextSequenceNumber; message.PublishTime = DateTime.UtcNow; message.NotificationData = new ListOfExtensionObject(); m_nextKeepAliveTime = (long)(currentTime + m_publishingInterval * m_keepAliveCount); return message; } return null; } }
/// <summary> /// This method executes an extension object values test. /// </summary> /// <param name="channelContext">This parameter stores the channel related data.</param> /// <param name="testCaseContext">This parameter stores the test case parameter values.</param> /// <param name="testCase">This parameter stores the test case related data.</param> /// <param name="iteration">This parameter stores the current iteration number.</param> /// <remarks> /// The test parameters required for this test case are of the /// following types: /// <list type="bullet"> /// <item>MaxStringLength <see cref="TestCaseContext.MaxStringLength"/></item> /// <item>MaxArrayLength <see cref="TestCaseContext.MaxArrayLength"/></item> /// <item>MaxDepth <see cref="TestCaseContext.MaxDepth"/></item> /// </list> /// </remarks> private void ExecuteTest_ExtensionObjectValues(ChannelContext channelContext, TestCaseContext testCaseContext, TestCase testCase, int iteration) { bool isSetupStep = TestUtils.IsSetupIteration(iteration); if (!isSetupStep) { channelContext.EventLogger.LogStartEvent(testCase, iteration); } else { channelContext.ClientSession.OperationTimeout = 30000; } RequestHeader requestHeader = new RequestHeader(); requestHeader.Timestamp = DateTime.UtcNow; requestHeader.ReturnDiagnostics = (uint)DiagnosticsMasks.All; Variant input; Variant output; Variant expectedOutput; if (isSetupStep) { input = new ExtensionObject(); ResponseHeader responseHeader = channelContext.ClientSession.TestStack( requestHeader, testCase.TestId, iteration, input, out output); } else { channelContext.Random.Start( (int)(testCase.Seed + iteration), (int)m_sequenceToExecute.RandomDataStepSize, testCaseContext); input = channelContext.Random.GetExtensionObject(); ResponseHeader responseHeader = channelContext.ClientSession.TestStack( requestHeader, testCase.TestId, iteration, input, out output); channelContext.Random.Start( (int)(testCase.ResponseSeed + iteration), (int)m_sequenceToExecute.RandomDataStepSize, testCaseContext); expectedOutput = channelContext.Random.GetExtensionObject(); if (!Compare.CompareVariant(output, expectedOutput)) { throw new ServiceResultException( StatusCodes.BadInvalidState, Utils.Format("'{0}' is not equal to '{1}'.", output, expectedOutput)); } } if (!isSetupStep) { channelContext.EventLogger.LogCompleteEvent(testCase, iteration); } }
/// <summary> /// Determines if the value contained in an extension object <paramref name="value"/> matches the expected data type. /// </summary> /// <param name="expectedTypeId">The identifier of the expected type .</param> /// <param name="value">The value.</param> /// <returns> /// <c>true</c> if the value contained in an extension object <paramref name="value"/> matches the /// expected data type; otherwise, <c>false</c>. /// </returns> public bool IsEncodingFor(NodeId expectedTypeId, ExtensionObject value) { // no match on null values. if (value == null) { return false; } // check for exact match. if (expectedTypeId == value.TypeId) { return true; } // find the encoding. ILocalNode encoding = Find(value.TypeId) as ILocalNode; if (encoding == null) { return false; } // find data type. foreach (IReference reference in encoding.References.Find(ReferenceTypeIds.HasEncoding, true, true, m_typeTree)) { if (reference.TargetId == expectedTypeId) { return true; } } // no match. return false; }
/// <summary> /// Creates a session with the server. /// </summary> public void CreateSession() { ApplicationDescription description = new ApplicationDescription(); description.ApplicationName = new LocalizedText("UA Sample Client"); description.ApplicationType = ApplicationType.Client_1; description.ApplicationUri = "http://localhost/UASampleClient"; byte[] serverCertificateData; ListOfEndpointDescription serverEndpoints; ListOfSignedSoftwareCertificate serverSoftwareCertificates; SignatureData serverSignature; // create a client nonce. byte[] clientNonce = new byte[32]; RNGCryptoServiceProvider random = new RNGCryptoServiceProvider(); random.GetBytes(clientNonce); string endpointUrl = this.Endpoint.Address.Uri.ToString(); // create the session. CreateSession( CreateRequestHeader(), description, null, this.Endpoint.Address.Uri.ToString(), "My Session", clientNonce, m_clientCertificate.RawData, 600000, 0, out m_sessionId, out m_authenticationToken, out m_sessionTimeout, out m_serverNonce, out serverCertificateData, out serverEndpoints, out serverSoftwareCertificates, out serverSignature, out m_maxRequestMessageSize); // find the endpoint description being used. string securityPolicyUri = ""; Uri url = new Uri(endpointUrl); foreach (EndpointDescription serverEndpoint in serverEndpoints) { Uri url2 = new Uri(serverEndpoint.EndpointUrl); if (url2.Scheme == url.Scheme && url2.Port == url.Port && url2.PathAndQuery == url.PathAndQuery) { securityPolicyUri = serverEndpoint.SecurityPolicyUri; break; } } // validate the server's signature. byte[] dataToSign = SecurityUtils.Append(m_clientCertificate.RawData, clientNonce); bool valid = SecurityUtils.Verify( new X509Certificate2(serverCertificateData), securityPolicyUri, dataToSign, serverSignature); if (!valid) { throw new StatusCodeException( StatusCodes.BadSecurityChecksFailed, "Server did not provide a correct signature for the nonce data provided by the client."); } // create the client signature. dataToSign = SecurityUtils.Append(serverCertificateData, m_serverNonce); SignatureData clientSignature = SecurityUtils.Sign( m_clientCertificate, securityPolicyUri, dataToSign); // use an anonymous user identity token. ExtensionObject userIdentityToken = new ExtensionObject( new ExpandedNodeId(Objects.AnonymousIdentityToken_Encoding_DefaultXml), new AnonymousIdentityToken()); ListOfStatusCode results; ListOfDiagnosticInfo diagnosticInfos; // activate the session. ActivateSession( CreateRequestHeader(), clientSignature, new ListOfSignedSoftwareCertificate(), new ListOfString(), null, null, out m_serverNonce, out results, out diagnosticInfos); }
public EcmaHelpSource (string base_file, bool create) : base (base_file, create) { ExtObject = new ExtensionObject (this); }
/// <summary> /// Reads the processed data. /// </summary> public List<HdaReadRequest> ReadProcessed( DateTime startTime, DateTime endTime, long resampleInterval, int[] serverHandles, uint[] aggregateIds) { Session session = ThrowIfNotConnected(); // create the read requests. ReadProcessedDetails details = new ReadProcessedDetails(); List<HdaReadRequest> requests = CreateReadRequests( session, startTime, endTime, resampleInterval, serverHandles, aggregateIds, details); ExtensionObject extension = new ExtensionObject(details); // fetch all of the values. if (ReadNext(session, extension, requests, false)) { ReadNext(session, extension, requests, true); } return requests; }
/// <summary> /// Reads the modified data. /// </summary> public List<HdaReadRequest> ReadModified( DateTime startTime, DateTime endTime, uint numValues, int[] serverHandles) { Session session = ThrowIfNotConnected(); ReadRawModifiedDetails details = new ReadRawModifiedDetails(); // create the read requests. List<HdaReadRequest> requests = CreateReadRequests( session, startTime, endTime, numValues, false, serverHandles, details); details.IsReadModified = true; for (int ii = 0; ii < requests.Count; ii++) { requests[ii].ModificationInfos = new List<ModificationInfo>(); } ExtensionObject extension = new ExtensionObject(details); // fetch all of the values. if (ReadNext(session, extension, requests, false)) { ReadNext(session, extension, requests, true); } return requests; }
/// <summary> /// Reads the attributes. /// </summary> public List<HdaReadRequest> ReadAttributes( DateTime startTime, DateTime endTime, int serverHandle, uint[] attributeIds) { Session session = ThrowIfNotConnected(); // create the read requests. ReadRawModifiedDetails details = new ReadRawModifiedDetails(); List<HdaReadRequest> requests = CreateReadRequests( session, startTime, endTime, serverHandle, attributeIds, details); ExtensionObject extension = new ExtensionObject(details); // fetch all of the values. if (ReadAttributes(session, extension, requests, false)) { ReadNext(session, extension, requests, true); } return requests; }
/// <summary> /// Returns a ExtensionObject array. /// </summary> public ExtensionObject[] GetExtensionObjectArray() { int length = GetInt32Range(-1, m_context.MaxArrayLength); if (length < 0) { return null; } ExtensionObject[] values = new ExtensionObject[length]; for (int ii = 0; ii < values.Length; ii++) { values[ii] = GetExtensionObject(); } return values; }
/// <summary> /// Validates a filter for a monitored item. /// </summary> private ServiceResult ValidateFilter( NodeMetadata metadata, uint attributeId, ExtensionObject filter, out bool rangeRequired) { rangeRequired = false; // check filter. DataChangeFilter datachangeFilter = null; if (filter != null) { datachangeFilter = filter.Body as DataChangeFilter; } if (datachangeFilter != null) { // get the datatype of the node. NodeId datatypeId = metadata.DataType; // check that filter is valid. ServiceResult error = datachangeFilter.Validate(); if (ServiceResult.IsBad(error)) { return error; } // check datatype of the variable. if (!m_server.TypeTree.IsTypeOf(datatypeId, DataTypes.Number)) { return StatusCodes.BadDeadbandFilterInvalid; } // percent deadbands only allowed for analog data items. if (datachangeFilter.DeadbandType == (uint)(int)DeadbandType.Percent) { ExpandedNodeId typeDefinitionId = metadata.TypeDefinition; if (typeDefinitionId == null) { return StatusCodes.BadDeadbandFilterInvalid; } // percent deadbands only allowed for analog data items. if (!m_server.TypeTree.IsTypeOf(typeDefinitionId, VariableTypes.AnalogItemType)) { return StatusCodes.BadDeadbandFilterInvalid; } // the EURange property is required to use the filter. rangeRequired = true; } } // filter is valid return ServiceResult.Good; }
/// <summary> /// Activates an existing session /// </summary> public virtual bool ActivateSession( OperationContext context, NodeId authenticationToken, SignatureData clientSignature, List<SoftwareCertificate> clientSoftwareCertificates, ExtensionObject userIdentityToken, SignatureData userTokenSignature, StringCollection localeIds, out byte[] serverNonce) { serverNonce = null; Session session = null; UserIdentityToken newIdentity = null; UserTokenPolicy userTokenPolicy = null; lock (m_lock) { // find session. if (!m_sessions.TryGetValue(authenticationToken, out session)) { throw new ServiceResultException(StatusCodes.BadSessionClosed); } // create new server nonce. serverNonce = new byte[m_minNonceLength]; IBuffer buffer = CryptographicBuffer.GenerateRandom((uint) m_minNonceLength); CryptographicBuffer.CopyToByteArray(buffer, out serverNonce); // validate before activation. session.ValidateBeforeActivate( context, clientSignature, clientSoftwareCertificates, userIdentityToken, userTokenSignature, localeIds, serverNonce, out newIdentity, out userTokenPolicy); } IUserIdentity identity = null; IUserIdentity effectiveIdentity = null; ServiceResult error = null; try { // check if the application has a callback which validates the identity tokens. lock (m_eventLock) { if (m_ImpersonateUser != null) { ImpersonateEventArgs args = new ImpersonateEventArgs(newIdentity, userTokenPolicy); m_ImpersonateUser(session, args); if (ServiceResult.IsBad(args.IdentityValidationError)) { error = args.IdentityValidationError; } else { identity = args.Identity; effectiveIdentity = args.EffectiveIdentity; } } } // parse the token manually if the identity is not provided. if (identity == null) { identity = new UserIdentity(newIdentity); } // use the identity as the effectiveIdentity if not provided. if (effectiveIdentity == null) { effectiveIdentity = identity; } } catch (Exception e) { if (e is ServiceResultException) { throw; } throw ServiceResultException.Create( StatusCodes.BadIdentityTokenInvalid, e, "Could not validate user identity token: {0}", newIdentity); } // check for validation error. if (ServiceResult.IsBad(error)) { throw new ServiceResultException(error); } // activate session. bool contextChanged = session.Activate( context, clientSoftwareCertificates, newIdentity, identity, effectiveIdentity, localeIds, serverNonce); // raise session related event. if (contextChanged) { RaiseSessionEvent(session, SessionEventReason.Activated); } // indicates that the identity context for the session has changed. return contextChanged; }
/// <summary> /// Reads the raw data. /// </summary> /// <param name="startTime">The start time.</param> /// <param name="endTime">The end time.</param> /// <param name="numValues">The num values.</param> /// <param name="returnBounds">if set to <c>true</c> the bounds should be returned.</param> /// <param name="serverHandles">The server handles.</param> /// <returns>The results.</returns> public List<HdaReadRequest> ReadRaw( DateTime startTime, DateTime endTime, uint numValues, bool returnBounds, int[] serverHandles) { Session session = ThrowIfNotConnected(); ReadRawModifiedDetails details = new ReadRawModifiedDetails(); // create the read requests. List<HdaReadRequest> requests = CreateReadRequests( session, startTime, endTime, numValues, returnBounds, serverHandles, details); ExtensionObject extension = new ExtensionObject(details); // fetch all of the values. if (ReadNext(session, extension, requests, false)) { ReadNext(session, extension, requests, true); } return requests; }
/// <summary> /// Reads the history of a set of items. /// </summary> public virtual void HistoryRead( OperationContext context, ExtensionObject historyReadDetails, TimestampsToReturn timestampsToReturn, bool releaseContinuationPoints, HistoryReadValueIdCollection nodesToRead, out HistoryReadResultCollection results, out DiagnosticInfoCollection diagnosticInfos) { // validate history details parameter. if (ExtensionObject.IsNull(historyReadDetails)) { throw new ServiceResultException(StatusCodes.BadHistoryOperationInvalid); } HistoryReadDetails details = historyReadDetails.Body as HistoryReadDetails; if (details == null) { throw new ServiceResultException(StatusCodes.BadHistoryOperationUnsupported); } // create result lists. bool diagnosticsExist = false; results = new HistoryReadResultCollection(nodesToRead.Count); diagnosticInfos = new DiagnosticInfoCollection(nodesToRead.Count); // pre-validate items. bool validItems = false; for (int ii = 0; ii < nodesToRead.Count; ii++) { HistoryReadResult result = null; DiagnosticInfo diagnosticInfo = null; // pre-validate and pre-parse parameter. ServiceResult error = HistoryReadValueId.Validate(nodesToRead[ii]); // return error status. if (ServiceResult.IsBad(error)) { nodesToRead[ii].Processed = true; result = new HistoryReadResult(); result.StatusCode = error.Code; // add diagnostics if requested. if ((context.DiagnosticsMask & DiagnosticsMasks.OperationAll) != 0) { diagnosticInfo = ServerUtils.CreateDiagnosticInfo(m_server, context, error); diagnosticsExist = true; } } // found at least one valid item. else { nodesToRead[ii].Processed = false; validItems = true; } results.Add(result); diagnosticInfos.Add(diagnosticInfo); } // call each node manager. if (validItems) { List<ServiceResult> errors = new List<ServiceResult>(results.Count); for (int ii = 0; ii < nodesToRead.Count; ii++) { errors.Add(null); } foreach (INodeManager nodeManager in m_nodeManagers) { nodeManager.HistoryRead( context, details, timestampsToReturn, releaseContinuationPoints, nodesToRead, results, errors); } for (int ii = 0; ii < nodesToRead.Count; ii++) { HistoryReadResult result = results[ii]; // set an error code for nodes that were not handled by any node manager. if (!nodesToRead[ii].Processed) { nodesToRead[ii].Processed = true; result = results[ii] = new HistoryReadResult(); result.StatusCode = StatusCodes.BadNodeIdUnknown; errors[ii] = results[ii].StatusCode; } // update the diagnostic info and ensure the status code in the result is the same as the error code. if (errors[ii] != null && errors[ii].Code != StatusCodes.Good) { if (result == null) { result = results[ii] = new HistoryReadResult(); } result.StatusCode = errors[ii].Code; // add diagnostics if requested. if ((context.DiagnosticsMask & DiagnosticsMasks.OperationAll) != 0) { diagnosticInfos[ii] = ServerUtils.CreateDiagnosticInfo(m_server, context, errors[ii]); diagnosticsExist = true; } } } } // clear the diagnostics array if no diagnostics requested or no errors occurred. UpdateDiagnostics(context, diagnosticsExist, ref diagnosticInfos); }
/// <summary> /// Reads the data at the specified times. /// </summary> public List<HdaReadRequest> ReadAtTime( DateTime[] timestamps, int[] serverHandles) { Session session = ThrowIfNotConnected(); // create the read requests. ReadAtTimeDetails details = new ReadAtTimeDetails(); List<HdaReadRequest> requests = CreateReadRequests( session, timestamps, serverHandles, details); ExtensionObject extension = new ExtensionObject(details); // fetch all of the values. if (ReadNext(session, extension, requests, false)) { ReadNext(session, extension, requests, true); } return requests; }
/// <summary> /// Validates a data change filter provided by the client. /// </summary> /// <param name="context">The system context.</param> /// <param name="source">The node being monitored.</param> /// <param name="attributeId">The attribute being monitored.</param> /// <param name="requestedFilter">The requested monitoring filter.</param> /// <param name="filter">The validated data change filter.</param> /// <param name="range">The EU range associated with the value if required by the filter.</param> /// <returns>Any error condition. Good if no errors occurred.</returns> protected ServiceResult ValidateDataChangeFilter( ISystemContext context, NodeState source, uint attributeId, ExtensionObject requestedFilter, out DataChangeFilter filter, out Range range) { filter = null; range = null; // check for valid filter type. filter = requestedFilter.Body as DataChangeFilter; if (filter == null) { return StatusCodes.BadMonitoredItemFilterUnsupported; } // only supported for value attributes. if (attributeId != Attributes.Value) { return StatusCodes.BadMonitoredItemFilterUnsupported; } // only supported for variables. BaseVariableState variable = source as BaseVariableState; if (variable == null) { return StatusCodes.BadMonitoredItemFilterUnsupported; } // check the datatype. BuiltInType builtInType = TypeInfo.GetBuiltInType(variable.DataType, Server.TypeTree); if (!TypeInfo.IsNumericType(builtInType)) { return StatusCodes.BadMonitoredItemFilterUnsupported; } // validate filter. ServiceResult error = filter.Validate(); if (ServiceResult.IsBad(error)) { return error; } if (filter.DeadbandType ==(uint)DeadbandType.Percent) { BaseVariableState euRange = variable.FindChild(context, BrowseNames.EURange) as BaseVariableState; if (euRange == null) { return StatusCodes.BadMonitoredItemFilterUnsupported; } range = euRange.Value as Range; if (range == null) { return StatusCodes.BadMonitoredItemFilterUnsupported; } } // all good. return ServiceResult.Good; }
/// <summary> /// Validates a monitoring filter. /// </summary> protected static ServiceResult ValidateMonitoringFilter(ExtensionObject filter) { ServiceResult error = null; // check that no filter is specified for non-value attributes. if (!ExtensionObject.IsNull(filter)) { DataChangeFilter datachangeFilter = filter.Body as DataChangeFilter; // validate data change filter. if (datachangeFilter != null) { error = datachangeFilter.Validate(); if (ServiceResult.IsBad(error)) { return error; } } } // passed basic validation. return null; }
/// <summary> /// Reads the historical or current value for attributes. /// </summary> private bool ReadAttributes( Session session, ExtensionObject extension, List<HdaReadRequest> requests, bool releaseContinuationPoints) { ReadRawModifiedDetails details = extension.Body as ReadRawModifiedDetails; if (details == null) { return false; } // check if reading historical values. if (details.EndTime != DateTime.MinValue) { return ReadNext(session, extension, requests, false); } HdaItemHandle handle = null; List<uint> attributeIds = new List<uint>(); List<int> indexes = new List<int>(); // build the list of requests. for (int ii = 0; ii < requests.Count; ii++) { HdaReadRequest request = requests[ii]; if (request.Error < 0) { continue; } // handle should be the same for all. if (handle == null) { handle = request.Handle; } attributeIds.Add(request.AttributeId); indexes.Add(ii); } // check if nothing to do. if (attributeIds.Count == 0) { return false; } // reads the current values for all requested attributes. DaValue[] values = m_itemManager.ReadCurrentValues(session, handle, attributeIds.ToArray()); // build the list of requests. for (int ii = 0; ii < attributeIds.Count; ii++) { HdaReadRequest request = requests[indexes[ii]]; if (values[ii].Error < 0) { request.Error = values[ii].Error; } else { request.Values = new List<DaValue>(); request.Values.Add(values[ii]); } request.IsComplete = true; } return false; }
/// <summary> /// Returns the server status as a structure. /// </summary> public object GetServerStatus() { lock (m_lock) { // update the current time. m_serverStatus.CurrentTime = DateTime.UtcNow; // The server status is a structure type that must be wrapped with an ExtensionObject // The TypeId tells the receiver what is contained in the Body of the ExtensionObject // In this case the body contains the ServerStatus serialized as an XML document. // The schema for the ServerStatusDataType is defined in Opc.Ua.Types.cs but any // schema can be used. The identifier is a Node in the address space. ExtensionObject extension = new ExtensionObject( new ExpandedNodeId(Objects.ServerStatusDataType_Encoding_DefaultXml), m_serverStatus); // return the extension. return extension; } }
public EcmaHelpSource () { ExtObject = new ExtensionObject (this); }
/// <summary> /// Reads the next batch of values from the server. /// </summary> private bool ReadNext( Session session, ExtensionObject details, List<HdaReadRequest> requests, bool releaseContinuationPoints) { // get the value. HistoryReadValueIdCollection nodesToRead = new HistoryReadValueIdCollection(); for (int ii = 0; ii < requests.Count; ii++) { HdaReadRequest request = requests[ii]; if (request.IsComplete || request.Error < 0) { continue; } if (NodeId.IsNull(request.NodeId)) { request.Error = ResultIds.S_NODATA; continue; } HistoryReadValueId nodeToRead = new HistoryReadValueId(); nodeToRead.NodeId = request.NodeId; nodeToRead.ContinuationPoint = request.ContinuationPoint; nodeToRead.Handle = request; nodesToRead.Add(nodeToRead); } // check if something to do. if (nodesToRead.Count == 0) { return false; } HistoryReadResultCollection results = null; DiagnosticInfoCollection diagnosticInfos = null; session.HistoryRead( null, details, TimestampsToReturn.Source, releaseContinuationPoints, nodesToRead, out results, out diagnosticInfos); Session.ValidateResponse(results, nodesToRead); Session.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead); // check if nothing more to do. if (releaseContinuationPoints) { return false; } // process results. bool continuationPoints = false; for (int ii = 0; ii < nodesToRead.Count; ii++) { HdaReadRequest request = (HdaReadRequest)nodesToRead[ii].Handle; if (request.Values == null) { request.Values = new List<DaValue>(); } request.Error = ProcessReadResults( session, results[ii], request.AttributeId, request.Values, request.ModificationInfos); request.ContinuationPoint = results[ii].ContinuationPoint; // check if continuation point provided. if (request.ContinuationPoint != null && request.ContinuationPoint.Length > 0) { request.Error = ResultIds.S_MOREDATA; continuationPoints = true; } else { request.IsComplete = true; } } return continuationPoints; }