diff --git a/.editorconfig b/.editorconfig index 24b72c8f2..12e1f7923 100644 --- a/.editorconfig +++ b/.editorconfig @@ -327,9 +327,15 @@ dotnet_diagnostic.CA1507.severity = # CA1510: Use ArgumentNullException throw helper dotnet_diagnostic.CA1510.severity = none +# CA1711: Identifiers should not have incorrect suffix +dotnet_diagnostic.CA1711.severity = silent + # IDE1005: Simplify delegate invocation dotnet_diagnostic.IDE1005.severity = warning +# CA1305: Specify IFormatProvider +dotnet_diagnostic.CA1305.severity = warning + # exclude generated code [**/Generated/*.cs] generated_code = true diff --git a/Applications/ConsoleReferenceServer/ConsoleUtils.cs b/Applications/ConsoleReferenceServer/ConsoleUtils.cs index c0a8a11b1..d1897107b 100644 --- a/Applications/ConsoleReferenceServer/ConsoleUtils.cs +++ b/Applications/ConsoleReferenceServer/ConsoleUtils.cs @@ -29,6 +29,7 @@ using System; using System.Collections.Generic; +using System.Globalization; using System.IO; using System.Linq; using System.Text; @@ -319,14 +320,18 @@ public static class ConsoleUtils if (logConsole) { loggerConfiguration.WriteTo.Console( - restrictedToMinimumLevel: (LogEventLevel)consoleLogLevel + restrictedToMinimumLevel: (LogEventLevel)consoleLogLevel, + formatProvider: CultureInfo.InvariantCulture ); } #if DEBUG else { loggerConfiguration - .WriteTo.Debug(restrictedToMinimumLevel: (LogEventLevel)consoleLogLevel); + .WriteTo.Debug( + restrictedToMinimumLevel: (LogEventLevel)consoleLogLevel, + formatProvider: CultureInfo.InvariantCulture + ); } #endif LogLevel fileLevel = LogLevel.Information; diff --git a/Applications/Quickstarts.Servers/ReferenceServer/ReferenceNodeManager.cs b/Applications/Quickstarts.Servers/ReferenceServer/ReferenceNodeManager.cs index d455c5fee..6817f123e 100644 --- a/Applications/Quickstarts.Servers/ReferenceServer/ReferenceNodeManager.cs +++ b/Applications/Quickstarts.Servers/ReferenceServer/ReferenceNodeManager.cs @@ -30,6 +30,7 @@ using System; using System.Collections.Generic; using System.Diagnostics; +using System.Globalization; using System.Numerics; using System.Threading; using System.Xml; @@ -233,7 +234,7 @@ public override void CreateAddressSpace(IDictionary> e BaseDataVariableState decimalVariable = CreateVariable(staticFolder, scalarStatic + "Decimal", "Decimal", DataTypeIds.DecimalDataType, ValueRanks.Scalar); // Set an arbitrary precision decimal value. - BigInteger largeInteger = BigInteger.Parse("1234567890123546789012345678901234567890123456789012345"); + BigInteger largeInteger = BigInteger.Parse("1234567890123546789012345678901234567890123456789012345", CultureInfo.InvariantCulture); DecimalDataType decimalValue = new DecimalDataType { Scale = 100, Value = largeInteger.ToByteArray() @@ -1689,8 +1690,8 @@ private DataItemState[] CreateDataItemVariables(NodeState parent, string path, s // now to create the remaining NUMBERED items for (uint i = 0; i < numVariables; i++) { - string newName = string.Format("{0}{1}", name, i.ToString("000")); - string newPath = string.Format("{0}/Mass/{1}", path, newName); + string newName = string.Format(CultureInfo.InvariantCulture, "{0}{1}", name, i.ToString("000")); + string newPath = string.Format(CultureInfo.InvariantCulture, "{0}/Mass/{1}", path, newName); itemsCreated.Add(CreateDataItemVariable(parent, newPath, newName, dataType, valueRank)); }//for i return (itemsCreated.ToArray()); @@ -1722,7 +1723,7 @@ private DataItemState[] CreateDataItemVariables(NodeState parent, string path, s if (typeInfo.BuiltInType != BuiltInType.DateTime) { - double number = Convert.ToDouble(value); + double number = Convert.ToDouble(value, CultureInfo.InvariantCulture); number = Math.Round(number, (int)variable.ValuePrecision.Value); value = Opc.Ua.TypeInfo.Cast(number, typeInfo.BuiltInType); } @@ -1839,9 +1840,9 @@ private AnalogItemState CreateAnalogItemVariable(NodeState parent, string path, /// /// Creates a new variable. /// - private DataItemState CreateTwoStateDiscreteItemVariable(NodeState parent, string path, string name, string trueState, string falseState) + private TwoStateDiscreteState CreateTwoStateDiscreteItemVariable(NodeState parent, string path, string name, string trueState, string falseState) { - TwoStateDiscreteState variable = new TwoStateDiscreteState(parent); + var variable = new TwoStateDiscreteState(parent); variable.NodeId = new NodeId(path, NamespaceIndex); variable.BrowseName = new QualifiedName(path, NamespaceIndex); @@ -1886,7 +1887,7 @@ private DataItemState CreateTwoStateDiscreteItemVariable(NodeState parent, strin /// /// Creates a new variable. /// - private DataItemState CreateMultiStateDiscreteItemVariable(NodeState parent, string path, string name, params string[] values) + private MultiStateDiscreteState CreateMultiStateDiscreteItemVariable(NodeState parent, string path, string name, params string[] values) { MultiStateDiscreteState variable = new MultiStateDiscreteState(parent); @@ -2036,7 +2037,7 @@ private DataItemState CreateMultiStateValueDiscreteItemVariable(NodeState parent return StatusCodes.BadIndexRangeInvalid; } - double number = Convert.ToDouble(value); + double number = Convert.ToDouble(value, CultureInfo.InvariantCulture); if (number >= variable.EnumStrings.Value.Length || number < 0) { @@ -2072,7 +2073,7 @@ private DataItemState CreateMultiStateValueDiscreteItemVariable(NodeState parent return StatusCodes.BadIndexRangeInvalid; } - Int32 number = Convert.ToInt32(value); + Int32 number = Convert.ToInt32(value, CultureInfo.InvariantCulture); if (number >= variable.EnumValues.Value.Length || number < 0) { return StatusCodes.BadOutOfRange; @@ -2137,7 +2138,7 @@ private DataItemState CreateMultiStateValueDiscreteItemVariable(NodeState parent return StatusCodes.BadIndexRangeInvalid; } - double number = Convert.ToDouble(value); + double number = Convert.ToDouble(value, CultureInfo.InvariantCulture); if (variable.InstrumentRange != null && (number < variable.InstrumentRange.Value.Low || number > variable.InstrumentRange.Value.High)) { @@ -2257,8 +2258,8 @@ private BaseDataVariableState[] CreateVariables(NodeState parent, string path, s // now to create the remaining NUMBERED items for (uint i = 0; i < numVariables; i++) { - string newName = string.Format("{0}_{1}", name, i.ToString("00")); - string newPath = string.Format("{0}_{1}", path, newName); + string newName = string.Format(CultureInfo.InvariantCulture, "{0}_{1}", name, i.ToString("00", CultureInfo.InvariantCulture)); + string newPath = string.Format(CultureInfo.InvariantCulture, "{0}_{1}", path, newName); itemsCreated.Add(CreateVariable(newParentFolder, newPath, newName, dataType, valueRank)); } return (itemsCreated.ToArray()); @@ -2297,8 +2298,8 @@ private BaseDataVariableState[] CreateDynamicVariables(NodeState parent, string // now to create the remaining NUMBERED items for (uint i = 0; i < numVariables; i++) { - string newName = string.Format("{0}_{1}", name, i.ToString("00")); - string newPath = string.Format("{0}_{1}", path, newName); + string newName = string.Format(CultureInfo.InvariantCulture, "{0}_{1}", name, i.ToString("00", CultureInfo.InvariantCulture)); + string newPath = string.Format(CultureInfo.InvariantCulture, "{0}_{1}", path, newName); itemsCreated.Add(CreateDynamicVariable(newParentFolder, newPath, newName, dataType, valueRank)); }//for i return (itemsCreated.ToArray()); @@ -2307,7 +2308,7 @@ private BaseDataVariableState[] CreateDynamicVariables(NodeState parent, string /// /// Creates a new variable type. /// - private BaseVariableTypeState CreateVariableType(NodeState parent, IDictionary> externalReferences, string path, string name, BuiltInType dataType, int valueRank) + private BaseDataVariableTypeState CreateVariableType(NodeState parent, IDictionary> externalReferences, string path, string name, BuiltInType dataType, int valueRank) { BaseDataVariableTypeState type = new BaseDataVariableTypeState(); diff --git a/Libraries/Opc.Ua.Client.ComplexTypes/Properties/AssemblyInfo.cs b/Libraries/Opc.Ua.Client.ComplexTypes/Properties/AssemblyInfo.cs index 7873735b4..270759fde 100644 --- a/Libraries/Opc.Ua.Client.ComplexTypes/Properties/AssemblyInfo.cs +++ b/Libraries/Opc.Ua.Client.ComplexTypes/Properties/AssemblyInfo.cs @@ -27,8 +27,10 @@ * http://opcfoundation.org/License/MIT/1.00/ * ======================================================================*/ +using System; using System.Runtime.CompilerServices; +[assembly: CLSCompliant(false)] #if SIGNASSEMBLY [assembly: InternalsVisibleTo("Opc.Ua.Client.ComplexTypes.Tests, PublicKey = " + // OPC Foundation Strong Name Public Key diff --git a/Libraries/Opc.Ua.Client.ComplexTypes/TypeBuilder/AttributeExtensions.cs b/Libraries/Opc.Ua.Client.ComplexTypes/TypeBuilder/AttributeExtensions.cs index c7f1bd493..84a93f95e 100644 --- a/Libraries/Opc.Ua.Client.ComplexTypes/TypeBuilder/AttributeExtensions.cs +++ b/Libraries/Opc.Ua.Client.ComplexTypes/TypeBuilder/AttributeExtensions.cs @@ -29,6 +29,7 @@ using System; using System.Collections.Generic; +using System.Globalization; using System.Reflection; using System.Reflection.Emit; using System.Runtime.Serialization; @@ -191,7 +192,7 @@ public static void EnumMemberAttribute(this FieldBuilder typeBuilder, string Nam }, new object[] // values to assign { - Name+"_"+Value.ToString() + Name+"_"+Value.ToString(CultureInfo.InvariantCulture) }); typeBuilder.SetCustomAttribute(builder); } diff --git a/Libraries/Opc.Ua.Client.ComplexTypes/Types/BaseComplexType.cs b/Libraries/Opc.Ua.Client.ComplexTypes/Types/BaseComplexType.cs index 4db58eee3..56f16ef70 100644 --- a/Libraries/Opc.Ua.Client.ComplexTypes/Types/BaseComplexType.cs +++ b/Libraries/Opc.Ua.Client.ComplexTypes/Types/BaseComplexType.cs @@ -200,7 +200,7 @@ public override string ToString() /// (Unused). Leave this as null /// The provider of a mechanism for retrieving an object to control formatting. /// - /// A containing the value of the current embeded instance in the specified format. + /// A containing the value of the current embedded instance in the specified format. /// /// Thrown if the format parameter is not null public virtual string ToString(string format, IFormatProvider formatProvider) @@ -221,7 +221,7 @@ public virtual string ToString(string format, IFormatProvider formatProvider) if (!NodeId.IsNull(this.TypeId)) { - return String.Format(formatProvider, "{{{0}}}", this.TypeId); + return string.Format(formatProvider, "{{{0}}}", this.TypeId); } return "(null)"; diff --git a/Libraries/Opc.Ua.Client.ComplexTypes/Types/OptionalFieldsComplexType.cs b/Libraries/Opc.Ua.Client.ComplexTypes/Types/OptionalFieldsComplexType.cs index 2bdd8b2a8..92666dca7 100644 --- a/Libraries/Opc.Ua.Client.ComplexTypes/Types/OptionalFieldsComplexType.cs +++ b/Libraries/Opc.Ua.Client.ComplexTypes/Types/OptionalFieldsComplexType.cs @@ -207,7 +207,7 @@ public override string ToString(string format, IFormatProvider formatProvider) if (!NodeId.IsNull(this.TypeId)) { - return String.Format(formatProvider, "{{{0}}}", this.TypeId); + return string.Format(formatProvider, "{{{0}}}", this.TypeId); } return "(null)"; diff --git a/Libraries/Opc.Ua.Client.ComplexTypes/Types/UnionComplexType.cs b/Libraries/Opc.Ua.Client.ComplexTypes/Types/UnionComplexType.cs index 9b3da52ef..63dcd4e56 100644 --- a/Libraries/Opc.Ua.Client.ComplexTypes/Types/UnionComplexType.cs +++ b/Libraries/Opc.Ua.Client.ComplexTypes/Types/UnionComplexType.cs @@ -218,7 +218,7 @@ public override string ToString(string format, IFormatProvider formatProvider) if (!NodeId.IsNull(this.TypeId)) { - return String.Format(formatProvider, "{{{0}}}", this.TypeId); + return string.Format(formatProvider, "{{{0}}}", this.TypeId); } return "(null)"; diff --git a/Libraries/Opc.Ua.Client/Properties/AssemblyInfo.cs b/Libraries/Opc.Ua.Client/Properties/AssemblyInfo.cs index 40f87e0a9..dc5d8aa71 100644 --- a/Libraries/Opc.Ua.Client/Properties/AssemblyInfo.cs +++ b/Libraries/Opc.Ua.Client/Properties/AssemblyInfo.cs @@ -27,8 +27,10 @@ * http://opcfoundation.org/License/MIT/1.00/ * ======================================================================*/ +using System; using System.Runtime.CompilerServices; +[assembly: CLSCompliant(false)] #if SIGNASSEMBLY [assembly: InternalsVisibleTo("Opc.Ua.Client.Tests, PublicKey = " + // OPC Foundation Strong Name Public Key diff --git a/Libraries/Opc.Ua.Client/Session.cs b/Libraries/Opc.Ua.Client/Session.cs index f0c9de8fd..a0e4bfb07 100644 --- a/Libraries/Opc.Ua.Client/Session.cs +++ b/Libraries/Opc.Ua.Client/Session.cs @@ -4033,7 +4033,7 @@ protected virtual bool OnKeepAliveError(ServiceResult result) /// /// Prepare a list of subscriptions to delete. /// - private bool PrepareSubscriptionsToDelete(IEnumerable subscriptions, IList subscriptionsToDelete) + private bool PrepareSubscriptionsToDelete(IEnumerable subscriptions, List subscriptionsToDelete) { bool removed = false; lock (SyncRoot) @@ -4061,7 +4061,7 @@ private bool PrepareSubscriptionsToDelete(IEnumerable subscription IList nodeIdCollection, NodeClass nodeClass, ReadValueIdCollection attributesToRead, - IList> attributesPerNodeId, + List> attributesPerNodeId, IList nodeCollection, bool optionalAttributes) { @@ -4151,7 +4151,7 @@ private void UpdateNamespaceTable(DataValueCollection values, DiagnosticInfoColl DataValueCollection nodeClassValues, DiagnosticInfoCollection diagnosticInfos, ReadValueIdCollection attributesToRead, - IList> attributesPerNodeId, + List> attributesPerNodeId, IList nodeCollection, IList errors, bool optionalAttributes @@ -4429,7 +4429,7 @@ bool optionalAttributes if (value != null) { - variableNode.MinimumSamplingInterval = Convert.ToDouble(attributes[Attributes.MinimumSamplingInterval].Value); + variableNode.MinimumSamplingInterval = Convert.ToDouble(attributes[Attributes.MinimumSamplingInterval].Value, CultureInfo.InvariantCulture); } // AccessLevelEx Attribute @@ -4710,7 +4710,7 @@ bool optionalAttributes /// /// Create a dictionary of attributes to read for a nodeclass. /// - private IDictionary CreateAttributes(NodeClass nodeclass = NodeClass.Unspecified, bool optionalAttributes = true) + private SortedDictionary CreateAttributes(NodeClass nodeclass = NodeClass.Unspecified, bool optionalAttributes = true) { // Attributes to read for all types of nodes var attributes = new SortedDictionary() { diff --git a/Libraries/Opc.Ua.Client/Subscription.cs b/Libraries/Opc.Ua.Client/Subscription.cs index bdebefe71..114e80a3e 100644 --- a/Libraries/Opc.Ua.Client/Subscription.cs +++ b/Libraries/Opc.Ua.Client/Subscription.cs @@ -2433,7 +2433,7 @@ private bool ValidSequentialPublishMessage(IncomingMessage message) /// private bool UpdateMonitoringMode( IList monitoredItems, - IList errors, + List errors, StatusCodeCollection results, DiagnosticInfoCollection diagnosticInfos, ResponseHeader responseHeader, @@ -2518,7 +2518,7 @@ private MonitoredItemCreateRequestCollection PrepareItemsToCreate(out List private void PrepareItemsToModify( MonitoredItemModifyRequestCollection requestItems, - IList itemsToModify) + List itemsToModify) { lock (m_cache) { @@ -2589,7 +2589,7 @@ private MonitoredItemCreateRequestCollection PrepareItemsToCreate(out List private void PrepareResolveItemNodeIds( BrowsePathCollection browsePaths, - IList itemsToBrowse) + List itemsToBrowse) { lock (m_cache) { diff --git a/Libraries/Opc.Ua.Configuration/ApplicationInstance.cs b/Libraries/Opc.Ua.Configuration/ApplicationInstance.cs index e5257b8af..3f2ce8171 100644 --- a/Libraries/Opc.Ua.Configuration/ApplicationInstance.cs +++ b/Libraries/Opc.Ua.Configuration/ApplicationInstance.cs @@ -29,6 +29,7 @@ using System; using System.Collections.Generic; +using System.Globalization; using System.IO; using System.Linq; using System.Net; @@ -513,7 +514,7 @@ public async Task DeleteApplicationInstanceCertificate(CancellationToken ct = de message.AppendLine("Use it instead?"); message.AppendLine("Requested: {0}"); message.AppendLine("Found: {1}"); - if (!await ApplicationInstance.ApproveMessageAsync(String.Format(message.ToString(), id.SubjectName, certificate.Subject), silent).ConfigureAwait(false)) + if (!await ApplicationInstance.ApproveMessageAsync(Utils.Format(message.ToString(), id.SubjectName, certificate.Subject), silent).ConfigureAwait(false)) { throw ServiceResultException.Create(StatusCodes.BadConfigurationError, message.ToString(), id.SubjectName, certificate.Subject); diff --git a/Libraries/Opc.Ua.Configuration/Properties/AssemblyInfo.cs b/Libraries/Opc.Ua.Configuration/Properties/AssemblyInfo.cs new file mode 100644 index 000000000..7c785976a --- /dev/null +++ b/Libraries/Opc.Ua.Configuration/Properties/AssemblyInfo.cs @@ -0,0 +1,44 @@ +/* ======================================================================== + * Copyright (c) 2005-2021 The OPC Foundation, Inc. All rights reserved. + * + * OPC Foundation MIT License 1.00 + * + * Permission is hereby granted, free of charge, to any person + * obtaining a copy of this software and associated documentation + * files (the "Software"), to deal in the Software without + * restriction, including without limitation the rights to use, + * copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following + * conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES + * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + * + * The complete license agreement can be found here: + * http://opcfoundation.org/License/MIT/1.00/ + * ======================================================================*/ + +using System; +using System.Runtime.CompilerServices; + +[assembly: CLSCompliant(false)] +#if SIGNASSEMBLY +[assembly: InternalsVisibleTo("Opc.Ua.Configuration.Tests, PublicKey = " + + // OPC Foundation Strong Name Public Key + "0024000004800000940000000602000000240000525341310004000001000100d987b12f068b35" + + "80429f3dde01397508880fc7e62621397618456ca1549aeacfbdb90c62adfe918f05ce3677b390" + + "f78357b8745cb6e1334655afce1a9527ac92fc829ff585ea79f007e52ba0f83ead627e3edda40b" + + "ec5ae574128fc9342cb57cb8285aa4e5b589c0ebef3be571b5c8f2ab1067f7c880e8f8882a73c8" + + "0a12a1ef")] +#else +[assembly: InternalsVisibleTo("Opc.Ua.Configuration.Tests")] +#endif diff --git a/Libraries/Opc.Ua.Gds.Client.Common/CertificateWrapper.cs b/Libraries/Opc.Ua.Gds.Client.Common/CertificateWrapper.cs index de9fec299..d18b8a138 100644 --- a/Libraries/Opc.Ua.Gds.Client.Common/CertificateWrapper.cs +++ b/Libraries/Opc.Ua.Gds.Client.Common/CertificateWrapper.cs @@ -257,6 +257,7 @@ public override string ToString() public string ToString(string format, IFormatProvider formatProvider) { + if (format != null) throw new FormatException(Utils.Format("Invalid format string: '{0}'.", format)); return SubjectName; } diff --git a/Libraries/Opc.Ua.Gds.Client.Common/Properties/AssemblyInfo.cs b/Libraries/Opc.Ua.Gds.Client.Common/Properties/AssemblyInfo.cs new file mode 100644 index 000000000..2db62cfc8 --- /dev/null +++ b/Libraries/Opc.Ua.Gds.Client.Common/Properties/AssemblyInfo.cs @@ -0,0 +1,44 @@ +/* ======================================================================== + * Copyright (c) 2005-2021 The OPC Foundation, Inc. All rights reserved. + * + * OPC Foundation MIT License 1.00 + * + * Permission is hereby granted, free of charge, to any person + * obtaining a copy of this software and associated documentation + * files (the "Software"), to deal in the Software without + * restriction, including without limitation the rights to use, + * copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following + * conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES + * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + * + * The complete license agreement can be found here: + * http://opcfoundation.org/License/MIT/1.00/ + * ======================================================================*/ + +using System; +using System.Runtime.CompilerServices; + +[assembly: CLSCompliant(false)] +#if SIGNASSEMBLY +[assembly: InternalsVisibleTo("Opc.Ua.Gds.Tests, PublicKey = " + + // OPC Foundation Strong Name Public Key + "0024000004800000940000000602000000240000525341310004000001000100d987b12f068b35" + + "80429f3dde01397508880fc7e62621397618456ca1549aeacfbdb90c62adfe918f05ce3677b390" + + "f78357b8745cb6e1334655afce1a9527ac92fc829ff585ea79f007e52ba0f83ead627e3edda40b" + + "ec5ae574128fc9342cb57cb8285aa4e5b589c0ebef3be571b5c8f2ab1067f7c880e8f8882a73c8" + + "0a12a1ef")] +#else +[assembly: InternalsVisibleTo("Opc.Ua.Gds.Tests")] +#endif diff --git a/Libraries/Opc.Ua.Gds.Client.Common/ServerCapabilities.cs b/Libraries/Opc.Ua.Gds.Client.Common/ServerCapabilities.cs index a5a2aeae7..b3ab7fe8a 100644 --- a/Libraries/Opc.Ua.Gds.Client.Common/ServerCapabilities.cs +++ b/Libraries/Opc.Ua.Gds.Client.Common/ServerCapabilities.cs @@ -184,14 +184,15 @@ public override string ToString() /// /// Returns a that represents this instance. /// - /// The format. + /// The format. Must be null. /// The format provider. /// /// A that represents this instance. /// public string ToString(string format, IFormatProvider formatProvider) { - return "[" + Id + "] " + Description; + if (format != null) throw new FormatException(Utils.Format("Invalid format string: '{0}'.", format)); + return string.Format(formatProvider, "[{0}] {1}", Id, Description); } #region Well Known Identifiers diff --git a/Libraries/Opc.Ua.Gds.Server.Common/Properties/AssemblyInfo.cs b/Libraries/Opc.Ua.Gds.Server.Common/Properties/AssemblyInfo.cs new file mode 100644 index 000000000..2db62cfc8 --- /dev/null +++ b/Libraries/Opc.Ua.Gds.Server.Common/Properties/AssemblyInfo.cs @@ -0,0 +1,44 @@ +/* ======================================================================== + * Copyright (c) 2005-2021 The OPC Foundation, Inc. All rights reserved. + * + * OPC Foundation MIT License 1.00 + * + * Permission is hereby granted, free of charge, to any person + * obtaining a copy of this software and associated documentation + * files (the "Software"), to deal in the Software without + * restriction, including without limitation the rights to use, + * copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following + * conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES + * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + * + * The complete license agreement can be found here: + * http://opcfoundation.org/License/MIT/1.00/ + * ======================================================================*/ + +using System; +using System.Runtime.CompilerServices; + +[assembly: CLSCompliant(false)] +#if SIGNASSEMBLY +[assembly: InternalsVisibleTo("Opc.Ua.Gds.Tests, PublicKey = " + + // OPC Foundation Strong Name Public Key + "0024000004800000940000000602000000240000525341310004000001000100d987b12f068b35" + + "80429f3dde01397508880fc7e62621397618456ca1549aeacfbdb90c62adfe918f05ce3677b390" + + "f78357b8745cb6e1334655afce1a9527ac92fc829ff585ea79f007e52ba0f83ead627e3edda40b" + + "ec5ae574128fc9342cb57cb8285aa4e5b589c0ebef3be571b5c8f2ab1067f7c880e8f8882a73c8" + + "0a12a1ef")] +#else +[assembly: InternalsVisibleTo("Opc.Ua.Gds.Tests")] +#endif diff --git a/Libraries/Opc.Ua.PubSub/Configuration/UaPubSubConfigurationHelper.cs b/Libraries/Opc.Ua.PubSub/Configuration/UaPubSubConfigurationHelper.cs index 097ce8dce..5fa768338 100644 --- a/Libraries/Opc.Ua.PubSub/Configuration/UaPubSubConfigurationHelper.cs +++ b/Libraries/Opc.Ua.PubSub/Configuration/UaPubSubConfigurationHelper.cs @@ -28,6 +28,7 @@ * ======================================================================*/ using System; +using System.Globalization; using System.IO; using System.Runtime.Serialization; using System.Text; @@ -76,8 +77,8 @@ public static PubSubConfigurationDataType LoadConfiguration(string filePath) catch (Exception e) { StringBuilder buffer = new StringBuilder(); - buffer.AppendFormat("Configuration file could not be loaded: {0}\r\n", filePath); - buffer.AppendFormat("Error: {0}", e.Message); + buffer.AppendFormat(CultureInfo.InvariantCulture, "Configuration file could not be loaded: {0}\r\n", filePath); + buffer.AppendFormat(CultureInfo.InvariantCulture, "Error: {0}", e.Message); throw ServiceResultException.Create( StatusCodes.BadConfigurationError, diff --git a/Libraries/Opc.Ua.PubSub/Configuration/UaPubSubConfigurator.cs b/Libraries/Opc.Ua.PubSub/Configuration/UaPubSubConfigurator.cs index c37f47452..4a84e299f 100644 --- a/Libraries/Opc.Ua.PubSub/Configuration/UaPubSubConfigurator.cs +++ b/Libraries/Opc.Ua.PubSub/Configuration/UaPubSubConfigurator.cs @@ -29,6 +29,7 @@ using System; using System.Collections.Generic; +using System.Globalization; using System.IO; namespace Opc.Ua.PubSub.Configuration @@ -294,7 +295,7 @@ public void LoadConfiguration(string configFilePath, bool replaceExisting = true // validate input argument if (configFilePath == null) { - throw new ArgumentException(nameof(configFilePath)); + throw new ArgumentNullException(nameof(configFilePath)); } if (!File.Exists(configFilePath)) { @@ -397,11 +398,7 @@ public StatusCode AddPublishedDataSet(PublishedDataSetDataType publishedDataSetD m_pubSubConfiguration.PublishedDataSets.Add(publishedDataSetDataType); // raise PublishedDataSetAdded event - if (PublishedDataSetAdded != null) - { - PublishedDataSetAdded(this, - new PublishedDataSetEventArgs() { PublishedDataSetId = newPublishedDataSetId, PublishedDataSetDataType = publishedDataSetDataType }); - } + PublishedDataSetAdded?.Invoke(this, new PublishedDataSetEventArgs() { PublishedDataSetId = newPublishedDataSetId, PublishedDataSetDataType = publishedDataSetDataType }); if (publishedDataSetDataType.ExtensionFields == null) { @@ -491,13 +488,10 @@ public StatusCode RemovePublishedDataSet(PublishedDataSetDataType publishedDataS m_idsToParentId.Remove(publishedDataSetId); m_idsToPubSubState.Remove(publishedDataSetId); - if (PublishedDataSetRemoved != null) - { - PublishedDataSetRemoved(this, new PublishedDataSetEventArgs() { - PublishedDataSetId = publishedDataSetId, - PublishedDataSetDataType = publishedDataSetDataType - }); - } + PublishedDataSetRemoved?.Invoke(this, new PublishedDataSetEventArgs() { + PublishedDataSetId = publishedDataSetId, + PublishedDataSetDataType = publishedDataSetDataType + }); return StatusCodes.Good; } } @@ -554,11 +548,7 @@ public StatusCode AddExtensionField(uint publishedDataSetConfigId, KeyValuePair publishedDataSetDataType.ExtensionFields.Add(extensionField); // raise ExtensionFieldAdded event - if (ExtensionFieldAdded != null) - { - ExtensionFieldAdded(this, - new ExtensionFieldEventArgs() { PublishedDataSetId = publishedDataSetConfigId, ExtensionFieldId = newextensionFieldId, ExtensionField = extensionField }); - } + ExtensionFieldAdded?.Invoke(this, new ExtensionFieldEventArgs() { PublishedDataSetId = publishedDataSetConfigId, ExtensionFieldId = newextensionFieldId, ExtensionField = extensionField }); return StatusCodes.Good; } @@ -591,11 +581,7 @@ public StatusCode RemoveExtensionField(uint publishedDataSetConfigId, uint exten publishedDataSetDataType.ExtensionFields.Remove(extensionFieldToRemove); // raise ExtensionFieldRemoved event - if (ExtensionFieldRemoved != null) - { - ExtensionFieldRemoved(this, - new ExtensionFieldEventArgs() { PublishedDataSetId = publishedDataSetConfigId, ExtensionFieldId = extensionFieldConfigId, ExtensionField = extensionField }); - } + ExtensionFieldRemoved?.Invoke(this, new ExtensionFieldEventArgs() { PublishedDataSetId = publishedDataSetConfigId, ExtensionFieldId = extensionFieldConfigId, ExtensionField = extensionField }); return StatusCodes.Good; } } @@ -658,11 +644,7 @@ public StatusCode AddConnection(PubSubConnectionDataType pubSubConnectionDataTyp m_pubSubConfiguration.Connections.Add(pubSubConnectionDataType); // raise ConnectionAdded event - if (ConnectionAdded != null) - { - ConnectionAdded(this, - new ConnectionEventArgs() { ConnectionId = newConnectionId, PubSubConnectionDataType = pubSubConnectionDataType }); - } + ConnectionAdded?.Invoke(this, new ConnectionEventArgs() { ConnectionId = newConnectionId, PubSubConnectionDataType = pubSubConnectionDataType }); //handler reader & writer groups foreach (WriterGroupDataType writerGroup in writerGroups) { @@ -756,13 +738,10 @@ public StatusCode RemoveConnection(PubSubConnectionDataType pubSubConnectionData m_idsToParentId.Remove(connectionId); m_idsToPubSubState.Remove(connectionId); - if (ConnectionRemoved != null) - { - ConnectionRemoved(this, new ConnectionEventArgs() { - ConnectionId = connectionId, - PubSubConnectionDataType = pubSubConnectionDataType - }); - } + ConnectionRemoved?.Invoke(this, new ConnectionEventArgs() { + ConnectionId = connectionId, + PubSubConnectionDataType = pubSubConnectionDataType + }); return StatusCodes.Good; } return StatusCodes.BadNodeIdUnknown; @@ -795,9 +774,9 @@ public StatusCode AddWriterGroup(uint parentConnectionId, WriterGroupDataType wr { throw new ArgumentException("This WriterGroupDataType instance is already added to the configuration."); } - if (!m_idsToObjects.ContainsKey(parentConnectionId)) + if (!m_idsToObjects.TryGetValue(parentConnectionId, out object value)) { - throw new ArgumentException(String.Format("There is no connection with configurationId = {0} in current configuration.", parentConnectionId)); + throw new ArgumentException(Utils.Format("There is no connection with configurationId = {0} in current configuration.", parentConnectionId)); } try { @@ -806,7 +785,7 @@ public StatusCode AddWriterGroup(uint parentConnectionId, WriterGroupDataType wr // remember collections DataSetWriterDataTypeCollection dataSetWriters = new DataSetWriterDataTypeCollection(writerGroupDataType.DataSetWriters); writerGroupDataType.DataSetWriters.Clear(); - if (m_idsToObjects[parentConnectionId] is PubSubConnectionDataType parentConnection) + if (value is PubSubConnectionDataType parentConnection) { //validate duplicate name bool duplicateName = false; @@ -836,11 +815,7 @@ public StatusCode AddWriterGroup(uint parentConnectionId, WriterGroupDataType wr m_idsToPubSubState.Add(newWriterGroupId, GetInitialPubSubState(writerGroupDataType)); // raise WriterGroupAdded event - if (WriterGroupAdded != null) - { - WriterGroupAdded(this, - new WriterGroupEventArgs() { ConnectionId = parentConnectionId, WriterGroupId = newWriterGroupId, WriterGroupDataType = writerGroupDataType }); - } + WriterGroupAdded?.Invoke(this, new WriterGroupEventArgs() { ConnectionId = parentConnectionId, WriterGroupId = newWriterGroupId, WriterGroupDataType = writerGroupDataType }); //handler datasetWriters foreach (DataSetWriterDataType datasetWriter in dataSetWriters) @@ -926,14 +901,11 @@ public StatusCode RemoveWriterGroup(WriterGroupDataType writerGroupDataType) m_idsToParentId.Remove(writerGroupId); m_idsToPubSubState.Remove(writerGroupId); - if (WriterGroupRemoved != null) - { - WriterGroupRemoved(this, new WriterGroupEventArgs() { - WriterGroupId = writerGroupId, - WriterGroupDataType = writerGroupDataType, - ConnectionId = parentConnectionId - }); - } + WriterGroupRemoved?.Invoke(this, new WriterGroupEventArgs() { + WriterGroupId = writerGroupId, + WriterGroupDataType = writerGroupDataType, + ConnectionId = parentConnectionId + }); return StatusCodes.Good; } } @@ -968,15 +940,15 @@ public StatusCode AddDataSetWriter(uint parentWriterGroupId, DataSetWriterDataTy { throw new ArgumentException("This DataSetWriterDataType instance is already added to the configuration."); } - if (!m_idsToObjects.ContainsKey(parentWriterGroupId)) + if (!m_idsToObjects.TryGetValue(parentWriterGroupId, out object value)) { - throw new ArgumentException(String.Format("There is no WriterGroup with configurationId = {0} in current configuration.", parentWriterGroupId)); + throw new ArgumentException(Utils.Format("There is no WriterGroup with configurationId = {0} in current configuration.", parentWriterGroupId)); } try { lock (m_lock) { - if (m_idsToObjects[parentWriterGroupId] is WriterGroupDataType parentWriterGroup) + if (value is WriterGroupDataType parentWriterGroup) { //validate duplicate name bool duplicateName = false; @@ -1007,11 +979,7 @@ public StatusCode AddDataSetWriter(uint parentWriterGroupId, DataSetWriterDataTy m_idsToPubSubState.Add(newDataSetWriterId, GetInitialPubSubState(dataSetWriterDataType)); // raise DataSetWriterAdded event - if (DataSetWriterAdded != null) - { - DataSetWriterAdded(this, - new DataSetWriterEventArgs() { WriterGroupId = parentWriterGroupId, DataSetWriterId = newDataSetWriterId, DataSetWriterDataType = dataSetWriterDataType }); - } + DataSetWriterAdded?.Invoke(this, new DataSetWriterEventArgs() { WriterGroupId = parentWriterGroupId, DataSetWriterId = newDataSetWriterId, DataSetWriterDataType = dataSetWriterDataType }); return StatusCodes.Good; } @@ -1079,14 +1047,11 @@ public StatusCode RemoveDataSetWriter(DataSetWriterDataType dataSetWriterDataTyp m_idsToParentId.Remove(dataSetWriterId); m_idsToPubSubState.Remove(dataSetWriterId); - if (DataSetWriterRemoved != null) - { - DataSetWriterRemoved(this, new DataSetWriterEventArgs() { - WriterGroupId = parentWriterGroupId, - DataSetWriterDataType = dataSetWriterDataType, - DataSetWriterId = dataSetWriterId - }); - } + DataSetWriterRemoved?.Invoke(this, new DataSetWriterEventArgs() { + WriterGroupId = parentWriterGroupId, + DataSetWriterDataType = dataSetWriterDataType, + DataSetWriterId = dataSetWriterId + }); return StatusCodes.Good; } } @@ -1120,9 +1085,9 @@ public StatusCode AddReaderGroup(uint parentConnectionId, ReaderGroupDataType re { throw new ArgumentException("This ReaderGroupDataType instance is already added to the configuration."); } - if (!m_idsToObjects.ContainsKey(parentConnectionId)) + if (!m_idsToObjects.TryGetValue(parentConnectionId, out object value)) { - throw new ArgumentException(String.Format("There is no connection with configurationId = {0} in current configuration.", parentConnectionId)); + throw new ArgumentException(Utils.Format("There is no connection with configurationId = {0} in current configuration.", parentConnectionId)); } try { @@ -1131,7 +1096,7 @@ public StatusCode AddReaderGroup(uint parentConnectionId, ReaderGroupDataType re // remember collections DataSetReaderDataTypeCollection dataSetReaders = new DataSetReaderDataTypeCollection(readerGroupDataType.DataSetReaders); readerGroupDataType.DataSetReaders.Clear(); - if (m_idsToObjects[parentConnectionId] is PubSubConnectionDataType parentConnection) + if (value is PubSubConnectionDataType parentConnection) { //validate duplicate name bool duplicateName = false; @@ -1162,11 +1127,7 @@ public StatusCode AddReaderGroup(uint parentConnectionId, ReaderGroupDataType re m_idsToPubSubState.Add(newReaderGroupId, GetInitialPubSubState(readerGroupDataType)); // raise ReaderGroupAdded event - if (ReaderGroupAdded != null) - { - ReaderGroupAdded(this, - new ReaderGroupEventArgs() { ConnectionId = parentConnectionId, ReaderGroupId = newReaderGroupId, ReaderGroupDataType = readerGroupDataType }); - } + ReaderGroupAdded?.Invoke(this, new ReaderGroupEventArgs() { ConnectionId = parentConnectionId, ReaderGroupId = newReaderGroupId, ReaderGroupDataType = readerGroupDataType }); //handler datasetWriters foreach (DataSetReaderDataType datasetReader in dataSetReaders) @@ -1252,14 +1213,11 @@ public StatusCode RemoveReaderGroup(ReaderGroupDataType readerGroupDataType) m_idsToParentId.Remove(readerGroupId); m_idsToPubSubState.Remove(readerGroupId); - if (ReaderGroupRemoved != null) - { - ReaderGroupRemoved(this, new ReaderGroupEventArgs() { - ReaderGroupId = readerGroupId, - ReaderGroupDataType = readerGroupDataType, - ConnectionId = parentConnectionId - }); - } + ReaderGroupRemoved?.Invoke(this, new ReaderGroupEventArgs() { + ReaderGroupId = readerGroupId, + ReaderGroupDataType = readerGroupDataType, + ConnectionId = parentConnectionId + }); return StatusCodes.Good; } } @@ -1294,15 +1252,15 @@ public StatusCode AddDataSetReader(uint parentReaderGroupId, DataSetReaderDataTy { throw new ArgumentException("This DataSetReaderDataType instance is already added to the configuration."); } - if (!m_idsToObjects.ContainsKey(parentReaderGroupId)) + if (!m_idsToObjects.TryGetValue(parentReaderGroupId, out object value)) { - throw new ArgumentException(String.Format("There is no ReaderGroup with configurationId = {0} in current configuration.", parentReaderGroupId)); + throw new ArgumentException(Utils.Format("There is no ReaderGroup with configurationId = {0} in current configuration.", parentReaderGroupId)); } try { lock (m_lock) { - if (m_idsToObjects[parentReaderGroupId] is ReaderGroupDataType parentReaderGroup) + if (value is ReaderGroupDataType parentReaderGroup) { //validate duplicate name bool duplicateName = false; @@ -1333,11 +1291,7 @@ public StatusCode AddDataSetReader(uint parentReaderGroupId, DataSetReaderDataTy m_idsToPubSubState.Add(newDataSetReaderId, GetInitialPubSubState(dataSetReaderDataType)); // raise WriterGroupAdded event - if (DataSetReaderAdded != null) - { - DataSetReaderAdded(this, - new DataSetReaderEventArgs() { ReaderGroupId = parentReaderGroupId, DataSetReaderId = newDataSetReaderId, DataSetReaderDataType = dataSetReaderDataType }); - } + DataSetReaderAdded?.Invoke(this, new DataSetReaderEventArgs() { ReaderGroupId = parentReaderGroupId, DataSetReaderId = newDataSetReaderId, DataSetReaderDataType = dataSetReaderDataType }); return StatusCodes.Good; } @@ -1405,14 +1359,11 @@ public StatusCode RemoveDataSetReader(DataSetReaderDataType dataSetReaderDataTyp m_idsToParentId.Remove(dataSetReaderId); m_idsToPubSubState.Remove(dataSetReaderId); - if (DataSetReaderRemoved != null) - { - DataSetReaderRemoved(this, new DataSetReaderEventArgs() { - ReaderGroupId = parenReaderGroupId, - DataSetReaderDataType = dataSetReaderDataType, - DataSetReaderId = dataSetReaderId - }); - } + DataSetReaderRemoved?.Invoke(this, new DataSetReaderEventArgs() { + ReaderGroupId = parenReaderGroupId, + DataSetReaderDataType = dataSetReaderDataType, + DataSetReaderId = dataSetReaderId + }); return StatusCodes.Good; } } @@ -1531,19 +1482,15 @@ public StatusCode Disable(object configurationObject) private void SetStateForObject(object configurationObject, PubSubState newState) { uint id = FindIdForObject(configurationObject); - if (id != InvalidId && m_idsToPubSubState.ContainsKey(id)) + if (id != InvalidId && m_idsToPubSubState.TryGetValue(id, out PubSubState oldState)) { - PubSubState oldState = m_idsToPubSubState[id]; m_idsToPubSubState[id] = newState; - if (PubSubStateChanged != null) - { - PubSubStateChanged(this, new PubSubStateChangedEventArgs() { - ConfigurationObject = configurationObject, - ConfigurationObjectId = id, - NewState = newState, - OldState = oldState - }); - } + PubSubStateChanged?.Invoke(this, new PubSubStateChangedEventArgs() { + ConfigurationObject = configurationObject, + ConfigurationObjectId = id, + NewState = newState, + OldState = oldState + }); bool configurationObjectEnabled = (newState == PubSubState.Operational || newState == PubSubState.Paused); //update the Enabled flag in config object if (configurationObject is PubSubConfigurationDataType) diff --git a/Libraries/Opc.Ua.PubSub/Encoding/UadpDataSetMessage.cs b/Libraries/Opc.Ua.PubSub/Encoding/UadpDataSetMessage.cs index 7d98527f1..d88f5564f 100644 --- a/Libraries/Opc.Ua.PubSub/Encoding/UadpDataSetMessage.cs +++ b/Libraries/Opc.Ua.PubSub/Encoding/UadpDataSetMessage.cs @@ -32,6 +32,7 @@ using System.Collections.Generic; using System.Xml; using System.Linq; +using System.Globalization; namespace Opc.Ua.PubSub.Encoding { @@ -380,7 +381,7 @@ private void EncodeMessageDataKeyFrame(BinaryEncoder binaryEncoder) // DataSetFieldCount is not persisted for RawData foreach (Field field in DataSet.Fields) { - UadpDataSetMessage.EncodeFieldAsRawData(binaryEncoder, field); + UadpDataSetMessage.EncodeFieldAsRawData(binaryEncoder, field, CultureInfo.InvariantCulture); } break; case FieldTypeEncodingMask.Reserved: @@ -422,7 +423,7 @@ private void EncodeMessageDataDeltaFrame(BinaryEncoder binaryEncoder) binaryEncoder.WriteDataValue("FieldValue", field.Value); break; case FieldTypeEncodingMask.RawData: - UadpDataSetMessage.EncodeFieldAsRawData(binaryEncoder, field); + UadpDataSetMessage.EncodeFieldAsRawData(binaryEncoder, field, CultureInfo.InvariantCulture); break; case FieldTypeEncodingMask.Reserved: // ignore @@ -675,7 +676,8 @@ private DataSet DecodeMessageDataDeltaFrame(BinaryDecoder binaryDecoder, DataSet /// /// /// - private static void EncodeFieldAsRawData(BinaryEncoder binaryEncoder, Field field) + /// + private static void EncodeFieldAsRawData(BinaryEncoder binaryEncoder, Field field, IFormatProvider formatProvider) { try { @@ -693,40 +695,40 @@ private static void EncodeFieldAsRawData(BinaryEncoder binaryEncoder, Field fiel switch ((BuiltInType)field.FieldMetaData.BuiltInType) { case BuiltInType.Boolean: - binaryEncoder.WriteBoolean("Bool", Convert.ToBoolean(valueToEncode)); + binaryEncoder.WriteBoolean("Bool", Convert.ToBoolean(valueToEncode, formatProvider)); break; case BuiltInType.SByte: - binaryEncoder.WriteSByte("SByte", Convert.ToSByte(valueToEncode)); + binaryEncoder.WriteSByte("SByte", Convert.ToSByte(valueToEncode, formatProvider)); break; case BuiltInType.Byte: - binaryEncoder.WriteByte("Byte", Convert.ToByte(valueToEncode)); + binaryEncoder.WriteByte("Byte", Convert.ToByte(valueToEncode, formatProvider)); break; case BuiltInType.Int16: - binaryEncoder.WriteInt16("Int16", Convert.ToInt16(valueToEncode)); + binaryEncoder.WriteInt16("Int16", Convert.ToInt16(valueToEncode, formatProvider)); break; case BuiltInType.UInt16: - binaryEncoder.WriteUInt16("UInt16", Convert.ToUInt16(valueToEncode)); + binaryEncoder.WriteUInt16("UInt16", Convert.ToUInt16(valueToEncode, formatProvider)); break; case BuiltInType.Int32: - binaryEncoder.WriteInt32("Int32", Convert.ToInt32(valueToEncode)); + binaryEncoder.WriteInt32("Int32", Convert.ToInt32(valueToEncode, formatProvider)); break; case BuiltInType.UInt32: - binaryEncoder.WriteUInt32("UInt32", Convert.ToUInt32(valueToEncode)); + binaryEncoder.WriteUInt32("UInt32", Convert.ToUInt32(valueToEncode, formatProvider)); break; case BuiltInType.Int64: - binaryEncoder.WriteInt64("Int64", Convert.ToInt64(valueToEncode)); + binaryEncoder.WriteInt64("Int64", Convert.ToInt64(valueToEncode, formatProvider)); break; case BuiltInType.UInt64: - binaryEncoder.WriteUInt64("UInt64", Convert.ToUInt64(valueToEncode)); + binaryEncoder.WriteUInt64("UInt64", Convert.ToUInt64(valueToEncode, formatProvider)); break; case BuiltInType.Float: - binaryEncoder.WriteFloat("Float", Convert.ToSingle(valueToEncode)); + binaryEncoder.WriteFloat("Float", Convert.ToSingle(valueToEncode, formatProvider)); break; case BuiltInType.Double: - binaryEncoder.WriteDouble("Double", Convert.ToDouble(valueToEncode)); + binaryEncoder.WriteDouble("Double", Convert.ToDouble(valueToEncode, formatProvider)); break; case BuiltInType.DateTime: - binaryEncoder.WriteDateTime("DateTime", Convert.ToDateTime(valueToEncode)); + binaryEncoder.WriteDateTime("DateTime", Convert.ToDateTime(valueToEncode, formatProvider)); break; case BuiltInType.Guid: binaryEncoder.WriteGuid("GUID", (Uuid)valueToEncode); @@ -756,7 +758,7 @@ private static void EncodeFieldAsRawData(BinaryEncoder binaryEncoder, Field fiel binaryEncoder.WriteXmlElement("XmlElement", valueToEncode as XmlElement); break; case BuiltInType.Enumeration: - binaryEncoder.WriteInt32("Enumeration", Convert.ToInt32(valueToEncode)); + binaryEncoder.WriteInt32("Enumeration", Convert.ToInt32(valueToEncode, formatProvider)); break; case BuiltInType.ExtensionObject: binaryEncoder.WriteExtensionObject("ExtensionObject", valueToEncode as ExtensionObject); diff --git a/Libraries/Opc.Ua.PubSub/Encoding/UadpNetworkMessage.cs b/Libraries/Opc.Ua.PubSub/Encoding/UadpNetworkMessage.cs index 3e0f74503..5ba10561a 100644 --- a/Libraries/Opc.Ua.PubSub/Encoding/UadpNetworkMessage.cs +++ b/Libraries/Opc.Ua.PubSub/Encoding/UadpNetworkMessage.cs @@ -29,6 +29,7 @@ using System; using System.Collections.Generic; +using System.Globalization; using System.IO; using static Opc.Ua.Utils; @@ -983,19 +984,19 @@ private void EncodeNetworkMessageHeader(BinaryEncoder encoder) switch (publisherIdType) { case PublisherIdTypeEncodingMask.Byte: - encoder.WriteByte("PublisherId", Convert.ToByte(PublisherId)); + encoder.WriteByte("PublisherId", Convert.ToByte(PublisherId, CultureInfo.InvariantCulture)); break; case PublisherIdTypeEncodingMask.UInt16: - encoder.WriteUInt16("PublisherId", Convert.ToUInt16(PublisherId)); + encoder.WriteUInt16("PublisherId", Convert.ToUInt16(PublisherId, CultureInfo.InvariantCulture)); break; case PublisherIdTypeEncodingMask.UInt32: - encoder.WriteUInt32("PublisherId", Convert.ToUInt32(PublisherId)); + encoder.WriteUInt32("PublisherId", Convert.ToUInt32(PublisherId, CultureInfo.InvariantCulture)); break; case PublisherIdTypeEncodingMask.UInt64: - encoder.WriteUInt64("PublisherId", Convert.ToUInt64(PublisherId)); + encoder.WriteUInt64("PublisherId", Convert.ToUInt64(PublisherId, CultureInfo.InvariantCulture)); break; case PublisherIdTypeEncodingMask.String: - encoder.WriteString("PublisherId", Convert.ToString(PublisherId)); + encoder.WriteString("PublisherId", Convert.ToString(PublisherId, CultureInfo.InvariantCulture)); break; default: // Reserved - no type provided diff --git a/Libraries/Opc.Ua.PubSub/Properties/AssemblyInfo.cs b/Libraries/Opc.Ua.PubSub/Properties/AssemblyInfo.cs index c408df094..5ee02c650 100644 --- a/Libraries/Opc.Ua.PubSub/Properties/AssemblyInfo.cs +++ b/Libraries/Opc.Ua.PubSub/Properties/AssemblyInfo.cs @@ -27,8 +27,10 @@ * http://opcfoundation.org/License/MIT/1.00/ * ======================================================================*/ +using System; using System.Runtime.CompilerServices; +[assembly: CLSCompliant(false)] #if SIGNASSEMBLY [assembly: InternalsVisibleTo("Opc.Ua.PubSub.Tests, PublicKey = " + // OPC Foundation Strong Name Public Key diff --git a/Libraries/Opc.Ua.PubSub/Transport/MqttClientProtocolConfiguration.cs b/Libraries/Opc.Ua.PubSub/Transport/MqttClientProtocolConfiguration.cs index d31d5be8c..625f315bb 100644 --- a/Libraries/Opc.Ua.PubSub/Transport/MqttClientProtocolConfiguration.cs +++ b/Libraries/Opc.Ua.PubSub/Transport/MqttClientProtocolConfiguration.cs @@ -29,6 +29,7 @@ using System; using System.Collections.Generic; +using System.Globalization; using System.Security; using System.Security.Authentication; using System.Security.Cryptography.X509Certificates; @@ -172,16 +173,16 @@ public MqttTlsOptions(KeyValuePairCollection kvpMqttOptions) Certificates = new MqttTlsCertificates(kvpMqttOptions); QualifiedName qSslProtocolVersion = EnumMqttClientConfigurationParameters.TlsProtocolVersion.ToString(); - SslProtocolVersion = (SslProtocols)Convert.ToInt32(kvpMqttOptions.Find(kvp => kvp.Key.Name.Equals(qSslProtocolVersion.Name))?.Value.Value); + SslProtocolVersion = (SslProtocols)Convert.ToInt32(kvpMqttOptions.Find(kvp => kvp.Key.Name.Equals(qSslProtocolVersion.Name))?.Value.Value, CultureInfo.InvariantCulture); QualifiedName qAllowUntrustedCertificates = EnumMqttClientConfigurationParameters.TlsAllowUntrustedCertificates.ToString(); - AllowUntrustedCertificates = Convert.ToBoolean(kvpMqttOptions.Find(kvp => kvp.Key.Name.Equals(qAllowUntrustedCertificates.Name))?.Value.Value); + AllowUntrustedCertificates = Convert.ToBoolean(kvpMqttOptions.Find(kvp => kvp.Key.Name.Equals(qAllowUntrustedCertificates.Name, StringComparison.Ordinal))?.Value.Value, CultureInfo.InvariantCulture); QualifiedName qIgnoreCertificateChainErrors = EnumMqttClientConfigurationParameters.TlsIgnoreCertificateChainErrors.ToString(); - IgnoreCertificateChainErrors = Convert.ToBoolean(kvpMqttOptions.Find(kvp => kvp.Key.Name.Equals(qIgnoreCertificateChainErrors.Name))?.Value.Value); + IgnoreCertificateChainErrors = Convert.ToBoolean(kvpMqttOptions.Find(kvp => kvp.Key.Name.Equals(qIgnoreCertificateChainErrors.Name))?.Value.Value, CultureInfo.InvariantCulture); QualifiedName qIgnoreRevocationListErrors = EnumMqttClientConfigurationParameters.TlsIgnoreRevocationListErrors.ToString(); - IgnoreRevocationListErrors = Convert.ToBoolean(kvpMqttOptions.Find(kvp => kvp.Key.Name.Equals(qIgnoreRevocationListErrors.Name))?.Value.Value); + IgnoreRevocationListErrors = Convert.ToBoolean(kvpMqttOptions.Find(kvp => kvp.Key.Name.Equals(qIgnoreRevocationListErrors.Name))?.Value.Value, CultureInfo.InvariantCulture); QualifiedName qTrustedIssuerCertificatesStoreType = EnumMqttClientConfigurationParameters.TrustedIssuerCertificatesStoreType.ToString(); string issuerCertificatesStoreType = kvpMqttOptions.Find(kvp => kvp.Key.Name.Equals(qTrustedIssuerCertificatesStoreType.Name))?.Value.Value as string; @@ -430,13 +431,13 @@ public MqttClientProtocolConfiguration(KeyValuePairCollection connectionProperti } QualifiedName qAzureClientId = EnumMqttClientConfigurationParameters.AzureClientId.ToString(); - AzureClientId = Convert.ToString(connectionProperties.Find(kvp => kvp.Key.Name.Equals(qAzureClientId.Name))?.Value.Value); + AzureClientId = Convert.ToString(connectionProperties.Find(kvp => kvp.Key.Name.Equals(qAzureClientId.Name))?.Value.Value, CultureInfo.InvariantCulture); QualifiedName qCleanSession = EnumMqttClientConfigurationParameters.CleanSession.ToString(); - CleanSession = Convert.ToBoolean(connectionProperties.Find(kvp => kvp.Key.Name.Equals(qCleanSession.Name))?.Value.Value); + CleanSession = Convert.ToBoolean(connectionProperties.Find(kvp => kvp.Key.Name.Equals(qCleanSession.Name))?.Value.Value, CultureInfo.InvariantCulture); QualifiedName qProtocolVersion = EnumMqttClientConfigurationParameters.ProtocolVersion.ToString(); - ProtocolVersion = (EnumMqttProtocolVersion)Convert.ToInt32(connectionProperties.Find(kvp => kvp.Key.Name.Equals(qProtocolVersion.Name))?.Value.Value); + ProtocolVersion = (EnumMqttProtocolVersion)Convert.ToInt32(connectionProperties.Find(kvp => kvp.Key.Name.Equals(qProtocolVersion.Name))?.Value.Value, CultureInfo.InvariantCulture); if (ProtocolVersion == EnumMqttProtocolVersion.Unknown) { Utils.Trace(Utils.TraceMasks.Information, "Mqtt protocol version is Unknown and it will default to V310"); diff --git a/Libraries/Opc.Ua.PubSub/Transport/MqttPubSubConnection.cs b/Libraries/Opc.Ua.PubSub/Transport/MqttPubSubConnection.cs index 8e50b76c4..e873154cf 100644 --- a/Libraries/Opc.Ua.PubSub/Transport/MqttPubSubConnection.cs +++ b/Libraries/Opc.Ua.PubSub/Transport/MqttPubSubConnection.cs @@ -653,7 +653,7 @@ private MqttClientOptions GetMqttClientOptions() (MqttProtocolVersion)((MqttClientProtocolConfiguration)transportProtocolConfiguration) .ProtocolVersion; // create uniques client id - string clientId = "ClientId_" + new Random().Next().ToString("D10"); + string clientId = $"ClientId_{new Random().Next():D10}"; // MQTTS mqttConnection. if (connectionUri.Scheme == Utils.UriSchemeMqtts) { diff --git a/Libraries/Opc.Ua.PubSub/Transport/UdpClientCreator.cs b/Libraries/Opc.Ua.PubSub/Transport/UdpClientCreator.cs index 407e6bd65..aa2b1a92b 100644 --- a/Libraries/Opc.Ua.PubSub/Transport/UdpClientCreator.cs +++ b/Libraries/Opc.Ua.PubSub/Transport/UdpClientCreator.cs @@ -29,6 +29,7 @@ using System; using System.Collections.Generic; +using System.Globalization; using System.Net; using System.Net.NetworkInformation; using System.Net.Sockets; @@ -107,8 +108,8 @@ internal static IPEndPoint GetEndPoint(string url) internal static List GetUdpClients(UsedInContext pubSubContext, string networkInterface, IPEndPoint configuredEndpoint) { StringBuilder buffer = new StringBuilder(); - buffer.AppendFormat("networkAddressUrl.NetworkInterface = {0} \n", networkInterface ?? "null"); - buffer.AppendFormat("configuredEndpoint = {0}", configuredEndpoint != null ? configuredEndpoint.ToString() : "null"); + buffer.AppendFormat(CultureInfo.InvariantCulture, "networkAddressUrl.NetworkInterface = {0} \n", networkInterface ?? "null"); + buffer.AppendFormat(CultureInfo.InvariantCulture, "configuredEndpoint = {0}", configuredEndpoint != null ? configuredEndpoint.ToString() : "null"); Utils.Trace(Utils.TraceMasks.Information, buffer.ToString()); diff --git a/Libraries/Opc.Ua.PubSub/UaPubSubApplication.cs b/Libraries/Opc.Ua.PubSub/UaPubSubApplication.cs index 74e8f5514..eed5d37ca 100644 --- a/Libraries/Opc.Ua.PubSub/UaPubSubApplication.cs +++ b/Libraries/Opc.Ua.PubSub/UaPubSubApplication.cs @@ -118,7 +118,7 @@ private UaPubSubApplication(IUaPubSubDataStore dataStore = null, string applicat } else { - ApplicationId = $"opcua:{System.Net.Dns.GetHostName()}:{new Random().Next().ToString("D10")}"; + ApplicationId = $"opcua:{System.Net.Dns.GetHostName()}:{new Random().Next():D10}"; } m_dataCollector = new DataCollector(m_dataStore); @@ -201,7 +201,7 @@ public static UaPubSubApplication Create(string configFilePath, IUaPubSubDataSto // validate input argument if (configFilePath == null) { - throw new ArgumentException(nameof(configFilePath)); + throw new ArgumentNullException(nameof(configFilePath)); } if (!File.Exists(configFilePath)) { @@ -272,10 +272,7 @@ internal void RaiseRawDataReceivedEvent(RawDataReceivedEventArgs e) { try { - if (RawDataReceived != null) - { - RawDataReceived(this, e); - } + RawDataReceived?.Invoke(this, e); } catch (Exception ex) { @@ -291,10 +288,7 @@ internal void RaiseDataReceivedEvent(SubscribedDataEventArgs e) { try { - if (DataReceived != null) - { - DataReceived(this, e); - } + DataReceived?.Invoke(this, e); } catch (Exception ex) { @@ -310,10 +304,7 @@ internal void RaiseMetaDataReceivedEvent(SubscribedDataEventArgs e) { try { - if (MetaDataReceived != null) - { - MetaDataReceived(this, e); - } + MetaDataReceived?.Invoke(this, e); } catch (Exception ex) { @@ -328,10 +319,7 @@ internal void RaiseDatasetWriterConfigurationReceivedEvent(DataSetWriterConfigur { try { - if (DataSetWriterConfigurationReceived != null) - { - DataSetWriterConfigurationReceived(this, e); - } + DataSetWriterConfigurationReceived?.Invoke(this, e); } catch (Exception ex) { @@ -347,10 +335,7 @@ internal void RaisePublisherEndpointsReceivedEvent(PublisherEndpointsEventArgs e { try { - if (PublisherEndpointsReceived != null) - { - PublisherEndpointsReceived(this, e); - } + PublisherEndpointsReceived?.Invoke(this, e); } catch (Exception ex) { @@ -366,10 +351,7 @@ internal void RaiseConfigurationUpdatingEvent(ConfigurationUpdatingEventArgs e) { try { - if (ConfigurationUpdating != null) - { - ConfigurationUpdating(this, e); - } + ConfigurationUpdating?.Invoke(this, e); } catch (Exception ex) { diff --git a/Libraries/Opc.Ua.Security.Certificates/Common/AsnUtils.cs b/Libraries/Opc.Ua.Security.Certificates/Common/AsnUtils.cs index 22fe4985e..7b89c27dd 100644 --- a/Libraries/Opc.Ua.Security.Certificates/Common/AsnUtils.cs +++ b/Libraries/Opc.Ua.Security.Certificates/Common/AsnUtils.cs @@ -29,6 +29,7 @@ using System; using System.Formats.Asn1; +using System.Globalization; using System.Security.Cryptography; using System.Text; @@ -55,14 +56,14 @@ internal static string ToHexString(this byte[] buffer, bool invertEndian = false { for (int ii = buffer.Length - 1; ii >= 0; ii--) { - builder.AppendFormat("{0:X2}", buffer[ii]); + builder.AppendFormat(CultureInfo.InvariantCulture, "{0:X2}", buffer[ii]); } } else { for (int ii = 0; ii < buffer.Length; ii++) { - builder.AppendFormat("{0:X2}", buffer[ii]); + builder.AppendFormat(CultureInfo.InvariantCulture, "{0:X2}", buffer[ii]); } } diff --git a/Libraries/Opc.Ua.Security.Certificates/PEM/PEMReader.cs b/Libraries/Opc.Ua.Security.Certificates/PEM/PEMReader.cs index 234e8dd84..1f0e6e43b 100644 --- a/Libraries/Opc.Ua.Security.Certificates/PEM/PEMReader.cs +++ b/Libraries/Opc.Ua.Security.Certificates/PEM/PEMReader.cs @@ -64,13 +64,13 @@ public static class PEMReader { count++; string beginlabel = $"-----BEGIN {label}-----"; - int beginIndex = pemText.IndexOf(beginlabel); + int beginIndex = pemText.IndexOf(beginlabel, StringComparison.Ordinal); if (beginIndex < 0) { continue; } string endlabel = $"-----END {label}-----"; - int endIndex = pemText.IndexOf(endlabel); + int endIndex = pemText.IndexOf(endlabel, StringComparison.Ordinal); beginIndex += beginlabel.Length; if (endIndex < 0 || endIndex <= beginIndex) { diff --git a/Libraries/Opc.Ua.Security.Certificates/PEM/PEMWriter.cs b/Libraries/Opc.Ua.Security.Certificates/PEM/PEMWriter.cs index d25622b46..147a66120 100644 --- a/Libraries/Opc.Ua.Security.Certificates/PEM/PEMWriter.cs +++ b/Libraries/Opc.Ua.Security.Certificates/PEM/PEMWriter.cs @@ -28,6 +28,7 @@ * ======================================================================*/ using System; +using System.Globalization; using System.IO; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; @@ -125,7 +126,7 @@ X509Certificate2 certificate if (rsaPrivateKey != null) { // write private key as PKCS#8 - exportedPkcs8PrivateKey = String.IsNullOrEmpty(password) ? + exportedPkcs8PrivateKey = string.IsNullOrEmpty(password) ? rsaPrivateKey.ExportPkcs8PrivateKey() : rsaPrivateKey.ExportEncryptedPkcs8PrivateKey(password.ToCharArray(), new PbeParameters(PbeEncryptionAlgorithm.TripleDes3KeyPkcs12, HashAlgorithmName.SHA1, 2000)); @@ -137,10 +138,10 @@ X509Certificate2 certificate if (ecdsaPrivateKey != null) { // write private key as PKCS#8 - exportedPkcs8PrivateKey = String.IsNullOrEmpty(password) ? - ecdsaPrivateKey.ExportPkcs8PrivateKey() : - ecdsaPrivateKey.ExportEncryptedPkcs8PrivateKey(password.ToCharArray(), - new PbeParameters(PbeEncryptionAlgorithm.TripleDes3KeyPkcs12, HashAlgorithmName.SHA1, 2000)); + exportedPkcs8PrivateKey = string.IsNullOrEmpty(password) ? + ecdsaPrivateKey.ExportPkcs8PrivateKey() : + ecdsaPrivateKey.ExportEncryptedPkcs8PrivateKey(password.ToCharArray(), + new PbeParameters(PbeEncryptionAlgorithm.TripleDes3KeyPkcs12, HashAlgorithmName.SHA1, 2000)); } } } @@ -156,23 +157,35 @@ X509Certificate2 certificate private static byte[] EncodeAsPEM(byte[] content, string contentType) { if (content == null) throw new ArgumentNullException(nameof(content)); - if (String.IsNullOrEmpty(contentType)) throw new ArgumentNullException(nameof(contentType)); + if (string.IsNullOrEmpty(contentType)) throw new ArgumentNullException(nameof(contentType)); const int LineLength = 64; string base64 = Convert.ToBase64String(content); - using (TextWriter textWriter = new StringWriter()) + using (var textWriter = new StringWriter()) { textWriter.WriteLine("-----BEGIN {0}-----", contentType); - while (base64.Length > LineLength) + + int offset = 0; + while (base64.Length - offset > LineLength) + { +#if NETSTANDARD2_1 || NET5_0_OR_GREATER + textWriter.WriteLine(base64.AsSpan(offset, LineLength)); +#else + textWriter.WriteLine(base64.Substring(offset, LineLength)); +#endif + offset += LineLength; + } + + var length = base64.Length - offset; + if (length > 0) { #if NETSTANDARD2_1 || NET5_0_OR_GREATER - textWriter.WriteLine(base64.AsSpan(0, LineLength)); + textWriter.WriteLine(base64.AsSpan(offset, length)); #else - textWriter.WriteLine(base64.Substring(0, LineLength)); + textWriter.WriteLine(base64.Substring(offset, length)); #endif - base64 = base64.Substring(LineLength); } - textWriter.WriteLine(base64); + textWriter.WriteLine("-----END {0}-----", contentType); return Encoding.ASCII.GetBytes(textWriter.ToString()); } diff --git a/Libraries/Opc.Ua.Security.Certificates/Properties/AssemblyInfo.cs b/Libraries/Opc.Ua.Security.Certificates/Properties/AssemblyInfo.cs index 21a6d3944..30b5ad22b 100644 --- a/Libraries/Opc.Ua.Security.Certificates/Properties/AssemblyInfo.cs +++ b/Libraries/Opc.Ua.Security.Certificates/Properties/AssemblyInfo.cs @@ -27,8 +27,10 @@ * http://opcfoundation.org/License/MIT/1.00/ * ======================================================================*/ +using System; using System.Runtime.CompilerServices; +[assembly: CLSCompliant(false)] #if SIGNASSEMBLY [assembly: InternalsVisibleTo("Opc.Ua.Security.Certificates.Tests, PublicKey = " + // OPC Foundation Strong Name Public Key diff --git a/Libraries/Opc.Ua.Security.Certificates/X509Certificate/CertificateBuilderBase.cs b/Libraries/Opc.Ua.Security.Certificates/X509Certificate/CertificateBuilderBase.cs index 3caade48b..dbdcb9443 100644 --- a/Libraries/Opc.Ua.Security.Certificates/X509Certificate/CertificateBuilderBase.cs +++ b/Libraries/Opc.Ua.Security.Certificates/X509Certificate/CertificateBuilderBase.cs @@ -320,44 +320,44 @@ protected virtual void NewSerialNumber() /// /// If the certificate is a CA. /// - protected bool m_isCA; + private protected bool m_isCA; /// /// The path length constraint to sue for a CA. /// - protected int m_pathLengthConstraint; + private protected int m_pathLengthConstraint; /// /// The serial number length in octets. /// - protected int m_serialNumberLength; + private protected int m_serialNumberLength; /// /// If the serial number is preset by the user. /// - protected bool m_presetSerial; + private protected bool m_presetSerial; /// /// The serial number as a little endian byte array. /// - protected byte[] m_serialNumber; + private protected byte[] m_serialNumber; /// /// The collection of X509Extension to add to the certificate. /// - protected X509ExtensionCollection m_extensions; + private protected X509ExtensionCollection m_extensions; /// /// The RSA public to use when if a certificate is signed. /// - protected RSA m_rsaPublicKey; + private protected RSA m_rsaPublicKey; /// /// The size of a RSA key pair to create. /// - protected int m_keySize; + private protected int m_keySize; #if ECC_SUPPORT /// /// The ECDsa public to use when if a certificate is signed. /// - protected ECDsa m_ecdsaPublicKey; + private protected ECDsa m_ecdsaPublicKey; /// /// The ECCurve to use. /// - protected ECCurve? m_curve; + private protected ECCurve? m_curve; #endif #endregion diff --git a/Libraries/Opc.Ua.Server/Diagnostics/CustomNodeManager.cs b/Libraries/Opc.Ua.Server/Diagnostics/CustomNodeManager.cs index 17f893742..43bfa0475 100644 --- a/Libraries/Opc.Ua.Server/Diagnostics/CustomNodeManager.cs +++ b/Libraries/Opc.Ua.Server/Diagnostics/CustomNodeManager.cs @@ -1907,7 +1907,7 @@ protected virtual bool IsReferenceInView(ServerSystemContext context, Continuati bool isOutOfRange = false; foreach (var arrayValue in array) { - double newValue = Convert.ToDouble(arrayValue); + double newValue = Convert.ToDouble(arrayValue, CultureInfo.InvariantCulture); if (newValue > analogItemState.InstrumentRange.Value.High || newValue < analogItemState.InstrumentRange.Value.Low) { @@ -1923,7 +1923,7 @@ protected virtual bool IsReferenceInView(ServerSystemContext context, Continuati } else { - double newValue = Convert.ToDouble(nodeToWrite.Value.Value); + double newValue = Convert.ToDouble(nodeToWrite.Value.Value, CultureInfo.InvariantCulture); if (newValue > analogItemState.InstrumentRange.Value.High || newValue < analogItemState.InstrumentRange.Value.Low) diff --git a/Libraries/Opc.Ua.Server/Diagnostics/DiagnosticsNodeManager.cs b/Libraries/Opc.Ua.Server/Diagnostics/DiagnosticsNodeManager.cs index 91f0a1404..cd283798e 100644 --- a/Libraries/Opc.Ua.Server/Diagnostics/DiagnosticsNodeManager.cs +++ b/Libraries/Opc.Ua.Server/Diagnostics/DiagnosticsNodeManager.cs @@ -29,6 +29,7 @@ using System; using System.Collections.Generic; +using System.Globalization; using System.Linq; using System.Reflection; using System.Threading; @@ -969,7 +970,7 @@ public void SetDiagnosticsEnabled(ServerSystemContext context, bool enabled) systemContext, null, ReferenceTypeIds.HasComponent, - new QualifiedName(diagnostics.SubscriptionId.ToString()), + new QualifiedName(diagnostics.SubscriptionId.ToString(CultureInfo.InvariantCulture)), diagnosticsNode); // add reference to subscription array. diff --git a/Libraries/Opc.Ua.Server/NodeManager/CoreNodeManager.cs b/Libraries/Opc.Ua.Server/NodeManager/CoreNodeManager.cs index 121634526..0aab482a4 100644 --- a/Libraries/Opc.Ua.Server/NodeManager/CoreNodeManager.cs +++ b/Libraries/Opc.Ua.Server/NodeManager/CoreNodeManager.cs @@ -29,6 +29,7 @@ using System; using System.Collections.Generic; +using System.Globalization; using System.Threading.Tasks; #pragma warning disable 0618 @@ -585,7 +586,7 @@ public object GetManagerHandle(NodeId nodeId) // Set AccessRestrictions and RolePermissions Node node = (Node)target; - metadata.AccessRestrictions = (AccessRestrictionType)Enum.Parse(typeof(AccessRestrictionType), node.AccessRestrictions.ToString()); + metadata.AccessRestrictions = (AccessRestrictionType)Enum.Parse(typeof(AccessRestrictionType), node.AccessRestrictions.ToString(CultureInfo.InvariantCulture)); metadata.RolePermissions = node.RolePermissions; metadata.UserRolePermissions = node.UserRolePermissions; diff --git a/Libraries/Opc.Ua.Server/NodeManager/ResourceManager.cs b/Libraries/Opc.Ua.Server/NodeManager/ResourceManager.cs index 481bb9189..66431b551 100644 --- a/Libraries/Opc.Ua.Server/NodeManager/ResourceManager.cs +++ b/Libraries/Opc.Ua.Server/NodeManager/ResourceManager.cs @@ -36,7 +36,7 @@ using System.Reflection; namespace Opc.Ua.Server -{ +{ /// /// An object that manages access to localized resources. /// @@ -48,14 +48,14 @@ public class ResourceManager : IDisposable, ITranslationManager /// public ResourceManager(IServerInternal server, ApplicationConfiguration configuration) { - if (server == null) throw new ArgumentNullException(nameof(server)); + if (server == null) throw new ArgumentNullException(nameof(server)); if (configuration == null) throw new ArgumentNullException(nameof(configuration)); - + m_server = server; m_translationTables = new List(); } #endregion - + #region IDisposable Members /// /// May be called by the application to clean up resources. @@ -83,7 +83,7 @@ public virtual LocalizedText Translate(IList preferredLocales, string ke { return Translate(preferredLocales, null, new TranslationInfo(key, String.Empty, text, args)); } - + /// public LocalizedText Translate(IList preferredLocales, LocalizedText text) { @@ -133,7 +133,7 @@ public ServiceResult Translate(IList preferredLocales, ServiceResult res { return result; } - + translatedText = Translate(preferredLocales, result.LocalizedText); } @@ -168,7 +168,7 @@ public virtual string[] GetAvailableLocales() return availableLocales; } } - + /// /// Returns the locales supported by the resource manager. /// @@ -185,7 +185,7 @@ public string[] GetAvailableLocales(IEnumerable preferredLocales) public LocalizedText GetText(IList preferredLocales, string textId, string defaultText, params object[] args) { return Translate(preferredLocales, textId, defaultText, args); - } + } /// /// Adds a translation to the resource manager. @@ -197,7 +197,7 @@ public void Add(string key, string locale, string text) if (text == null) throw new ArgumentNullException(nameof(text)); CultureInfo culture = new CultureInfo(locale); - + if (culture.IsNeutralCulture) { throw new ArgumentException("Cannot specify neutral locales for translation tables.", nameof(locale)); @@ -213,13 +213,13 @@ public void Add(string key, string locale, string text) /// /// Adds the translations to the resource manager. /// - public void Add(string locale, IDictionary translations) + public void Add(string locale, IDictionary translations) { if (locale == null) throw new ArgumentNullException(nameof(locale)); if (translations == null) throw new ArgumentNullException(nameof(translations)); CultureInfo culture = new CultureInfo(locale); - + if (culture.IsNeutralCulture) { throw new ArgumentException("Cannot specify neutral locales for translation tables.", nameof(locale)); @@ -229,7 +229,7 @@ public void Add(string locale, IDictionary translations) { TranslationTable table = GetTable(culture.Name); - foreach (KeyValuePair translation in translations) + foreach (KeyValuePair translation in translations) { table.Translations[translation.Key] = translation.Value; } @@ -243,15 +243,15 @@ public void Add(uint statusCode, string locale, string text) { lock (m_lock) { - string key = statusCode.ToString(); + string key = statusCode.ToString(CultureInfo.InvariantCulture); Add(key, locale, text); if (m_statusCodeMapping == null) { - m_statusCodeMapping = new Dictionary(); + m_statusCodeMapping = new Dictionary(); } - + if (String.IsNullOrEmpty(locale) || locale == "en-US") { m_statusCodeMapping[statusCode] = new TranslationInfo(key, locale, text); @@ -303,7 +303,7 @@ public void LoadDefaultText() } } #endregion - + #region Protected Methods /// /// Returns the text for the specified locale (null if the locale is not supported). @@ -382,10 +382,10 @@ protected virtual LocalizedText Translate(IList preferredLocales, Locali string formattedText = translatedText; if (info.Args != null && info.Args.Length > 0) - { + { try { - formattedText = String.Format(culture, translatedText, info.Args); + formattedText = string.Format(culture, translatedText, info.Args); } catch { @@ -399,7 +399,7 @@ protected virtual LocalizedText Translate(IList preferredLocales, Locali return finalText; } #endregion - + #region Private Methods /// /// Stores the translations for a locale. @@ -407,7 +407,7 @@ protected virtual LocalizedText Translate(IList preferredLocales, Locali private class TranslationTable { public CultureInfo Locale; - public SortedDictionary Translations = new SortedDictionary(); + public SortedDictionary Translations = new SortedDictionary(); } /// @@ -421,7 +421,7 @@ private TranslationTable GetTable(string locale) for (int ii = 0; ii < m_translationTables.Count; ii++) { TranslationTable translationTable = m_translationTables[ii]; - + if (translationTable.Locale.Name == locale) { return translationTable; @@ -446,7 +446,7 @@ private string FindBestTranslation(IList preferredLocales, string key, o TranslationTable match = null; if (preferredLocales == null || preferredLocales.Count == 0) { return null; } - + for (int jj = 0; jj < preferredLocales.Count; jj++) { // parse the locale. @@ -470,7 +470,7 @@ private string FindBestTranslation(IList preferredLocales, string key, o for (int ii = 0; ii < m_translationTables.Count; ii++) { TranslationTable translationTable = m_translationTables[ii]; - + // all done if exact match found. if (translationTable.Locale.Name == preferredLocales[jj]) { @@ -480,7 +480,7 @@ private string FindBestTranslation(IList preferredLocales, string key, o return translatedText; } } - + // check for matching language but different region. if (match == null && translationTable.Locale.TwoLetterISOLanguageName == language) { @@ -499,10 +499,10 @@ private string FindBestTranslation(IList preferredLocales, string key, o { return translatedText; } - } + } - // no translations available. - return null; + // no translations available. + return null; } /// @@ -533,7 +533,7 @@ private LocalizedText TranslateStatusCode(IList preferredLocales, Status } } - return String.Format("{0:X8}", statusCode.Code); + return Utils.Format("{0:X8}", statusCode.Code); } /// @@ -573,8 +573,8 @@ private LocalizedText TranslateSymbolicId(IList preferredLocales, string [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] private IServerInternal m_server; private List m_translationTables; - private Dictionary m_statusCodeMapping; - private Dictionary m_symbolicIdMapping; + private Dictionary m_statusCodeMapping; + private Dictionary m_symbolicIdMapping; #endregion } } diff --git a/Libraries/Opc.Ua.Server/Properties/AssemblyInfo.cs b/Libraries/Opc.Ua.Server/Properties/AssemblyInfo.cs index 5b99293d7..7a503405e 100644 --- a/Libraries/Opc.Ua.Server/Properties/AssemblyInfo.cs +++ b/Libraries/Opc.Ua.Server/Properties/AssemblyInfo.cs @@ -27,8 +27,10 @@ * http://opcfoundation.org/License/MIT/1.00/ * ======================================================================*/ +using System; using System.Runtime.CompilerServices; +[assembly: CLSCompliant(false)] #if SIGNASSEMBLY [assembly: InternalsVisibleTo("Opc.Ua.Server.Tests, PublicKey = " + // OPC Foundation Strong Name Public Key diff --git a/Libraries/Opc.Ua.Server/Server/StandardServer.cs b/Libraries/Opc.Ua.Server/Server/StandardServer.cs index 7b59e3107..b07118c56 100644 --- a/Libraries/Opc.Ua.Server/Server/StandardServer.cs +++ b/Libraries/Opc.Ua.Server/Server/StandardServer.cs @@ -3250,7 +3250,7 @@ protected virtual ResourceManager CreateResourceManager(IServerInternal server, /// Returns the master node manager for the server, the return type is . protected virtual MasterNodeManager CreateMasterNodeManager(IServerInternal server, ApplicationConfiguration configuration) { - IList nodeManagers = new List(); + var nodeManagers = new List(); foreach (var nodeManagerFactory in m_nodeManagerFactories) { @@ -3355,7 +3355,7 @@ public virtual void RemoveNodeManager(INodeManagerFactory nodeManagerFactory) private int m_lastRegistrationInterval; private int m_minNonceLength; private bool m_useRegisterServer2; - private IList m_nodeManagerFactories; + private List m_nodeManagerFactories; #endregion } } diff --git a/Libraries/Opc.Ua.Server/Subscription/MonitoredItem.cs b/Libraries/Opc.Ua.Server/Subscription/MonitoredItem.cs index 47c43c714..cefd14eef 100644 --- a/Libraries/Opc.Ua.Server/Subscription/MonitoredItem.cs +++ b/Libraries/Opc.Ua.Server/Subscription/MonitoredItem.cs @@ -830,7 +830,7 @@ public virtual void QueueValue(DataValue value, ServiceResult error, bool ignore if (!m_calculator.QueueRawValue(value)) { Utils.LogTrace("Value received out of order: {1}, ServerHandle={0}", - m_id, value.SourceTimestamp.ToLocalTime().ToString("HH:mm:ss.fff")); + m_id, value.SourceTimestamp.ToLocalTime().ToString("HH:mm:ss.fff", CultureInfo.InvariantCulture)); } DataValue processedValue = m_calculator.GetProcessedValue(false); diff --git a/Libraries/Opc.Ua.Server/Subscription/SessionPublishQueue.cs b/Libraries/Opc.Ua.Server/Subscription/SessionPublishQueue.cs index 1f711f1e5..495090dcd 100644 --- a/Libraries/Opc.Ua.Server/Subscription/SessionPublishQueue.cs +++ b/Libraries/Opc.Ua.Server/Subscription/SessionPublishQueue.cs @@ -29,6 +29,7 @@ using System; using System.Collections.Generic; +using System.Globalization; using System.Text; using System.Threading; @@ -868,21 +869,15 @@ internal void TraceState(string context, params object[] args) lock (m_lock) { buffer.Append("PublishQueue "); - buffer.AppendFormat(context, args); - - buffer.Append(", SessionId="); + buffer.AppendFormat(CultureInfo.InvariantCulture, context, args); if (m_session != null) { - buffer.AppendFormat("{0}", m_session.Id); - } - else - { - buffer.AppendFormat(", SessionId={0}", m_session.Id); + buffer.AppendFormat(CultureInfo.InvariantCulture, ", SessionId={0}", m_session.Id); } - buffer.AppendFormat(", SubscriptionCount={0}", m_queuedSubscriptions.Count); - buffer.AppendFormat(", RequestCount={0}", m_queuedRequests.Count); + buffer.AppendFormat(CultureInfo.InvariantCulture, ", SubscriptionCount={0}, RequestCount={1}", + m_queuedSubscriptions.Count, m_queuedRequests.Count); int readyToPublish = 0; @@ -894,7 +889,7 @@ internal void TraceState(string context, params object[] args) } } - buffer.AppendFormat(", ReadyToPublishCount={0}", readyToPublish); + buffer.AppendFormat(CultureInfo.InvariantCulture, ", ReadyToPublishCount={0}", readyToPublish); int expiredRequests = 0; @@ -906,10 +901,10 @@ internal void TraceState(string context, params object[] args) } } - buffer.AppendFormat(", ExpiredCount={0}", expiredRequests); + buffer.AppendFormat(CultureInfo.InvariantCulture, ", ExpiredCount={0}", expiredRequests); } - Utils.LogTrace("{0}", buffer.ToString()); + Utils.LogTrace(buffer.ToString()); } #endregion diff --git a/Libraries/Opc.Ua.Server/Subscription/Subscription.cs b/Libraries/Opc.Ua.Server/Subscription/Subscription.cs index ee1cb627d..34557b237 100644 --- a/Libraries/Opc.Ua.Server/Subscription/Subscription.cs +++ b/Libraries/Opc.Ua.Server/Subscription/Subscription.cs @@ -2168,10 +2168,10 @@ private void ConditionRefresh(List monitoredItems, uint mon { ServerSystemContext systemContext = m_server.DefaultSystemContext.Copy(m_session); - string messageTemplate = String.Format("Condition refresh {{0}} for subscription {0}.", m_id); + string messageTemplate = Utils.Format("Condition refresh {{0}} for subscription {0}.", m_id); if (monitoredItemId > 0) { - messageTemplate = String.Format("Condition refresh {{0}} for subscription {0}, monitored item {1}.", m_id, monitoredItemId); + messageTemplate = Utils.Format("Condition refresh {{0}} for subscription {0}, monitored item {1}.", m_id, monitoredItemId); } lock (m_lock) @@ -2184,7 +2184,7 @@ private void ConditionRefresh(List monitoredItems, uint mon message = new TranslationInfo( "RefreshStartEvent", "en-US", - String.Format(messageTemplate, "started")); + Utils.Format(messageTemplate, "started")); e.Initialize( systemContext, @@ -2238,7 +2238,7 @@ private void ConditionRefresh(List monitoredItems, uint mon message = new TranslationInfo( "RefreshEndEvent", "en-US", - String.Format(messageTemplate, "completed")); + Utils.Format(messageTemplate, "completed")); e.Initialize( systemContext, diff --git a/Stack/Opc.Ua.Bindings.Https/Properties/AssemblyInfo.cs b/Stack/Opc.Ua.Bindings.Https/Properties/AssemblyInfo.cs index f392c8d60..e9d25c2f8 100644 --- a/Stack/Opc.Ua.Bindings.Https/Properties/AssemblyInfo.cs +++ b/Stack/Opc.Ua.Bindings.Https/Properties/AssemblyInfo.cs @@ -9,8 +9,11 @@ but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. */ + +using System; using System.Runtime.CompilerServices; +[assembly: CLSCompliant(false)] #if SIGNASSEMBLY [assembly: InternalsVisibleTo("Opc.Ua.Core.Tests, PublicKey = " + // OPC Foundation Strong Name Public Key diff --git a/Stack/Opc.Ua.Core/Properties/AssemblyInfo.cs b/Stack/Opc.Ua.Core/Properties/AssemblyInfo.cs index f392c8d60..e9d25c2f8 100644 --- a/Stack/Opc.Ua.Core/Properties/AssemblyInfo.cs +++ b/Stack/Opc.Ua.Core/Properties/AssemblyInfo.cs @@ -9,8 +9,11 @@ but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. */ + +using System; using System.Runtime.CompilerServices; +[assembly: CLSCompliant(false)] #if SIGNASSEMBLY [assembly: InternalsVisibleTo("Opc.Ua.Core.Tests, PublicKey = " + // OPC Foundation Strong Name Public Key diff --git a/Stack/Opc.Ua.Core/Schema/UANodeSetHelpers.cs b/Stack/Opc.Ua.Core/Schema/UANodeSetHelpers.cs index b2e74bfbf..e4f00aee0 100644 --- a/Stack/Opc.Ua.Core/Schema/UANodeSetHelpers.cs +++ b/Stack/Opc.Ua.Core/Schema/UANodeSetHelpers.cs @@ -12,6 +12,7 @@ using System; using System.Collections.Generic; +using System.Globalization; using System.IO; using System.Text; using System.Xml; @@ -1211,7 +1212,7 @@ private uint[] ImportArrayDimensions(string arrayDimensions) { try { - dimensions[ii] = Convert.ToUInt32(fields[ii]); + dimensions[ii] = Convert.ToUInt32(fields[ii], CultureInfo.InvariantCulture); } catch { diff --git a/Stack/Opc.Ua.Core/Security/Certificates/CertificateIdentifier.cs b/Stack/Opc.Ua.Core/Security/Certificates/CertificateIdentifier.cs index 55784cfa7..e5b62e7d5 100644 --- a/Stack/Opc.Ua.Core/Security/Certificates/CertificateIdentifier.cs +++ b/Stack/Opc.Ua.Core/Security/Certificates/CertificateIdentifier.cs @@ -41,11 +41,7 @@ public partial class CertificateIdentifier : IFormattable /// public string ToString(string format, IFormatProvider formatProvider) { - if (!String.IsNullOrEmpty(format)) - { - throw new FormatException(); - } - + if (format != null) throw new FormatException(Utils.Format("Invalid format string: '{0}'.", format)); return ToString(); } #endregion diff --git a/Stack/Opc.Ua.Core/Security/Certificates/CertificateStoreIdentifier.cs b/Stack/Opc.Ua.Core/Security/Certificates/CertificateStoreIdentifier.cs index 8bcd9e6c3..a08e22083 100644 --- a/Stack/Opc.Ua.Core/Security/Certificates/CertificateStoreIdentifier.cs +++ b/Stack/Opc.Ua.Core/Security/Certificates/CertificateStoreIdentifier.cs @@ -52,11 +52,7 @@ public new object MemberwiseClone() /// public string ToString(string format, IFormatProvider formatProvider) { - if (!String.IsNullOrEmpty(format)) - { - throw new FormatException(); - } - + if (format != null) throw new FormatException(Utils.Format("Invalid format string: '{0}'.", format)); return ToString(); } #endregion diff --git a/Stack/Opc.Ua.Core/Security/Certificates/CertificateValidator.cs b/Stack/Opc.Ua.Core/Security/Certificates/CertificateValidator.cs index 4126bd902..02f5d46ac 100644 --- a/Stack/Opc.Ua.Core/Security/Certificates/CertificateValidator.cs +++ b/Stack/Opc.Ua.Core/Security/Certificates/CertificateValidator.cs @@ -13,6 +13,7 @@ using System; using System.Collections.Generic; using System.Diagnostics; +using System.Globalization; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.Text; @@ -1647,11 +1648,11 @@ private string CertificateMessage(string error, X509Certificate2 certificate) { var message = new StringBuilder() .AppendLine(error) - .AppendFormat("Subject: {0}", certificate.Subject) + .AppendFormat(CultureInfo.InvariantCulture, "Subject: {0}", certificate.Subject) .AppendLine(); if (!string.Equals(certificate.Subject, certificate.Issuer, StringComparison.Ordinal)) { - message.AppendFormat("Issuer: {0}", certificate.Issuer) + message.AppendFormat(CultureInfo.InvariantCulture, "Issuer: {0}", certificate.Issuer) .AppendLine(); } return message.ToString(); diff --git a/Stack/Opc.Ua.Core/Stack/Configuration/ApplicationConfiguration.cs b/Stack/Opc.Ua.Core/Stack/Configuration/ApplicationConfiguration.cs index 6c35537f1..0d46c7ebb 100644 --- a/Stack/Opc.Ua.Core/Stack/Configuration/ApplicationConfiguration.cs +++ b/Stack/Opc.Ua.Core/Stack/Configuration/ApplicationConfiguration.cs @@ -12,6 +12,7 @@ using System; using System.Collections.Generic; +using System.Globalization; using System.IO; using System.Runtime.Serialization; using System.Text; @@ -236,9 +237,9 @@ public static Task Load(string sectionName, Applicatio if (!file.Exists) { var message = new StringBuilder(); - message.AppendFormat("Configuration file does not exist: {0}", filePath); + message.AppendFormat(CultureInfo.InvariantCulture, "Configuration file does not exist: {0}", filePath); message.AppendLine(); - message.AppendFormat("Current directory is: {0}", Directory.GetCurrentDirectory()); + message.AppendFormat(CultureInfo.InvariantCulture, "Current directory is: {0}", Directory.GetCurrentDirectory()); throw ServiceResultException.Create( StatusCodes.BadConfigurationError, message.ToString()); } @@ -273,9 +274,9 @@ public static ApplicationConfiguration LoadWithNoValidation(FileInfo file, Type catch (Exception e) { var message = new StringBuilder(); - message.AppendFormat("Configuration file could not be loaded: {0}", file.FullName); + message.AppendFormat(CultureInfo.InvariantCulture, "Configuration file could not be loaded: {0}", file.FullName); message.AppendLine(); - message.AppendFormat("Error is: {0}", e.Message); + message.AppendFormat(CultureInfo.InvariantCulture, "Error is: {0}", e.Message); throw ServiceResultException.Create( StatusCodes.BadConfigurationError, e, message.ToString()); } @@ -322,7 +323,7 @@ public static Task Load(FileInfo file, ApplicationType catch (Exception e) { var message = new StringBuilder(); - message.AppendFormat("Configuration file could not be loaded: {0}", file.FullName); + message.AppendFormat(CultureInfo.InvariantCulture, "Configuration file could not be loaded: {0}", file.FullName); message.AppendLine(); message.Append(e.Message); throw ServiceResultException.Create( @@ -364,9 +365,9 @@ public static Task Load(FileInfo file, ApplicationType catch (Exception e) { var message = new StringBuilder(); - message.AppendFormat("Configuration could not be loaded."); + message.AppendFormat(CultureInfo.InvariantCulture, "Configuration could not be loaded."); message.AppendLine(); - message.AppendFormat("Error is: {0}", e.Message); + message.AppendFormat(CultureInfo.InvariantCulture, "Error is: {0}", e.Message); throw ServiceResultException.Create( StatusCodes.BadConfigurationError, e, message.ToString()); } diff --git a/Stack/Opc.Ua.Core/Stack/Configuration/ConfiguredEndpoints.cs b/Stack/Opc.Ua.Core/Stack/Configuration/ConfiguredEndpoints.cs index 4179df9dd..03eb1036d 100644 --- a/Stack/Opc.Ua.Core/Stack/Configuration/ConfiguredEndpoints.cs +++ b/Stack/Opc.Ua.Core/Stack/Configuration/ConfiguredEndpoints.cs @@ -1210,7 +1210,7 @@ public Uri GetDiscoveryUrl(Uri endpointUrl) { if (endpointUrl.Scheme.StartsWith(Utils.UriSchemeHttp, StringComparison.Ordinal)) { - return new Uri(String.Format(CultureInfo.InvariantCulture, "{0}" + DiscoverySuffix, endpointUrl)); + return new Uri(Utils.Format("{0}{1}", endpointUrl, DiscoverySuffix)); } else { @@ -1294,7 +1294,7 @@ public Uri EndpointUrl m_description.EndpointUrl = null; } - m_description.EndpointUrl = String.Format(CultureInfo.InvariantCulture, "{0}", value); + m_description.EndpointUrl = Utils.Format("{0}", value); } } diff --git a/Stack/Opc.Ua.Core/Stack/Nodes/ContentFilter.cs b/Stack/Opc.Ua.Core/Stack/Nodes/ContentFilter.cs index 1688bca5a..2b1691bb0 100644 --- a/Stack/Opc.Ua.Core/Stack/Nodes/ContentFilter.cs +++ b/Stack/Opc.Ua.Core/Stack/Nodes/ContentFilter.cs @@ -12,6 +12,7 @@ using System; using System.Collections.Generic; +using System.Globalization; using System.Text; namespace Opc.Ua @@ -23,14 +24,14 @@ public partial class ContentFilter : IFormattable /// /// Formats the value of the current instance using the specified format. /// - /// The specifying the format to use. + /// The specifying the format to use. /// -or- - /// null to use the default format defined for the type of the implementation. - /// The to use to format the value. + /// null to use the default format defined for the type of the implementation. + /// The to use to format the value. /// -or- /// null to obtain the numeric format information from the current locale setting of the operating system. /// - /// A containing the value of the current instance in the specified format. + /// A containing the value of the current instance in the specified format. /// public string ToString(string format, IFormatProvider formatProvider) { @@ -436,14 +437,14 @@ public partial class ContentFilterElement : IFormattable /// /// Formats the value of the current instance using the specified format. /// - /// The specifying the format to use. + /// The specifying the format to use. /// -or- - /// null to use the default format defined for the type of the implementation. - /// The to use to format the value. + /// null to use the default format defined for the type of the implementation. + /// The to use to format the value. /// -or- /// null to obtain the numeric format information from the current locale setting of the operating system. /// - /// A containing the value of the current instance in the specified format. + /// A containing the value of the current instance in the specified format. /// public string ToString(string format, IFormatProvider formatProvider) { @@ -724,7 +725,7 @@ public virtual string ToString(INodeTable nodeTable) case FilterOperator.IsNull: case FilterOperator.Not: { - buffer.AppendFormat("{0} '{1}'", FilterOperator, operand1); + buffer.AppendFormat(CultureInfo.InvariantCulture, "{0} '{1}'", FilterOperator, operand1); break; } @@ -739,30 +740,30 @@ public virtual string ToString(INodeTable nodeTable) case FilterOperator.BitwiseAnd: case FilterOperator.BitwiseOr: { - buffer.AppendFormat("'{1}' {0} '{2}'", FilterOperator, operand1, operand2); + buffer.AppendFormat(CultureInfo.InvariantCulture, "'{1}' {0} '{2}'", FilterOperator, operand1, operand2); break; } case FilterOperator.Between: { - buffer.AppendFormat("'{1}' <= '{0}' <= '{2}'", operand1, operand2, operand3); + buffer.AppendFormat(CultureInfo.InvariantCulture, "'{1}' <= '{0}' <= '{2}'", operand1, operand2, operand3); break; } case FilterOperator.Cast: { - buffer.AppendFormat("({1}){0}", operand1, operand2); + buffer.AppendFormat(CultureInfo.InvariantCulture, "({1}){0}", operand1, operand2); break; } case FilterOperator.InList: { - buffer.AppendFormat("'{0}' in ", operand1); + buffer.AppendFormat(CultureInfo.InvariantCulture, "'{0}' in ", operand1); buffer.Append('{'); for (int ii = 1; ii < operands.Count; ii++) { - buffer.AppendFormat("'{0}'", operands[ii].ToString()); + buffer.AppendFormat(CultureInfo.InvariantCulture, "'{0}'", operands[ii].ToString()); if (ii < operands.Count - 1) { buffer.Append(", "); @@ -775,7 +776,7 @@ public virtual string ToString(INodeTable nodeTable) case FilterOperator.RelatedTo: { - buffer.AppendFormat("'{0}' ", operand1); + buffer.AppendFormat(CultureInfo.InvariantCulture, "'{0}' ", operand1); string referenceType = operand2; @@ -792,11 +793,11 @@ public virtual string ToString(INodeTable nodeTable) } } - buffer.AppendFormat("{0} '{1}'", referenceType, operand2); + buffer.AppendFormat(CultureInfo.InvariantCulture, "{0} '{1}'", referenceType, operand2); if (operand3 != null) { - buffer.AppendFormat("Hops='{0}'", operand3); + buffer.AppendFormat(CultureInfo.InvariantCulture, "Hops='{0}'", operand3); } break; @@ -956,14 +957,14 @@ public partial class AttributeOperand : IFormattable /// /// Formats the value of the current instance using the specified format. /// - /// The specifying the format to use. + /// The specifying the format to use. /// -or- - /// null to use the default format defined for the type of the implementation. - /// The to use to format the value. + /// null to use the default format defined for the type of the implementation. + /// The to use to format the value. /// -or- /// null to obtain the numeric format information from the current locale setting of the operating system. /// - /// A containing the value of the current instance in the specified format. + /// A containing the value of the current instance in the specified format. /// public string ToString(string format, IFormatProvider formatProvider) { @@ -1097,26 +1098,26 @@ public override string ToString(INodeTable nodeTable) if (node != null) { - buffer.AppendFormat("{0}", NodeId); + buffer.AppendFormat(CultureInfo.InvariantCulture, "{0}", NodeId); } else { - buffer.AppendFormat("{0}", NodeId); + buffer.AppendFormat(CultureInfo.InvariantCulture, "{0}", NodeId); } if (!RelativePath.IsEmpty(BrowsePath)) { - buffer.AppendFormat("/{0}", BrowsePath.Format(nodeTable.TypeTree)); + buffer.AppendFormat(CultureInfo.InvariantCulture, "/{0}", BrowsePath.Format(nodeTable.TypeTree)); } if (!String.IsNullOrEmpty(IndexRange)) { - buffer.AppendFormat("[{0}]", NumericRange.Parse(IndexRange)); + buffer.AppendFormat(CultureInfo.InvariantCulture, "[{0}]", NumericRange.Parse(IndexRange)); } if (!String.IsNullOrEmpty(Alias)) { - buffer.AppendFormat("- '{0}'", Alias); + buffer.AppendFormat(CultureInfo.InvariantCulture, "- '{0}'", Alias); } return buffer.ToString(); @@ -1146,20 +1147,20 @@ public ElementOperand(uint index) /// /// Formats the value of the current instance using the specified format. /// - /// The specifying the format to use. + /// The specifying the format to use. /// -or- - /// null to use the default format defined for the type of the implementation. - /// The to use to format the value. + /// null to use the default format defined for the type of the implementation. + /// The to use to format the value. /// -or- /// null to obtain the numeric format information from the current locale setting of the operating system. /// - /// A containing the value of the current instance in the specified format. + /// A containing the value of the current instance in the specified format. /// public string ToString(string format, IFormatProvider formatProvider) { if (format == null) { - return String.Format("[{0}]", m_index); + return string.Format(formatProvider, "[{0}]", m_index); } throw new FormatException(Utils.Format("Invalid format string: '{0}'.", format)); @@ -1242,20 +1243,20 @@ public LiteralOperand(object value) /// /// Formats the value of the current instance using the specified format. /// - /// The specifying the format to use. + /// The specifying the format to use. /// -or- - /// null to use the default format defined for the type of the implementation. - /// The to use to format the value. + /// null to use the default format defined for the type of the implementation. + /// The to use to format the value. /// -or- /// null to obtain the numeric format information from the current locale setting of the operating system. /// - /// A containing the value of the current instance in the specified format. + /// A containing the value of the current instance in the specified format. /// public string ToString(string format, IFormatProvider formatProvider) { if (format == null) { - return String.Format("{0}", m_value); + return string.Format(formatProvider, "{0}", m_value); } throw new FormatException(Utils.Format("Invalid format string: '{0}'.", format)); diff --git a/Stack/Opc.Ua.Core/Stack/Nodes/Node.cs b/Stack/Opc.Ua.Core/Stack/Nodes/Node.cs index 5f787b491..a80261188 100644 --- a/Stack/Opc.Ua.Core/Stack/Nodes/Node.cs +++ b/Stack/Opc.Ua.Core/Stack/Nodes/Node.cs @@ -12,6 +12,7 @@ using System; using System.Collections.Generic; +using System.Globalization; namespace Opc.Ua { @@ -126,7 +127,7 @@ public string ToString(string format, IFormatProvider formatProvider) return m_browseName.Name; } - return Utils.Format("(unknown {0})", ((NodeClass)m_nodeClass).ToString().ToLower()); + return Utils.Format("(unknown {0})", ((NodeClass)m_nodeClass).ToString().ToLower(CultureInfo.InvariantCulture)); } throw new FormatException(Utils.Format("Invalid format string: '{0}'.", format)); @@ -500,7 +501,7 @@ public ReferenceNode(NodeId referenceTypeId, bool isInverse, ExpandedNodeId targ /// Returns a string representation of the HierarchyBrowsePath. /// /// - /// A that represents the current . + /// A that represents the current . /// public override string ToString() { diff --git a/Stack/Opc.Ua.Core/Stack/Nodes/ReferenceTable.cs b/Stack/Opc.Ua.Core/Stack/Nodes/ReferenceTable.cs index 69d929e34..0d3de16a2 100644 --- a/Stack/Opc.Ua.Core/Stack/Nodes/ReferenceTable.cs +++ b/Stack/Opc.Ua.Core/Stack/Nodes/ReferenceTable.cs @@ -154,7 +154,7 @@ public ReferenceCollection() /// Returns a string representation of the ReferenceCollection. /// /// - /// A that represents the current . + /// A that represents the current . /// public override string ToString() { @@ -164,14 +164,14 @@ public override string ToString() /// /// Returns a string representation of the ReferenceCollection. /// - /// The specifying the format to use. + /// The specifying the format to use. /// -or- - /// null to use the default format defined for the type of the implementation. - /// The to use to format the value. + /// null to use the default format defined for the type of the implementation. + /// The to use to format the value. /// -or- /// null to obtain the numeric format information from the current locale setting of the operating system. /// - /// A containing the value of the current instance in the specified format. + /// A containing the value of the current instance in the specified format. /// public string ToString(string format, IFormatProvider formatProvider) { @@ -180,7 +180,7 @@ public string ToString(string format, IFormatProvider formatProvider) throw new FormatException(Utils.Format("Invalid format string: '{0}'.", format)); } - return Utils.Format("References {0}", m_references.Count); + return string.Format(formatProvider, "References {0}", m_references.Count); } #endregion diff --git a/Stack/Opc.Ua.Core/Stack/Server/EndpointBase.cs b/Stack/Opc.Ua.Core/Stack/Server/EndpointBase.cs index ee7b94c31..da26557a4 100644 --- a/Stack/Opc.Ua.Core/Stack/Server/EndpointBase.cs +++ b/Stack/Opc.Ua.Core/Stack/Server/EndpointBase.cs @@ -887,7 +887,7 @@ public static IServiceRequest GetRequest(IAsyncResult ar) /// Saves an exception as response. /// /// The exception. - private IServiceResponse SaveExceptionAsResponse(Exception e) + private ServiceFault SaveExceptionAsResponse(Exception e) { try { diff --git a/Stack/Opc.Ua.Core/Stack/State/AlarmConditionState.cs b/Stack/Opc.Ua.Core/Stack/State/AlarmConditionState.cs index f42a592aa..be5c86f5d 100644 --- a/Stack/Opc.Ua.Core/Stack/State/AlarmConditionState.cs +++ b/Stack/Opc.Ua.Core/Stack/State/AlarmConditionState.cs @@ -760,10 +760,7 @@ private void OnTimerExpired(object state) { try { - if (OnTimedUnshelve != null) - { - OnTimedUnshelve((ISystemContext)state, this); - } + OnTimedUnshelve?.Invoke((ISystemContext)state, this); this.OnUnshelveTimeUpdate(state); } catch (Exception e) diff --git a/Stack/Opc.Ua.Core/Stack/State/BaseVariableState.cs b/Stack/Opc.Ua.Core/Stack/State/BaseVariableState.cs index 174358c38..8c3dbebd3 100644 --- a/Stack/Opc.Ua.Core/Stack/State/BaseVariableState.cs +++ b/Stack/Opc.Ua.Core/Stack/State/BaseVariableState.cs @@ -16,6 +16,7 @@ using System.Xml; using System.Runtime.Serialization; using System.Reflection; +using System.Globalization; namespace Opc.Ua { @@ -1270,7 +1271,7 @@ public static ReadOnlyList ArrayDimensionsFromXml(string value) return null; } - string[] fields = value.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); + string[] fields = value.Split(s_commaSeparator, StringSplitOptions.RemoveEmptyEntries); if (fields == null || fields.Length == 0) { @@ -1283,7 +1284,7 @@ public static ReadOnlyList ArrayDimensionsFromXml(string value) { try { - arrayDimensions[ii] = Convert.ToUInt32(fields[ii]); + arrayDimensions[ii] = Convert.ToUInt32(fields[ii], CultureInfo.InvariantCulture); } catch { @@ -2029,6 +2030,7 @@ public override void SetStatusCode(ISystemContext context, StatusCode statusCode private double m_minimumSamplingInterval; private bool m_historizing; private VariableCopyPolicy m_copyPolicy; + private static readonly char[] s_commaSeparator = new char[] { ',' }; #endregion } @@ -2491,10 +2493,7 @@ public void ChangesComplete(ISystemContext context) ISystemContext context, NodeState node) { - if (OnBeforeRead != null) - { - OnBeforeRead(context, this, node); - } + OnBeforeRead?.Invoke(context, this, node); } /// diff --git a/Stack/Opc.Ua.Core/Stack/State/DialogConditionState.cs b/Stack/Opc.Ua.Core/Stack/State/DialogConditionState.cs index 8699c4237..774fbd5d5 100644 --- a/Stack/Opc.Ua.Core/Stack/State/DialogConditionState.cs +++ b/Stack/Opc.Ua.Core/Stack/State/DialogConditionState.cs @@ -17,6 +17,7 @@ using System.IO; using System.Reflection; using Opc.Ua; +using System.Globalization; namespace Opc.Ua { @@ -195,7 +196,7 @@ protected override void UpdateEffectiveState(ISystemContext context) e.SetChildValue(context, BrowseNames.MethodId, method.NodeId, false); e.SetChildValue(context, BrowseNames.InputArguments, new object[] { selectedResponse }, false); - e.SetChildValue(context, BrowseNames.SelectedResponse, selectedResponse.ToString(), false); + e.SetChildValue(context, BrowseNames.SelectedResponse, selectedResponse.ToString(CultureInfo.InvariantCulture), false); ReportEvent(context, e); } diff --git a/Stack/Opc.Ua.Core/Stack/State/NodeState.cs b/Stack/Opc.Ua.Core/Stack/State/NodeState.cs index a0c0a5220..96753d26f 100644 --- a/Stack/Opc.Ua.Core/Stack/State/NodeState.cs +++ b/Stack/Opc.Ua.Core/Stack/State/NodeState.cs @@ -16,6 +16,7 @@ using System.Text; using System.IO; using System.Linq; +using System.Globalization; namespace Opc.Ua { @@ -109,7 +110,7 @@ protected virtual void InitializeOptionalChildren(ISystemContext context) /// The initialization string that is used to initializes the node. public virtual void Initialize(ISystemContext context, string initializationString) { - if (initializationString.StartsWith("<")) + if (initializationString.StartsWith("<", StringComparison.Ordinal)) { using (System.IO.StringReader reader = new System.IO.StringReader(initializationString)) { @@ -182,7 +183,7 @@ protected virtual void Initialize(ISystemContext context, NodeState source) /// Returns a string representation of the node. /// /// - /// A that represents the current . + /// A that represents the current . /// public override string ToString() { @@ -192,14 +193,14 @@ public override string ToString() /// /// Returns a string representation of the node. /// - /// The specifying the format to use. + /// The specifying the format to use. /// -or- - /// null to use the default format defined for the type of the implementation. - /// The to use to format the value. + /// null to use the default format defined for the type of the implementation. + /// The to use to format the value. /// -or- /// null to obtain the numeric format information from the current locale setting of the operating system. /// - /// A containing the value of the current instance in the specified format. + /// A containing the value of the current instance in the specified format. /// public string ToString(string format, IFormatProvider formatProvider) { @@ -210,10 +211,10 @@ public string ToString(string format, IFormatProvider formatProvider) if (!QualifiedName.IsNull(m_browseName)) { - return Utils.Format("[{0}]{1}", m_nodeClass, m_displayName); + return string.Format(formatProvider, "[{0}]{1}", m_nodeClass, m_displayName); } - return Utils.Format("[{0}]{1}", m_nodeClass, m_nodeId); + return string.Format(formatProvider, "[{0}]{1}", m_nodeClass, m_nodeId); } #endregion @@ -3935,7 +3936,7 @@ protected virtual void PopulateBrowser(ISystemContext context, NodeBrowser brows { if (value.GetType() == typeof(uint)) { - accessRestrictionsRef = Convert.ToUInt16(value); + accessRestrictionsRef = Convert.ToUInt16(value, CultureInfo.InvariantCulture); } else { diff --git a/Stack/Opc.Ua.Core/Stack/Tcp/UaSCBinaryClientChannel.cs b/Stack/Opc.Ua.Core/Stack/Tcp/UaSCBinaryClientChannel.cs index 0c4a109ec..f151b19cb 100644 --- a/Stack/Opc.Ua.Core/Stack/Tcp/UaSCBinaryClientChannel.cs +++ b/Stack/Opc.Ua.Core/Stack/Tcp/UaSCBinaryClientChannel.cs @@ -668,7 +668,7 @@ private bool ProcessOpenSecureChannelResponse(uint messageType, ArraySegment /// Formats the value of the current instance using the specified format. /// - /// The specifying the format to use. + /// The specifying the format to use. /// -or- - /// null to use the default format defined for the type of the implementation. - /// The to use to format the value. + /// null to use the default format defined for the type of the implementation. + /// The to use to format the value. /// -or- /// null to obtain the numeric format information from the current locale setting of the operating system. /// - /// A containing the value of the current instance in the specified format. + /// A containing the value of the current instance in the specified format. /// public string ToString(string format, IFormatProvider formatProvider) { @@ -570,21 +571,22 @@ public override string ToString(INodeTable nodeTable) if (node != null) { - buffer.AppendFormat("{0}", TypeDefinitionId); + // TODO: why is if and else the same codepath + buffer.AppendFormat(CultureInfo.InvariantCulture, "{0}", TypeDefinitionId); } else { - buffer.AppendFormat("{0}", TypeDefinitionId); + buffer.AppendFormat(CultureInfo.InvariantCulture, "{0}", TypeDefinitionId); } if (BrowsePath != null && BrowsePath.Count > 0) { - buffer.AppendFormat("{0}", Format(BrowsePath)); + buffer.AppendFormat(CultureInfo.InvariantCulture, "{0}", Format(BrowsePath)); } if (!String.IsNullOrEmpty(IndexRange)) { - buffer.AppendFormat("[{0}]", NumericRange.Parse(IndexRange)); + buffer.AppendFormat(CultureInfo.InvariantCulture, "[{0}]", NumericRange.Parse(IndexRange)); } return buffer.ToString(); @@ -617,7 +619,7 @@ public static string Format(IList browsePath) if (browseName.NamespaceIndex != 0) { - buffer.AppendFormat("{0}:", browseName.NamespaceIndex); + buffer.AppendFormat(CultureInfo.InvariantCulture, "{0}:", browseName.NamespaceIndex); } for (int jj = 0; jj < browseName.Name.Length; jj++) diff --git a/Stack/Opc.Ua.Core/Stack/Types/ReferenceDescription.cs b/Stack/Opc.Ua.Core/Stack/Types/ReferenceDescription.cs index 83f1639d4..39683a59c 100644 --- a/Stack/Opc.Ua.Core/Stack/Types/ReferenceDescription.cs +++ b/Stack/Opc.Ua.Core/Stack/Types/ReferenceDescription.cs @@ -12,6 +12,7 @@ using System; using System.Collections.Generic; +using System.Globalization; using System.Runtime.Serialization; using System.Security.Cryptography.X509Certificates; @@ -41,7 +42,7 @@ public string ToString(string format, IFormatProvider formatProvider) return m_browseName.Name; } - return Utils.Format("(unknown {0})", ((NodeClass)m_nodeClass).ToString().ToLower()); + return Utils.Format("(unknown {0})", ((NodeClass)m_nodeClass).ToString().ToLower(CultureInfo.InvariantCulture)); } throw new FormatException(Utils.Format("Invalid format string: '{0}'.", format)); diff --git a/Stack/Opc.Ua.Core/Stack/Types/UserTokenPolicy.cs b/Stack/Opc.Ua.Core/Stack/Types/UserTokenPolicy.cs index bfee23770..a621ddded 100644 --- a/Stack/Opc.Ua.Core/Stack/Types/UserTokenPolicy.cs +++ b/Stack/Opc.Ua.Core/Stack/Types/UserTokenPolicy.cs @@ -48,7 +48,7 @@ public string ToString(string format, IFormatProvider formatProvider) { if (format == null) { - return String.Format(formatProvider, "{0}", ToString()); + return string.Format(formatProvider, "{0}", ToString()); } throw new FormatException(Utils.Format("Invalid format string: '{0}'.", format)); diff --git a/Stack/Opc.Ua.Core/Types/BuiltIn/DataValue.cs b/Stack/Opc.Ua.Core/Types/BuiltIn/DataValue.cs index 52b3221a4..ceca1c7b6 100644 --- a/Stack/Opc.Ua.Core/Types/BuiltIn/DataValue.cs +++ b/Stack/Opc.Ua.Core/Types/BuiltIn/DataValue.cs @@ -337,7 +337,7 @@ public string ToString(string format, IFormatProvider formatProvider) { if (format == null) { - return String.Format(formatProvider, "{0}", m_value); + return string.Format(formatProvider, "{0}", m_value); } throw new FormatException(Utils.Format("Invalid format string: '{0}'.", format)); diff --git a/Stack/Opc.Ua.Core/Types/BuiltIn/ExpandedNodeId.cs b/Stack/Opc.Ua.Core/Types/BuiltIn/ExpandedNodeId.cs index 1a3c97a48..676ceb352 100644 --- a/Stack/Opc.Ua.Core/Types/BuiltIn/ExpandedNodeId.cs +++ b/Stack/Opc.Ua.Core/Types/BuiltIn/ExpandedNodeId.cs @@ -473,7 +473,7 @@ internal string IdentifierText { get { - return Format(); + return Format(CultureInfo.InvariantCulture); } set { @@ -514,25 +514,25 @@ internal string IdentifierText /// Note: Only information already included in the ExpandedNodeId-Instance will be included in the result /// /// - public string Format() + public string Format(IFormatProvider formatProvider) { StringBuilder buffer = new StringBuilder(); - Format(buffer); + Format(formatProvider ?? CultureInfo.InvariantCulture, buffer); return buffer.ToString(); } /// /// Formats the node ids as string and adds it to the buffer. /// - public void Format(StringBuilder buffer) + public void Format(IFormatProvider formatProvider, StringBuilder buffer) { if (m_nodeId != null) { - Format(buffer, m_nodeId.Identifier, m_nodeId.IdType, m_nodeId.NamespaceIndex, m_namespaceUri, m_serverIndex); + Format(formatProvider, buffer, m_nodeId.Identifier, m_nodeId.IdType, m_nodeId.NamespaceIndex, m_namespaceUri, m_serverIndex); } else { - Format(buffer, null, IdType.Numeric, 0, m_namespaceUri, m_serverIndex); + Format(formatProvider, buffer, null, IdType.Numeric, 0, m_namespaceUri, m_serverIndex); } } @@ -540,6 +540,19 @@ public void Format(StringBuilder buffer) /// Formats the node ids as string and adds it to the buffer. /// public static void Format( + StringBuilder buffer, + object identifier, + IdType identifierType, + ushort namespaceIndex, + string namespaceUri, + uint serverIndex) => + Format(CultureInfo.InvariantCulture, buffer, identifier, identifierType, namespaceIndex, namespaceUri, serverIndex); + + /// + /// Formats the node ids as string and adds it to the buffer. + /// + public static void Format( + IFormatProvider formatProvider, StringBuilder buffer, object identifier, IdType identifierType, @@ -549,7 +562,7 @@ public void Format(StringBuilder buffer) { if (serverIndex != 0) { - buffer.AppendFormat(CultureInfo.InvariantCulture, "svr={0};", serverIndex); + buffer.AppendFormat(formatProvider, "svr={0};", serverIndex); } if (!String.IsNullOrEmpty(namespaceUri)) @@ -565,7 +578,7 @@ public void Format(StringBuilder buffer) case ';': case '%': { - buffer.AppendFormat(CultureInfo.InvariantCulture, "%{0:X2}", Convert.ToInt16(ch)); + buffer.AppendFormat(formatProvider, "%{0:X2}", Convert.ToInt16(ch)); break; } @@ -580,7 +593,7 @@ public void Format(StringBuilder buffer) buffer.Append(';'); } - NodeId.Format(buffer, identifier, identifierType, namespaceIndex); + NodeId.Format(formatProvider, buffer, identifier, identifierType, namespaceIndex); } #endregion @@ -935,7 +948,7 @@ public string ToString(string format, IFormatProvider formatProvider) { if (format == null) { - return Format(); + return Format(formatProvider); } throw new FormatException(Utils.Format("Invalid format string: '{0}'.", format)); diff --git a/Stack/Opc.Ua.Core/Types/BuiltIn/ExtensionObject.cs b/Stack/Opc.Ua.Core/Types/BuiltIn/ExtensionObject.cs index 74a5de182..0a982c71b 100644 --- a/Stack/Opc.Ua.Core/Types/BuiltIn/ExtensionObject.cs +++ b/Stack/Opc.Ua.Core/Types/BuiltIn/ExtensionObject.cs @@ -12,6 +12,7 @@ using System; using System.Collections.Generic; +using System.Globalization; using System.Linq; using System.Reflection; using System.Runtime.Serialization; @@ -501,7 +502,7 @@ public override string ToString() /// (Unused). Leave this as null /// The provider of a mechanism for retrieving an object to control formatting. /// - /// A containing the value of the current embeded instance in the specified format. + /// A containing the value of the current embeded instance in the specified format. /// /// Thrown if the format parameter is not null public string ToString(string format, IFormatProvider formatProvider) @@ -510,17 +511,17 @@ public string ToString(string format, IFormatProvider formatProvider) { if (m_body is byte[] byteString) { - return String.Format(formatProvider, "Byte[{0}]", byteString.Length); + return string.Format(formatProvider, "Byte[{0}]", byteString.Length); } if (m_body is XmlElement element) { - return String.Format(formatProvider, "<{0}>", element.Name); + return string.Format(formatProvider, "<{0}>", element.Name); } if (m_body is IFormattable formattable) { - return String.Format(formatProvider, "{0}", formattable.ToString(null, formatProvider)); + return string.Format(formatProvider, "{0}", formattable.ToString(null, formatProvider)); } if (m_body is IEncodeable) @@ -546,7 +547,7 @@ public string ToString(string format, IFormatProvider formatProvider) body.Append(" | "); } - body.AppendFormat("{0}", property.GetGetMethod().Invoke(m_body, null)); + body.AppendFormat(formatProvider, "{0}", property.GetGetMethod().Invoke(m_body, null)); } } } @@ -556,12 +557,12 @@ public string ToString(string format, IFormatProvider formatProvider) body.Append('}'); } - return String.Format(formatProvider, "{0}", body); + return string.Format(formatProvider, "{0}", body); } if (!NodeId.IsNull(this.m_typeId)) { - return String.Format(formatProvider, "{{{0}}}", this.m_typeId); + return string.Format(formatProvider, "{{{0}}}", this.m_typeId); } return "(null)"; diff --git a/Stack/Opc.Ua.Core/Types/BuiltIn/LocalizedText.cs b/Stack/Opc.Ua.Core/Types/BuiltIn/LocalizedText.cs index 6e345d94d..5782be912 100644 --- a/Stack/Opc.Ua.Core/Types/BuiltIn/LocalizedText.cs +++ b/Stack/Opc.Ua.Core/Types/BuiltIn/LocalizedText.cs @@ -116,7 +116,7 @@ public LocalizedText(TranslationInfo translationInfo) try { - m_text = String.Format(culture, m_translationInfo.Text, m_translationInfo.Args); + m_text = string.Format(culture, m_translationInfo.Text, m_translationInfo.Args); } catch { @@ -375,7 +375,7 @@ public string ToString(string format, IFormatProvider formatProvider) { if (format == null) { - return String.Format(formatProvider, "{0}", this.m_text); + return string.Format(formatProvider, "{0}", this.m_text); } throw new FormatException(Utils.Format("Invalid format string: '{0}'.", format)); diff --git a/Stack/Opc.Ua.Core/Types/BuiltIn/Matrix.cs b/Stack/Opc.Ua.Core/Types/BuiltIn/Matrix.cs index d05824dac..064d5578f 100644 --- a/Stack/Opc.Ua.Core/Types/BuiltIn/Matrix.cs +++ b/Stack/Opc.Ua.Core/Types/BuiltIn/Matrix.cs @@ -1,5 +1,6 @@ using System; using System.Diagnostics; +using System.Globalization; using System.Runtime.Serialization; using System.Text; @@ -193,7 +194,7 @@ public string ToString(string format, IFormatProvider formatProvider) { StringBuilder buffer = new StringBuilder(); - buffer.AppendFormat("{0}[", m_elements.GetType().GetElementType().Name); + buffer.AppendFormat(formatProvider, "{0}[", m_elements.GetType().GetElementType().Name); for (int ii = 0; ii < m_dimensions.Length; ii++) { diff --git a/Stack/Opc.Ua.Core/Types/BuiltIn/NodeId.cs b/Stack/Opc.Ua.Core/Types/BuiltIn/NodeId.cs index ef4014b02..fd4582f60 100644 --- a/Stack/Opc.Ua.Core/Types/BuiltIn/NodeId.cs +++ b/Stack/Opc.Ua.Core/Types/BuiltIn/NodeId.cs @@ -57,8 +57,6 @@ namespace Opc.Ua public class NodeId : IComparable, IFormattable, IEquatable, ICloneable { #region Constructors - #region public NodeId() - /// /// Initializes the object with default values. /// @@ -71,8 +69,6 @@ public NodeId() Initialize(); } - #endregion - #region public NodeId(NodeId value) /// /// Creates a deep copy of the value. /// @@ -89,8 +85,7 @@ public NodeId(NodeId value) m_identifierType = value.m_identifierType; m_identifier = Utils.Clone(value.m_identifier); } - #endregion - #region public NodeId(uint value) + /// /// Initializes a numeric node identifier. /// @@ -104,8 +99,7 @@ public NodeId(uint value) m_identifierType = IdType.Numeric; m_identifier = value; } - #endregion - #region public NodeId(uint value, ushort namespaceIndex) + /// /// Initializes a numeric node identifier with a namespace index. /// @@ -123,9 +117,6 @@ public NodeId(uint value, ushort namespaceIndex) m_identifier = value; } - #endregion - - #region public NodeId(string value, ushort namespaceIndex) /// /// Initializes a string node identifier with a namespace index. /// @@ -142,8 +133,6 @@ public NodeId(string value, ushort namespaceIndex) m_identifier = value; } - #endregion - #region public NodeId(Guid value) /// /// Initializes a guid node identifier. /// @@ -158,9 +147,6 @@ public NodeId(Guid value) m_identifier = value; } - #endregion - - #region public NodeId(Guid value, ushort namespaceIndex) /// /// Initializes a guid node identifier. /// @@ -175,9 +161,7 @@ public NodeId(Guid value, ushort namespaceIndex) m_identifierType = IdType.Guid; m_identifier = value; } - #endregion - #region public NodeId(byte[] value) /// /// Initializes an opaque node identifier. /// @@ -199,8 +183,6 @@ public NodeId(byte[] value) } } - #endregion - #region public NodeId(byte[] value, ushort namespaceIndex) /// /// Initializes an opaque node identifier with a namespace index. /// @@ -224,8 +206,6 @@ public NodeId(byte[] value, ushort namespaceIndex) } } - #endregion - #region public NodeId(string text) /// /// Initializes a node id by parsing a node id string. /// @@ -242,9 +222,6 @@ public NodeId(string text) m_identifier = nodeId.Identifier; } - #endregion - - #region public NodeId(object value, ushort namespaceIndex) /// /// Initializes a node identifier with a namespace index. /// @@ -289,7 +266,6 @@ public NodeId(object value, ushort namespaceIndex) throw new ArgumentException("Identifier type not supported.", nameof(value)); } - #endregion /// /// Initializes the object during deserialization. @@ -337,7 +313,6 @@ public static NodeId Create(object identifier, string namespaceUri, NamespaceTab return new NodeId(identifier, (ushort)index); } - #region public static implicit operator NodeId(uint value) /// /// Converts an integer to a numeric node identifier. /// @@ -372,12 +347,12 @@ public static NodeId Create(object identifier, string namespaceUri, NamespaceTab /// 'create our node /// node1 = new NodeId(id1) /// - /// 'now to compare the node to the ids using a simple comparisson and Equals: + /// 'now to compare the node to the ids using a simple comparison and Equals: /// Utils.LogInfo("Comparing NodeId to uint") - /// Utils.LogInfo( String.Format(" Comparing 100 to 100 = [equals] {0}", node1.Equals(id1)) ) - /// Utils.LogInfo( String.Format(" Comparing 100 to 100 = [ = ] {0}", node1 = id1) ) - /// Utils.LogInfo( String.Format(" Comparing 100 to 101 = [equals] {0}", node1.Equals(id2)) ) - /// Utils.LogInfo( String.Format(" Comparing 100 to 101 = [ = ] {0}", node1 = id2) ) + /// Utils.LogInfo(" Comparing 100 to 100 = [equals] {0}", node1.Equals(id1)) + /// Utils.LogInfo(" Comparing 100 to 100 = [ = ] {0}", node1 = id1) + /// Utils.LogInfo(" Comparing 100 to 101 = [equals] {0}", node1.Equals(id2)) + /// Utils.LogInfo(" Comparing 100 to 101 = [ = ] {0}", node1 = id2) /// /// /// @@ -397,9 +372,6 @@ public static NodeId Create(object identifier, string namespaceUri, NamespaceTab return new NodeId(value); } - #endregion - - #region public static implicit operator NodeId(Guid value) /// /// Converts a guid to a guid node identifier. /// @@ -430,10 +402,10 @@ public static NodeId Create(object identifier, string namespaceUri, NamespaceTab /// /// 'now to compare the node to the guids /// Utils.LogInfo("Comparing NodeId to GUID") - /// Utils.LogInfo( String.Format( " Comparing {0} to {0} = [equals] {2}", id1, id1, node1.Equals(id1)) ); - /// Utils.LogInfo( String.Format( " Comparing {0} to {0} = [ = ] {2}", id1, id1, node1 = id1) ); - /// Utils.LogInfo( String.Format( " Comparing {0} to {0} = [equals] {2}", id1, id2, node1.Equals(id2)) ); - /// Utils.LogInfo( String.Format( " Comparing {0} to {0} = [ = ] {2}", id1, id2, node1 = id2) ); + /// Utils.LogInfo(" Comparing {0} to {0} = [equals] {2}", id1, id1, node1.Equals(id1)); + /// Utils.LogInfo(" Comparing {0} to {0} = [ = ] {2}", id1, id1, node1 = id1); + /// Utils.LogInfo(" Comparing {0} to {0} = [equals] {2}", id1, id2, node1.Equals(id2)); + /// Utils.LogInfo(" Comparing {0} to {0} = [ = ] {2}", id1, id2, node1 = id2); /// /// /// @@ -453,9 +425,6 @@ public static NodeId Create(object identifier, string namespaceUri, NamespaceTab return new NodeId(value); } - #endregion - - #region public static implicit operator NodeId(byte[] value) /// /// Converts a byte array to an opaque node identifier. /// @@ -495,10 +464,10 @@ public static NodeId Create(object identifier, string namespaceUri, NamespaceTab /// /// 'now to compare the node to the guids /// Utils.LogInfo("Comparing NodeId to Byte()") - /// Utils.LogInfo( String.Format("Comparing {0} to {0} = [equals] {2}", id1String, id1String, node1.Equals(id1)) ) - /// Utils.LogInfo( String.Format("Comparing {0} to {0} = [ = ] {2}", id1String, id1String, node1 = id1) ) - /// Utils.LogInfo( String.Format("Comparing {0} to {1} = [equals] {2}", id1String, id2String, node1.Equals(id2)) ) - /// Utils.LogInfo( String.Format("Comparing {0} to {1} = [ = ] {2}", id1String, id2String, node1 = id2) ) + /// Utils.LogInfo("Comparing {0} to {0} = [equals] {2}", id1String, id1String, node1.Equals(id1)) + /// Utils.LogInfo("Comparing {0} to {0} = [ = ] {2}", id1String, id1String, node1 = id1) + /// Utils.LogInfo("Comparing {0} to {1} = [equals] {2}", id1String, id2String, node1.Equals(id2)) + /// Utils.LogInfo("Comparing {0} to {1} = [ = ] {2}", id1String, id2String, node1 = id2) /// /// /// @@ -518,9 +487,6 @@ public static NodeId Create(object identifier, string namespaceUri, NamespaceTab return new NodeId(value); } - #endregion - - #region public static implicit operator NodeId(string text) /// /// Parses a node id string and initializes a node id. /// @@ -552,10 +518,10 @@ public static NodeId Create(object identifier, string namespaceUri, NamespaceTab /// /// 'now to compare the node to the guids /// Utils.LogInfo("Comparing NodeId to String"); - /// Utils.LogInfo(String.Format("Comparing {0} to {1} = [equals] {2}", id1, id1, node1.Equals(id1))); - /// Utils.LogInfo(String.Format("Comparing {0} to {1} = [ = ] {2}", id1, id1, node1 = id1)); - /// Utils.LogInfo(String.Format("Comparing {0} to {1} = [equals] {2}", id1, id2, node1.Equals(id2))); - /// Utils.LogInfo(String.Format("Comparing {0} to {1} = [ = ] {2}", id1, id2, node1 = id2)); + /// Utils.LogInfo("Comparing {0} to {1} = [equals] {2}", id1, id1, node1.Equals(id1)); + /// Utils.LogInfo("Comparing {0} to {1} = [ = ] {2}", id1, id1, node1 = id1); + /// Utils.LogInfo("Comparing {0} to {1} = [equals] {2}", id1, id2, node1.Equals(id2)); + /// Utils.LogInfo("Comparing {0} to {1} = [ = ] {2}", id1, id2, node1 = id2); /// /// /// @@ -565,9 +531,6 @@ public static NodeId Create(object identifier, string namespaceUri, NamespaceTab return NodeId.Parse(text); } - #endregion - - #region public static bool IsNull(NodeId nodeId) /// /// Checks if the node id represents a 'Null' node id. /// @@ -584,9 +547,7 @@ public static bool IsNull(NodeId nodeId) return nodeId.IsNullNodeId; } - #endregion - #region public static bool IsNull(ExpandedNodeId nodeId) /// /// Checks if the node id represents a 'Null' node id. /// @@ -603,9 +564,7 @@ public static bool IsNull(ExpandedNodeId nodeId) return nodeId.IsNull; } - #endregion - #region Public Static NodeId Parse(string text) /// /// Parses a node id string and returns a node id object. /// @@ -708,7 +667,6 @@ internal static NodeId InternalParse(string text, bool namespaceSet) throw argumentException; } - #endregion /// /// Returns an instance of a null NodeId. @@ -719,8 +677,6 @@ internal static NodeId InternalParse(string text, bool namespaceSet) #endregion #region Public Methods (and some Internals) - - #region public string Format() /// /// Formats a node id as a string. /// @@ -738,29 +694,35 @@ internal static NodeId InternalParse(string text, bool namespaceSet) /// ns=1;s=hello123 ///
/// - public string Format() + private string Format(IFormatProvider formatProvider) { StringBuilder buffer = new StringBuilder(); - Format(buffer); + Format(formatProvider, buffer); return buffer.ToString(); } /// /// Formats the NodeId as a string and appends it to the buffer. /// - public void Format(StringBuilder buffer) + private void Format(IFormatProvider formatProvider, StringBuilder buffer) { - Format(buffer, m_identifier, m_identifierType, m_namespaceIndex); + Format(formatProvider, buffer, m_identifier, m_identifierType, m_namespaceIndex); } /// /// Formats the NodeId as a string and appends it to the buffer. /// public static void Format(StringBuilder buffer, object identifier, IdType identifierType, ushort namespaceIndex) + => Format(CultureInfo.InvariantCulture, buffer, identifier, identifierType, namespaceIndex); + + /// + /// Formats the NodeId as a string and appends it to the buffer. + /// + public static void Format(IFormatProvider formatProvider, StringBuilder buffer, object identifier, IdType identifierType, ushort namespaceIndex) { if (namespaceIndex != 0) { - buffer.AppendFormat(CultureInfo.InvariantCulture, "ns={0};", namespaceIndex); + buffer.AppendFormat(formatProvider, "ns={0};", namespaceIndex); } // add identifier type prefix. @@ -792,29 +754,23 @@ public static void Format(StringBuilder buffer, object identifier, IdType identi } // add identifier. - FormatIdentifier(buffer, identifier, identifierType); + FormatIdentifier(formatProvider, buffer, identifier, identifierType); } - #endregion - - #region public override string ToString() /// /// Returns the string representation of a NodeId. /// /// /// Returns the Node represented as a String. This is the same as calling - /// . + /// . /// public override string ToString() { return ToString(null, null); } - #endregion - - #region public static ExpandedNodeId ToExpandedNodeId(NodeId nodeId, NamespaceTable namespaceTable) /// - /// Converts an node id to an expanded node id using a namespace table. + /// Converts a node id to an expanded node id using a namespace table. /// /// /// Returns an ExpandedNodeId based on the NodeId requested in the parameters. If the namespaceTable @@ -846,7 +802,6 @@ public static ExpandedNodeId ToExpandedNodeId(NodeId nodeId, NamespaceTable name return expandedId; } - #endregion /// /// Updates the namespace index. /// @@ -886,12 +841,9 @@ internal void SetIdentifier(string value, IdType idType) m_identifierType = idType; SetIdentifier(IdType.String, value); } - #endregion #region IComparable Members - - #region public int CompareTo(object obj) /// /// Compares the current instance to the object. /// @@ -1118,9 +1070,7 @@ public int CompareTo(object obj) return CompareTo(idType, id); } - #endregion - #region public static bool operator>(NodeId value1, NodeId value2) /// /// Returns true if a is greater than b. /// @@ -1136,9 +1086,7 @@ public int CompareTo(object obj) return false; } - #endregion - #region public static bool operator<(NodeId value1, NodeId value2) /// /// Returns true if a is less than b. /// @@ -1156,31 +1104,24 @@ public int CompareTo(object obj) } #endregion - #endregion - #region IFormattable Members - - #region public string ToString(string format, IFormatProvider formatProvider) /// /// Returns the string representation of a NodeId. /// /// /// Returns the string representation of a NodeId. This is the same as calling - /// . + /// . /// /// Thrown when the format is not null public string ToString(string format, IFormatProvider formatProvider) { if (format == null) { - return String.Format(formatProvider, "{0}", Format()); + return Format(formatProvider); } throw new FormatException(Utils.Format("Invalid format string: '{0}'.", format)); } - - #endregion - #endregion #region ICloneable @@ -1204,7 +1145,6 @@ public new object MemberwiseClone() #endregion #region Comparison Functions - #region public override bool Equals(object obj) /// /// Determines if the specified object is equal to the NodeId. /// @@ -1255,9 +1195,7 @@ public bool Equals(NodeId other) return CompareTo(other.IdType, other.Identifier) == 0; } - #endregion - #region public override int GetHashCode() /// /// Returns a unique hashcode for the NodeId /// @@ -1307,9 +1245,7 @@ public override int GetHashCode() } return hashCode.ToHashCode(); } - #endregion - #region public static bool operator==(NodeId a, object b) /// /// Returns true if the objects are equal. /// @@ -1325,9 +1261,7 @@ public override int GetHashCode() return (value1.CompareTo(value2) == 0); } - #endregion - #region public static bool operator!=(NodeId value1, object value2) /// /// Returns true if the objects are not equal. /// @@ -1345,11 +1279,7 @@ public override int GetHashCode() } #endregion - #endregion - #region Public Properties - - #region internal string IdentifierText /// /// The node identifier formatted as a URI. /// @@ -1361,7 +1291,7 @@ internal string IdentifierText { get { - return Format(); + return Format(CultureInfo.InvariantCulture); } set { @@ -1373,8 +1303,6 @@ internal string IdentifierText } } - #endregion - #region public ushort NamespaceIndex /// /// The index of the namespace URI in the server's namespace array. /// @@ -1383,8 +1311,6 @@ internal string IdentifierText /// public ushort NamespaceIndex => m_namespaceIndex; - #endregion - #region public IdType IdType /// /// The type of node identifier used. /// @@ -1400,8 +1326,6 @@ internal string IdentifierText /// public IdType IdType => m_identifierType; - #endregion - #region public object Identifier /// /// The node identifier. /// @@ -1425,8 +1349,6 @@ public object Identifier } } - #endregion - #region public bool IsNull /// /// Whether the object represents a Null NodeId. /// @@ -1496,8 +1418,6 @@ public bool IsNullNodeId } #endregion - #endregion - #region Private Methods /// /// Compares two node identifiers. @@ -1603,7 +1523,7 @@ private static int CompareIdentifiers(IdType idType1, object id1, IdType idType2 return comparable1.CompareTo(id2); } - return String.CompareOrdinal(id1.ToString(), id2.ToString()); + return string.CompareOrdinal(id1.ToString(), id2.ToString()); } /// @@ -1677,7 +1597,7 @@ private int CompareTo(IdType idType, object id) /// /// Formats a node id as a string. /// - private static void FormatIdentifier(StringBuilder buffer, object identifier, IdType identifierType) + private static void FormatIdentifier(IFormatProvider formatProvider, StringBuilder buffer, object identifier, IdType identifierType) { switch (identifierType) { @@ -1689,13 +1609,13 @@ private static void FormatIdentifier(StringBuilder buffer, object identifier, Id break; } - buffer.AppendFormat(CultureInfo.InvariantCulture, "{0}", identifier); + buffer.AppendFormat(formatProvider, "{0}", identifier); break; } case IdType.String: { - buffer.AppendFormat(CultureInfo.InvariantCulture, "{0}", identifier); + buffer.AppendFormat(formatProvider, "{0}", identifier); break; } @@ -1707,7 +1627,7 @@ private static void FormatIdentifier(StringBuilder buffer, object identifier, Id break; } - buffer.AppendFormat(CultureInfo.InvariantCulture, "{0}", identifier); + buffer.AppendFormat(formatProvider, "{0}", identifier); break; } @@ -1715,9 +1635,8 @@ private static void FormatIdentifier(StringBuilder buffer, object identifier, Id { if (identifier != null) { - buffer.AppendFormat(CultureInfo.InvariantCulture, "{0}", Convert.ToBase64String((byte[])identifier)); + buffer.AppendFormat(formatProvider, "{0}", Convert.ToBase64String((byte[])identifier)); } - break; } } diff --git a/Stack/Opc.Ua.Core/Types/BuiltIn/StatusCode.cs b/Stack/Opc.Ua.Core/Types/BuiltIn/StatusCode.cs index e38052def..abbca587e 100644 --- a/Stack/Opc.Ua.Core/Types/BuiltIn/StatusCode.cs +++ b/Stack/Opc.Ua.Core/Types/BuiltIn/StatusCode.cs @@ -12,6 +12,7 @@ using System; using System.Collections.Generic; +using System.Globalization; using System.Runtime.Serialization; using System.Text; using System.Xml.Serialization; @@ -479,10 +480,10 @@ public string ToString(string format, IFormatProvider formatProvider) if (!String.IsNullOrEmpty(text)) { - return String.Format(formatProvider, "{0}", text); + return string.Format(formatProvider, "{0}", text); } - return String.Format(formatProvider, "0x{0:X8}", m_code); + return string.Format(formatProvider, "0x{0:X8}", m_code); } @@ -540,7 +541,7 @@ public override string ToString() if ((0x0000FFFF & Code) != 0) { - buffer.AppendFormat(" [{0:X4}]", (0x0000FFFF & Code)); + buffer.AppendFormat(CultureInfo.InvariantCulture, " [{0:X4}]", (0x0000FFFF & Code)); } return buffer.ToString(); diff --git a/Stack/Opc.Ua.Core/Types/Encoders/BinaryDecoder.cs b/Stack/Opc.Ua.Core/Types/Encoders/BinaryDecoder.cs index 8bd04f1e0..11a0231eb 100644 --- a/Stack/Opc.Ua.Core/Types/Encoders/BinaryDecoder.cs +++ b/Stack/Opc.Ua.Core/Types/Encoders/BinaryDecoder.cs @@ -11,6 +11,7 @@ */ using System; +using System.Globalization; using System.IO; using System.Text; using System.Xml; @@ -1469,7 +1470,7 @@ public Array ReadEnumeratedArray(string fieldName, System.Type enumType) for (int i = 0; i < length; i++) { IEncodeable element = ReadEncodeable(null, systemType, encodeableTypeId); - elements.SetValue(Convert.ChangeType(element, systemType), i); + elements.SetValue(Convert.ChangeType(element, systemType, CultureInfo.InvariantCulture), i); } } diff --git a/Stack/Opc.Ua.Core/Types/Encoders/BinaryEncoder.cs b/Stack/Opc.Ua.Core/Types/Encoders/BinaryEncoder.cs index 3e3dd869b..703d59a71 100644 --- a/Stack/Opc.Ua.Core/Types/Encoders/BinaryEncoder.cs +++ b/Stack/Opc.Ua.Core/Types/Encoders/BinaryEncoder.cs @@ -2257,7 +2257,7 @@ private void WriteVariantValue(string fieldName, Variant value) case BuiltInType.LocalizedText: { WriteLocalizedText(null, (LocalizedText)valueToEncode); return; } case BuiltInType.ExtensionObject: { WriteExtensionObject(null, (ExtensionObject)valueToEncode); return; } case BuiltInType.DataValue: { WriteDataValue(null, (DataValue)valueToEncode); return; } - case BuiltInType.Enumeration: { WriteInt32(null, Convert.ToInt32(valueToEncode)); return; } + case BuiltInType.Enumeration: { WriteInt32(null, Convert.ToInt32(valueToEncode, CultureInfo.InvariantCulture)); return; } case BuiltInType.DiagnosticInfo: { WriteDiagnosticInfo(null, (DiagnosticInfo)valueToEncode); break; } } diff --git a/Stack/Opc.Ua.Core/Types/Encoders/JsonDecoder.cs b/Stack/Opc.Ua.Core/Types/Encoders/JsonDecoder.cs index 992acca07..3ae305cfc 100644 --- a/Stack/Opc.Ua.Core/Types/Encoders/JsonDecoder.cs +++ b/Stack/Opc.Ua.Core/Types/Encoders/JsonDecoder.cs @@ -2463,7 +2463,7 @@ public Array ReadEnumeratedArray(string fieldName, System.Type enumType) int ii = 0; foreach (var element in elements) { - newElements.SetValue(Convert.ChangeType(element, systemType), ii++); + newElements.SetValue(Convert.ChangeType(element, systemType, CultureInfo.InvariantCulture), ii++); } matrix = new Matrix(newElements, builtInType, dimensions.ToArray()); } @@ -2480,7 +2480,7 @@ public Array ReadEnumeratedArray(string fieldName, System.Type enumType) Array newElements = Array.CreateInstance(systemType, elements.Count); for (int i = 0; i < elements.Count; i++) { - newElements.SetValue(Convert.ChangeType(elements[i], systemType), i); + newElements.SetValue(Convert.ChangeType(elements[i], systemType, CultureInfo.InvariantCulture), i); } matrix = new Matrix(newElements, builtInType, dimensions.ToArray()); break; @@ -2501,7 +2501,7 @@ public Array ReadEnumeratedArray(string fieldName, System.Type enumType) Array newElements = Array.CreateInstance(systemType, elements.Count); for (int i = 0; i < elements.Count; i++) { - newElements.SetValue(Convert.ChangeType(elements[i], systemType), i); + newElements.SetValue(Convert.ChangeType(elements[i], systemType, CultureInfo.InvariantCulture), i); } matrix = new Matrix(newElements, builtInType, dimensions.ToArray()); break; diff --git a/Stack/Opc.Ua.Core/Types/Encoders/XmlEncoder.cs b/Stack/Opc.Ua.Core/Types/Encoders/XmlEncoder.cs index 0a993d532..cc9d51cea 100644 --- a/Stack/Opc.Ua.Core/Types/Encoders/XmlEncoder.cs +++ b/Stack/Opc.Ua.Core/Types/Encoders/XmlEncoder.cs @@ -573,7 +573,7 @@ public void WriteNodeId(string fieldName, NodeId value) } StringBuilder buffer = new StringBuilder(); - NodeId.Format(buffer, value.Identifier, value.IdType, namespaceIndex); + NodeId.Format(CultureInfo.InvariantCulture, buffer, value.Identifier, value.IdType, namespaceIndex); WriteString("Identifier", buffer.ToString()); } @@ -609,7 +609,7 @@ public void WriteExpandedNodeId(string fieldName, ExpandedNodeId value) } StringBuilder buffer = new StringBuilder(); - ExpandedNodeId.Format(buffer, value.Identifier, value.IdType, namespaceIndex, value.NamespaceUri, serverIndex); + ExpandedNodeId.Format(CultureInfo.InvariantCulture, buffer, value.Identifier, value.IdType, namespaceIndex, value.NamespaceUri, serverIndex); WriteString("Identifier", buffer.ToString()); } @@ -895,7 +895,7 @@ public void WriteEnumerated(string fieldName, Enum value) if (value != null) { var valueSymbol = value.ToString(); - var valueInt32 = Convert.ToInt32(value, CultureInfo.InvariantCulture).ToString(); + var valueInt32 = Convert.ToInt32(value, CultureInfo.InvariantCulture).ToString(CultureInfo.InvariantCulture); if (valueSymbol != valueInt32) { m_writer.WriteString(Utils.Format("{0}_{1}", valueSymbol, valueInt32)); diff --git a/Stack/Opc.Ua.Core/Types/Schemas/BinarySchemaValidator.cs b/Stack/Opc.Ua.Core/Types/Schemas/BinarySchemaValidator.cs index 111db9b45..691f4946c 100644 --- a/Stack/Opc.Ua.Core/Types/Schemas/BinarySchemaValidator.cs +++ b/Stack/Opc.Ua.Core/Types/Schemas/BinarySchemaValidator.cs @@ -178,7 +178,7 @@ private void Validate() foreach (TypeDescription description in m_validatedDescriptions) { ValidateDescription(description); - m_warnings.Add(String.Format(CultureInfo.InvariantCulture, "{0} '{1}' validated.", description.GetType().Name, description.Name)); + m_warnings.Add(string.Format(CultureInfo.InvariantCulture, "{0} '{1}' validated.", description.GetType().Name, description.Name)); } } } @@ -407,12 +407,12 @@ private void ValidateDescription(TypeDescription description) { if (!opaque.LengthInBitsSpecified) { - m_warnings.Add(String.Format(CultureInfo.InvariantCulture, "Warning: The opaque type '{0}' does not have a length specified.", description.Name)); + m_warnings.Add(string.Format(CultureInfo.InvariantCulture, "Warning: The opaque type '{0}' does not have a length specified.", description.Name)); } if (IsNull(opaque.Documentation)) { - m_warnings.Add(String.Format(CultureInfo.InvariantCulture, "Warning: The opaque type '{0}' does not have any documentation.", description.Name)); + m_warnings.Add(string.Format(CultureInfo.InvariantCulture, "Warning: The opaque type '{0}' does not have any documentation.", description.Name)); } } diff --git a/Stack/Opc.Ua.Core/Types/Schemas/SchemaValidator.cs b/Stack/Opc.Ua.Core/Types/Schemas/SchemaValidator.cs index dfb4b69be..4d3fea1d8 100644 --- a/Stack/Opc.Ua.Core/Types/Schemas/SchemaValidator.cs +++ b/Stack/Opc.Ua.Core/Types/Schemas/SchemaValidator.cs @@ -106,7 +106,7 @@ protected static Exception Exception(string format) /// protected static Exception Exception(string format, object arg1) { - return new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, format, arg1)); + return new InvalidOperationException(Utils.Format(format, arg1)); } /// @@ -114,7 +114,7 @@ protected static Exception Exception(string format, object arg1) /// protected static Exception Exception(string format, object arg1, object arg2) { - return new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, format, arg1, arg2)); + return new InvalidOperationException(Utils.Format(format, arg1, arg2)); } /// @@ -122,7 +122,7 @@ protected static Exception Exception(string format, object arg1, object arg2) /// protected static Exception Exception(string format, object arg1, object arg2, object arg3) { - return new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, format, arg1, arg2, arg3)); + return new InvalidOperationException(Utils.Format(format, arg1, arg2, arg3)); } /// @@ -280,7 +280,7 @@ protected static object LoadResource(Type type, string path, Assembly assembly) } catch (Exception e) { - throw new FileNotFoundException(String.Format(CultureInfo.InvariantCulture, "Could not load resource '{0}'.", path), e); + throw new FileNotFoundException(Utils.Format("Could not load resource '{0}'.", path), e); } } diff --git a/Stack/Opc.Ua.Core/Types/Utils/NumericRange.cs b/Stack/Opc.Ua.Core/Types/Utils/NumericRange.cs index ef714ae25..539ed316c 100644 --- a/Stack/Opc.Ua.Core/Types/Utils/NumericRange.cs +++ b/Stack/Opc.Ua.Core/Types/Utils/NumericRange.cs @@ -351,10 +351,10 @@ public string ToString(string format, IFormatProvider formatProvider) { if (m_end < 0) { - return String.Format(formatProvider, "{0}", m_begin); + return string.Format(formatProvider, "{0}", m_begin); } - return String.Format(formatProvider, "{0}:{1}", m_begin, m_end); + return string.Format(formatProvider, "{0}:{1}", m_begin, m_end); } throw new FormatException(Utils.Format("Invalid format string: '{0}'.", format)); diff --git a/Stack/Opc.Ua.Core/Types/Utils/RelativePath.cs b/Stack/Opc.Ua.Core/Types/Utils/RelativePath.cs index ebfb679d1..482433f71 100644 --- a/Stack/Opc.Ua.Core/Types/Utils/RelativePath.cs +++ b/Stack/Opc.Ua.Core/Types/Utils/RelativePath.cs @@ -400,7 +400,7 @@ public string ToString(string format, IFormatProvider formatProvider) foreach (Element element in m_elements) { - path.AppendFormat("{0}", element); + path.AppendFormat(formatProvider, "{0}", element); } return path.ToString(); @@ -635,7 +635,7 @@ public string ToString(string format, IFormatProvider formatProvider) if (m_referenceTypeName.NamespaceIndex != 0) { - path.AppendFormat("{0}:", m_referenceTypeName.NamespaceIndex); + path.AppendFormat(formatProvider, "{0}:", m_referenceTypeName.NamespaceIndex); } EncodeName(path, m_referenceTypeName.Name); @@ -651,7 +651,7 @@ public string ToString(string format, IFormatProvider formatProvider) { if (m_targetName.NamespaceIndex != 0) { - path.AppendFormat("{0}:", m_targetName.NamespaceIndex); + path.AppendFormat(formatProvider, "{0}:", m_targetName.NamespaceIndex); } EncodeName(path, m_targetName.Name); diff --git a/Stack/Opc.Ua.Core/Types/Utils/ServiceResult.cs b/Stack/Opc.Ua.Core/Types/Utils/ServiceResult.cs index 970d65844..a4f4041a8 100644 --- a/Stack/Opc.Ua.Core/Types/Utils/ServiceResult.cs +++ b/Stack/Opc.Ua.Core/Types/Utils/ServiceResult.cs @@ -722,22 +722,22 @@ public override string ToString() { if (!String.IsNullOrEmpty(m_namespaceUri)) { - buffer.AppendFormat(" ({0}:{1})", m_namespaceUri, m_symbolicId); + buffer.AppendFormat(CultureInfo.InvariantCulture, " ({0}:{1})", m_namespaceUri, m_symbolicId); } else if (m_symbolicId != buffer.ToString()) { - buffer.AppendFormat(" ({0})", m_symbolicId); + buffer.AppendFormat(CultureInfo.InvariantCulture, " ({0})", m_symbolicId); } } if (!LocalizedText.IsNullOrEmpty(m_localizedText)) { - buffer.AppendFormat(" '{0}'", m_localizedText); + buffer.AppendFormat(CultureInfo.InvariantCulture, " '{0}'", m_localizedText); } if ((0x0000FFFF & Code) != 0) { - buffer.AppendFormat(" [{0:X4}]", (0x0000FFFF & Code)); + buffer.AppendFormat(CultureInfo.InvariantCulture, " [{0:X4}]", (0x0000FFFF & Code)); } return buffer.ToString(); @@ -809,12 +809,12 @@ private static string GetDefaultMessage(Exception exception) { if (exception != null && exception.Message != null) { - if (exception.Message.StartsWith("[") || exception is ServiceResultException) + if (exception.Message.StartsWith("[", StringComparison.Ordinal) || exception is ServiceResultException) { return exception.Message; } - return String.Format(CultureInfo.InvariantCulture, "[{0}] {1}", exception.GetType().Name, exception.Message); + return Utils.Format("[{0}] {1}", exception.GetType().Name, exception.Message); } return String.Empty; diff --git a/Stack/Opc.Ua.Core/Types/Utils/TypeInfo.cs b/Stack/Opc.Ua.Core/Types/Utils/TypeInfo.cs index ec5b20efd..1f06d6125 100644 --- a/Stack/Opc.Ua.Core/Types/Utils/TypeInfo.cs +++ b/Stack/Opc.Ua.Core/Types/Utils/TypeInfo.cs @@ -11,6 +11,7 @@ */ using System; +using System.Globalization; using System.Reflection; using System.Threading; using System.Threading.Tasks; @@ -2295,7 +2296,7 @@ private static string ToString(object value, TypeInfo sourceType) case BuiltInType.StatusCode: { - return ((StatusCode)value).Code.ToString(); + return ((StatusCode)value).Code.ToString(CultureInfo.InvariantCulture); } case BuiltInType.ExtensionObject: @@ -2553,14 +2554,14 @@ private static StatusCode ToStatusCode(object value, TypeInfo sourceType) case BuiltInType.UInt16: { - uint code = Convert.ToUInt32((ushort)value); + uint code = Convert.ToUInt32((ushort)value, CultureInfo.InvariantCulture); code <<= 16; return (StatusCode)code; } case BuiltInType.Int32: { - return (StatusCode)Convert.ToUInt32((int)value); + return (StatusCode)Convert.ToUInt32((int)value, CultureInfo.InvariantCulture); } case BuiltInType.UInt32: @@ -2570,7 +2571,7 @@ private static StatusCode ToStatusCode(object value, TypeInfo sourceType) case BuiltInType.Int64: { - return (StatusCode)Convert.ToUInt32((long)value); + return (StatusCode)Convert.ToUInt32((long)value, CultureInfo.InvariantCulture); } case BuiltInType.UInt64: @@ -2589,12 +2590,12 @@ private static StatusCode ToStatusCode(object value, TypeInfo sourceType) text = text.Trim(); - if (text.StartsWith("0x")) + if (text.StartsWith("0x", StringComparison.Ordinal)) { return (StatusCode)Convert.ToUInt32(text.Substring(2), 16); } - return (StatusCode)Convert.ToUInt32((string)value); + return (StatusCode)Convert.ToUInt32((string)value, CultureInfo.InvariantCulture); } } diff --git a/Stack/Opc.Ua.Core/Types/Utils/Utils.cs b/Stack/Opc.Ua.Core/Types/Utils/Utils.cs index e3e5a4a78..b7559aa5b 100644 --- a/Stack/Opc.Ua.Core/Types/Utils/Utils.cs +++ b/Stack/Opc.Ua.Core/Types/Utils/Utils.cs @@ -316,7 +316,7 @@ private static void TraceWriteLine(string message, params object[] args) { try { - output = String.Format(CultureInfo.InvariantCulture, message, args); + output = string.Format(CultureInfo.InvariantCulture, message, args); } catch (Exception) { @@ -1584,7 +1584,7 @@ public static string ToString(object source) { if (source != null) { - return String.Format(CultureInfo.InvariantCulture, "{0}", source); + return string.Format(CultureInfo.InvariantCulture, "{0}", source); } return String.Empty; @@ -1595,7 +1595,7 @@ public static string ToString(object source) /// public static string Format(string text, params object[] args) { - return String.Format(CultureInfo.InvariantCulture, text, args); + return string.Format(CultureInfo.InvariantCulture, text, args); } /// diff --git a/Tests/Opc.Ua.Client.ComplexTypes.Tests/Types/ComplexTypesCommon.cs b/Tests/Opc.Ua.Client.ComplexTypes.Tests/Types/ComplexTypesCommon.cs index b4ca7dbca..7cf43a05c 100644 --- a/Tests/Opc.Ua.Client.ComplexTypes.Tests/Types/ComplexTypesCommon.cs +++ b/Tests/Opc.Ua.Client.ComplexTypes.Tests/Types/ComplexTypesCommon.cs @@ -114,8 +114,8 @@ public StructureFieldParameter(StructureField structureField) BuiltInType = TypeInfo.GetBuiltInType(structureField.DataType); } - public string Name; - public BuiltInType BuiltInType; + public string Name { get; set; } + public BuiltInType BuiltInType { get; set; } public string ToString(string format, IFormatProvider formatProvider) { diff --git a/Tests/Opc.Ua.Client.Tests/ReverseConnectTest.cs b/Tests/Opc.Ua.Client.Tests/ReverseConnectTest.cs index 02b34d762..e277b587f 100644 --- a/Tests/Opc.Ua.Client.Tests/ReverseConnectTest.cs +++ b/Tests/Opc.Ua.Client.Tests/ReverseConnectTest.cs @@ -28,6 +28,7 @@ * ======================================================================*/ using System; +using System.Globalization; using System.IO; using System.Runtime.InteropServices; using System.Threading; @@ -83,7 +84,7 @@ public async Task OneTimeSetUpAsync() await ClientFixture.LoadClientConfiguration(PkiRoot).ConfigureAwait(false); await ClientFixture.StartReverseConnectHost().ConfigureAwait(false); - m_endpointUrl = new Uri(Utils.ReplaceLocalhost("opc.tcp://localhost:" + ServerFixture.Port.ToString())); + m_endpointUrl = new Uri(Utils.ReplaceLocalhost("opc.tcp://localhost:" + ServerFixture.Port.ToString(CultureInfo.InvariantCulture))); // start reverse connection ReferenceServer.AddReverseConnection(new Uri(ClientFixture.ReverseConnectUri), MaxTimeout); } diff --git a/Tests/Opc.Ua.Client.Tests/SubscriptionTest.cs b/Tests/Opc.Ua.Client.Tests/SubscriptionTest.cs index 6e37a7912..0b6db7f4f 100644 --- a/Tests/Opc.Ua.Client.Tests/SubscriptionTest.cs +++ b/Tests/Opc.Ua.Client.Tests/SubscriptionTest.cs @@ -1258,7 +1258,7 @@ public void FastKeepAliveCallback() } } - private IList CreateMonitoredItemTestSet(Subscription subscription, IList nodeIds) + private List CreateMonitoredItemTestSet(Subscription subscription, IList nodeIds) { var list = new List(); foreach (NodeId nodeId in nodeIds) diff --git a/Tests/Opc.Ua.Configuration.Tests/CertificateStoreTypeTest.cs b/Tests/Opc.Ua.Configuration.Tests/CertificateStoreTypeTest.cs index f58f13b39..8b4b6c692 100644 --- a/Tests/Opc.Ua.Configuration.Tests/CertificateStoreTypeTest.cs +++ b/Tests/Opc.Ua.Configuration.Tests/CertificateStoreTypeTest.cs @@ -139,7 +139,7 @@ public ICertificateStore CreateStore() public bool SupportsStorePath(string storePath) { - return storePath != null && storePath.StartsWith(TestCertStore.StoreTypePrefix); + return storePath != null && storePath.StartsWith(TestCertStore.StoreTypePrefix, StringComparison.Ordinal); } } diff --git a/Tests/Opc.Ua.Core.Tests/Security/Certificates/ApplicationTestDataGenerator.cs b/Tests/Opc.Ua.Core.Tests/Security/Certificates/ApplicationTestDataGenerator.cs index 2055be787..21d564ee3 100644 --- a/Tests/Opc.Ua.Core.Tests/Security/Certificates/ApplicationTestDataGenerator.cs +++ b/Tests/Opc.Ua.Core.Tests/Security/Certificates/ApplicationTestDataGenerator.cs @@ -29,6 +29,7 @@ using System; using System.Collections.Generic; +using System.Globalization; using System.Text.RegularExpressions; using Opc.Ua.Test; @@ -97,7 +98,7 @@ private ApplicationTestData RandomApplicationTestData() ApplicationName = appName, ApplicationUri = appUri, DomainNames = domainNames, - Subject = String.Format("CN={0},O=OPC Foundation,DC={1}", appName, localhost), + Subject = Utils.Format("CN={0},O=OPC Foundation,DC={1}", appName, localhost), PrivateKeyFormat = privateKeyFormat }; return testData; @@ -132,15 +133,15 @@ private StringCollection RandomDiscoveryUrl(StringCollection domainNames, int po int random = m_randomSource.NextInt32(7); if ((result.Count == 0) || (random & 1) == 0) { - result.Add(String.Format("opc.tcp://{0}:{1}/{2}", name, (port++).ToString(), appUri)); + result.Add(Utils.Format("opc.tcp://{0}:{1}/{2}", name, (port++).ToString(CultureInfo.InvariantCulture), appUri)); } if ((random & 2) == 0) { - result.Add(String.Format("http://{0}:{1}/{2}", name, (port++).ToString(), appUri)); + result.Add(Utils.Format("http://{0}:{1}/{2}", name, (port++).ToString(CultureInfo.InvariantCulture), appUri)); } if ((random & 4) == 0) { - result.Add(String.Format("opc.https://{0}:{1}/{2}", name, (port++).ToString(), appUri)); + result.Add(Utils.Format("opc.https://{0}:{1}/{2}", name, (port++).ToString(CultureInfo.InvariantCulture), appUri)); } } return result; diff --git a/Tests/Opc.Ua.Core.Tests/Stack/Transport/MessageSocketTests.cs b/Tests/Opc.Ua.Core.Tests/Stack/Transport/MessageSocketTests.cs index e0c536881..59e86e103 100644 --- a/Tests/Opc.Ua.Core.Tests/Stack/Transport/MessageSocketTests.cs +++ b/Tests/Opc.Ua.Core.Tests/Stack/Transport/MessageSocketTests.cs @@ -45,7 +45,7 @@ protected void TearDown() #region Test Methods [Test] - public void IMessageSocket_IPEndpoint_Returned() + public void IMessageSocketIPEndpointReturned() { var messageSocketMock = new Mock(); var endPoint = new IPEndPoint(IPAddress.Parse("192.168.0.1"), 55062); diff --git a/Tests/Opc.Ua.Core.Tests/Types/BuiltIn/BuiltInTests.cs b/Tests/Opc.Ua.Core.Tests/Types/BuiltIn/BuiltInTests.cs index 5bfd60dc8..e1d72ea93 100644 --- a/Tests/Opc.Ua.Core.Tests/Types/BuiltIn/BuiltInTests.cs +++ b/Tests/Opc.Ua.Core.Tests/Types/BuiltIn/BuiltInTests.cs @@ -413,7 +413,7 @@ public void NodeIdConstructor() Assert.True(NodeId.IsNull((ExpandedNodeId)null)); Assert.True(NodeId.IsNull(new ExpandedNodeId(Guid.Empty))); Assert.True(NodeId.IsNull(ExpandedNodeId.Null)); - Assert.True(NodeId.IsNull(new ExpandedNodeId(new byte[0]))); + Assert.True(NodeId.IsNull(new ExpandedNodeId(Array.Empty()))); Assert.True(NodeId.IsNull(new ExpandedNodeId("", 0))); Assert.True(NodeId.IsNull(new ExpandedNodeId(0))); Assert.False(NodeId.IsNull(new ExpandedNodeId(1))); @@ -548,7 +548,7 @@ public void ExpandedNodeIdConstructor() public void NodeIdHashCode() { // ensure that the hash code is the same for the same node id - IList nodeIds = new List(); + var nodeIds = new List(); // Null NodeIds nodeIds.Add(0); @@ -557,7 +557,7 @@ public void NodeIdHashCode() nodeIds.Add(new NodeId(0)); nodeIds.Add(new NodeId(Guid.Empty)); nodeIds.Add(new NodeId("")); - nodeIds.Add(new NodeId(new byte[0])); + nodeIds.Add(new NodeId(Array.Empty())); foreach (NodeId nodeId in nodeIds) { @@ -660,7 +660,7 @@ public void NullIdNodeIdComparison(Opc.Ua.IdType idType) case Opc.Ua.IdType.Numeric: nodeId = new NodeId(0, 0); break; case Opc.Ua.IdType.String: nodeId = new NodeId(""); break; case Opc.Ua.IdType.Guid: nodeId = new NodeId(Guid.Empty); break; - case Opc.Ua.IdType.Opaque: nodeId = new NodeId(new byte[0]); break; + case Opc.Ua.IdType.Opaque: nodeId = new NodeId(Array.Empty()); break; case (Opc.Ua.IdType)100: nodeId = new NodeId((byte[])null); break; } @@ -669,14 +669,14 @@ public void NullIdNodeIdComparison(Opc.Ua.IdType idType) Assert.AreEqual(nodeId, NodeId.Null); Assert.AreEqual(nodeId, new NodeId(0, 0)); Assert.AreEqual(nodeId, new NodeId(Guid.Empty)); - Assert.AreEqual(nodeId, new NodeId(new byte[0])); + Assert.AreEqual(nodeId, new NodeId(Array.Empty())); Assert.AreEqual(nodeId, new NodeId((byte[])null)); Assert.AreEqual(nodeId, new NodeId((string)null)); Assert.True(nodeId.Equals(NodeId.Null)); Assert.True(nodeId.Equals(new NodeId(0, 0))); Assert.True(nodeId.Equals(new NodeId(Guid.Empty))); - Assert.True(nodeId.Equals(new NodeId(new byte[0]))); + Assert.True(nodeId.Equals(new NodeId(Array.Empty()))); Assert.True(nodeId.Equals(new NodeId((byte[])null))); Assert.True(nodeId.Equals(new NodeId((string)null))); diff --git a/Tests/Opc.Ua.Core.Tests/Types/BuiltIn/SessionLessServiceMessageTests.cs b/Tests/Opc.Ua.Core.Tests/Types/BuiltIn/SessionLessServiceMessageTests.cs index 1c8db7645..fd32f603d 100644 --- a/Tests/Opc.Ua.Core.Tests/Types/BuiltIn/SessionLessServiceMessageTests.cs +++ b/Tests/Opc.Ua.Core.Tests/Types/BuiltIn/SessionLessServiceMessageTests.cs @@ -14,7 +14,7 @@ namespace Opc.Ua.Core.Tests.Types.BuiltIn public class SessionLessServiceMessageTests { [Test] - public void WhenServerUrisAreLessThanNamespaces_ShouldNotThrowAndMustReturnCorrectServerUris() + public void WhenServerUrisAreLessThanNamespacesShouldNotThrowAndMustReturnCorrectServerUris() { //arrange UInt32 uriVersion = 1234; diff --git a/Tests/Opc.Ua.Core.Tests/Types/Encoders/JsonEncoderTests.cs b/Tests/Opc.Ua.Core.Tests/Types/Encoders/JsonEncoderTests.cs index 947418e34..e04feba43 100644 --- a/Tests/Opc.Ua.Core.Tests/Types/Encoders/JsonEncoderTests.cs +++ b/Tests/Opc.Ua.Core.Tests/Types/Encoders/JsonEncoderTests.cs @@ -80,7 +80,7 @@ public class JsonEncoderTests : EncoderCommon /// shall be followed by the JSON encoder accordingly. /// [DatapointSource] - public JsonValidationData[] Data = new JsonValidationDataCollection() { + public static readonly JsonValidationData[] Data = new JsonValidationDataCollection() { { BuiltInType.Boolean, true,"true", null }, { BuiltInType.Boolean, false, null, null }, { BuiltInType.Boolean, false, "false", null, true }, diff --git a/Tests/Opc.Ua.Core.Tests/Types/Utils/LogTests.cs b/Tests/Opc.Ua.Core.Tests/Types/Utils/LogTests.cs index 0a24a9579..0801c8e0c 100644 --- a/Tests/Opc.Ua.Core.Tests/Types/Utils/LogTests.cs +++ b/Tests/Opc.Ua.Core.Tests/Types/Utils/LogTests.cs @@ -114,7 +114,7 @@ public void TraceEventHandler(object sender, TraceEventArgs e) m_writer.WriteLine(e.Exception); m_traceList.Add(e.Exception.Message); } - string message = string.Format(e.Format, e.Arguments); + string message = Utils.Format(e.Format, e.Arguments); m_writer.WriteLine(message); m_traceList.Add(message); } diff --git a/Tests/Opc.Ua.Gds.Tests/Common.cs b/Tests/Opc.Ua.Gds.Tests/Common.cs index bdf63217d..6b3d45770 100644 --- a/Tests/Opc.Ua.Gds.Tests/Common.cs +++ b/Tests/Opc.Ua.Gds.Tests/Common.cs @@ -29,6 +29,7 @@ using System; using System.Collections.Generic; +using System.Globalization; using System.IO; using System.Text.RegularExpressions; using System.Threading; @@ -144,7 +145,7 @@ private ApplicationTestData RandomApplicationTestData() ServerCapabilities = serverCapabilities }, DomainNames = domainNames, - Subject = String.Format("CN={0},DC={1},O=OPC Foundation", appName, localhost), + Subject = Utils.Format("CN={0},DC={1},O=OPC Foundation", appName, localhost), PrivateKeyFormat = privateKeyFormat }; return testData; @@ -197,15 +198,15 @@ private StringCollection RandomDiscoveryUrl(StringCollection domainNames, int po int random = m_randomSource.NextInt32(7); if ((result.Count == 0) || (random & 1) == 0) { - result.Add(String.Format("opc.tcp://{0}:{1}/{2}", name, (port++).ToString(), appUri)); + result.Add(Utils.Format("opc.tcp://{0}:{1}/{2}", name, (port++).ToString(CultureInfo.InvariantCulture), appUri)); } if ((random & 2) == 0) { - result.Add(String.Format("http://{0}:{1}/{2}", name, (port++).ToString(), appUri)); + result.Add(Utils.Format("http://{0}:{1}/{2}", name, (port++).ToString(CultureInfo.InvariantCulture), appUri)); } if ((random & 4) == 0) { - result.Add(String.Format("opc.https://{0}:{1}/{2}", name, (port++).ToString(), appUri)); + result.Add(Utils.Format("opc.https://{0}:{1}/{2}", name, (port++).ToString(CultureInfo.InvariantCulture), appUri)); } } return result; diff --git a/Tests/Opc.Ua.Gds.Tests/PushTest.cs b/Tests/Opc.Ua.Gds.Tests/PushTest.cs index 3858c9b25..8bfa568cf 100644 --- a/Tests/Opc.Ua.Gds.Tests/PushTest.cs +++ b/Tests/Opc.Ua.Gds.Tests/PushTest.cs @@ -797,17 +797,13 @@ private async Task AddTrustListToStore(SecurityConfiguration config, Trust var storeCrls = await store.EnumerateCRLs().ConfigureAwait(false); foreach (var crl in storeCrls) { - if (!updatedCrls.Contains(crl)) + if (!updatedCrls.Remove(crl)) { if (!await store.DeleteCRL(crl).ConfigureAwait(false)) { result = false; } } - else - { - updatedCrls.Remove(crl); - } } foreach (var crl in updatedCrls) { diff --git a/Tests/Opc.Ua.PubSub.Tests/Configuration/UaPubSubApplicationTests.cs b/Tests/Opc.Ua.PubSub.Tests/Configuration/UaPubSubApplicationTests.cs index 46394057d..a9da353ed 100644 --- a/Tests/Opc.Ua.PubSub.Tests/Configuration/UaPubSubApplicationTests.cs +++ b/Tests/Opc.Ua.PubSub.Tests/Configuration/UaPubSubApplicationTests.cs @@ -52,7 +52,7 @@ public void MyTestInitialize() [Test(Description = "Validate Create call with null path")] public void ValidateUaPubSubApplicationCreateNullFilePath() { - Assert.Throws(() => UaPubSubApplication.Create((string)null), "Calling Create with null parameter shall throw error"); + Assert.Throws(() => UaPubSubApplication.Create((string)null), "Calling Create with null parameter shall throw error"); } [Test(Description = "Validate Create call with null PubSubConfigurationDataType")] diff --git a/Tests/Opc.Ua.PubSub.Tests/Encoding/MqttJsonNetworkMessageTests.cs b/Tests/Opc.Ua.PubSub.Tests/Encoding/MqttJsonNetworkMessageTests.cs index 42384bb4e..5349713bc 100644 --- a/Tests/Opc.Ua.PubSub.Tests/Encoding/MqttJsonNetworkMessageTests.cs +++ b/Tests/Opc.Ua.PubSub.Tests/Encoding/MqttJsonNetworkMessageTests.cs @@ -30,6 +30,7 @@ using System; using System.Collections.Generic; using System.ComponentModel; +using System.Globalization; using System.IO; using System.Linq; using System.Reflection; @@ -1656,14 +1657,14 @@ private MetaDataFailOptions VerifyDataSetMetaDataEncoding(JsonNetworkMessage jso Assert.IsNotNull(fieldMetaData, "DataSetMetaData.Field - Name: '{0}' read by json decoder not found into decoded DataSetMetaData.Fields collection.", jsonFieldMetaData.Name); Assert.IsTrue(Utils.IsEqual(jsonFieldMetaData, fieldMetaData), "FieldMetaData found in decoded collection is not identical with original one. Encoded: {0} Decoded: {1}", - string.Format("Name: {0}, Description: {1}, DataSetFieldId: {2}, BuiltInType: {3}, DataType: {4}, TypeId: {5}", + Utils.Format("Name: {0}, Description: {1}, DataSetFieldId: {2}, BuiltInType: {3}, DataType: {4}, TypeId: {5}", jsonFieldMetaData.Name, jsonFieldMetaData.Description, jsonFieldMetaData.DataSetFieldId, jsonFieldMetaData.BuiltInType, jsonFieldMetaData.DataType, jsonFieldMetaData.TypeId), - string.Format("Name: {0}, Description: {1}, DataSetFieldId: {2}, BuiltInType: {3}, DataType: {4}, TypeId: {5}", + Utils.Format("Name: {0}, Description: {1}, DataSetFieldId: {2}, BuiltInType: {3}, DataType: {4}, TypeId: {5}", fieldMetaData.Name, fieldMetaData.Description, fieldMetaData.DataSetFieldId, @@ -1683,8 +1684,8 @@ private MetaDataFailOptions VerifyDataSetMetaDataEncoding(JsonNetworkMessage jso return MetaDataFailOptions.MetaData_ConfigurationVersion; } Assert.IsTrue(Utils.IsEqual(jsonNetworkMessage.DataSetMetaData.ConfigurationVersion, dataSetMetaData.ConfigurationVersion), "DataSetMetaData.ConfigurationVersion was not decoded correctly, Encoded: {0} Decoded: {1}", - string.Format("MajorVersion: {0}, MinorVersion: {1}", jsonNetworkMessage.DataSetMetaData.ConfigurationVersion.MajorVersion, jsonNetworkMessage.DataSetMetaData.ConfigurationVersion.MinorVersion), - string.Format("MajorVersion: {0}, MinorVersion: {1}", dataSetMetaData.ConfigurationVersion.MajorVersion, dataSetMetaData.ConfigurationVersion.MinorVersion)); + Utils.Format("MajorVersion: {0}, MinorVersion: {1}", jsonNetworkMessage.DataSetMetaData.ConfigurationVersion.MajorVersion, jsonNetworkMessage.DataSetMetaData.ConfigurationVersion.MinorVersion), + Utils.Format("MajorVersion: {0}, MinorVersion: {1}", dataSetMetaData.ConfigurationVersion.MajorVersion, dataSetMetaData.ConfigurationVersion.MinorVersion)); #endregion @@ -1937,7 +1938,7 @@ private DataSetMessageFailOptions VerifyDataSetMessagesEncoding(JsonNetworkMessa Convert.ToUInt16(ServiceMessageContext.GlobalContext.NamespaceUris.GetIndex(((ExpandedNodeId)decodedFieldValue).NamespaceUri)); StringBuilder stringBuilder = new StringBuilder(); - ExpandedNodeId.Format(stringBuilder, expandedNodeId.Identifier, expandedNodeId.IdType, namespaceIndex, string.Empty, expandedNodeId.ServerIndex); + ExpandedNodeId.Format(CultureInfo.InvariantCulture, stringBuilder, expandedNodeId.Identifier, expandedNodeId.IdType, namespaceIndex, string.Empty, expandedNodeId.ServerIndex); decodedFieldValue = new ExpandedNodeId(stringBuilder.ToString()); } // by convention array decoders always return the Array type @@ -2014,7 +2015,7 @@ private DataSetMessageFailOptions VerifyDataSetMessagesEncoding(JsonNetworkMessa Convert.ToUInt16(ServiceMessageContext.GlobalContext.NamespaceUris.GetIndex(((ExpandedNodeId)dataValue.Value).NamespaceUri)); StringBuilder stringBuilder = new StringBuilder(); - ExpandedNodeId.Format(stringBuilder, expandedNodeId.Identifier, expandedNodeId.IdType, namespaceIndex, string.Empty, expandedNodeId.ServerIndex); + ExpandedNodeId.Format(CultureInfo.InvariantCulture, stringBuilder, expandedNodeId.Identifier, expandedNodeId.IdType, namespaceIndex, string.Empty, expandedNodeId.ServerIndex); dataValue.Value = new ExpandedNodeId(stringBuilder.ToString()); } Assert.IsTrue(Utils.IsEqual(field.Value.Value, dataValue.Value), @@ -2048,8 +2049,8 @@ private DataSetMessageFailOptions VerifyDataSetMessagesEncoding(JsonNetworkMessa { ConfigurationVersionDataType configurationVersion = jsonDecoder.ReadEncodeable(DataSetMessageMetaDataVersion, typeof(ConfigurationVersionDataType)) as ConfigurationVersionDataType; Assert.IsTrue(Utils.IsEqual(jsonDataSetMessage.MetaDataVersion, configurationVersion), "jsonDataSetMessage.MetaDataVersion was not decoded correctly, Encoded: {0} Decoded: {1}", - string.Format("MajorVersion: {0}, MinorVersion: {1}", jsonDataSetMessage.MetaDataVersion.MajorVersion, jsonDataSetMessage.MetaDataVersion.MinorVersion), - string.Format("MajorVersion: {0}, MinorVersion: {1}", configurationVersion?.MajorVersion, configurationVersion?.MinorVersion)); + Utils.Format("MajorVersion: {0}, MinorVersion: {1}", jsonDataSetMessage.MetaDataVersion.MajorVersion, jsonDataSetMessage.MetaDataVersion.MinorVersion), + Utils.Format("MajorVersion: {0}, MinorVersion: {1}", configurationVersion?.MajorVersion, configurationVersion?.MinorVersion)); } if (jsonDecoder.ReadField(DataSetMessageTimestamp, out token)) diff --git a/Tests/Opc.Ua.PubSub.Tests/Encoding/UadpNetworkMessageTests.cs b/Tests/Opc.Ua.PubSub.Tests/Encoding/UadpNetworkMessageTests.cs index 364869e3c..f982a88ca 100644 --- a/Tests/Opc.Ua.PubSub.Tests/Encoding/UadpNetworkMessageTests.cs +++ b/Tests/Opc.Ua.PubSub.Tests/Encoding/UadpNetworkMessageTests.cs @@ -494,7 +494,7 @@ private void LoadData() for (uint index = 0; index < 100; index++) { DataValue value = new DataValue(new Variant(index)); - m_publisherApplication.DataStore.WritePublishedDataItem(new NodeId(string.Format("Mass_{0}", index), NamespaceIndexMassTest), + m_publisherApplication.DataStore.WritePublishedDataItem(new NodeId(Utils.Format("Mass_{0}", index), NamespaceIndexMassTest), Attributes.Value, value); } #endregion diff --git a/Tests/Opc.Ua.PubSub.Tests/Transport/UdpClientCreatorTests.cs b/Tests/Opc.Ua.PubSub.Tests/Transport/UdpClientCreatorTests.cs index 827df9cdb..140e53315 100644 --- a/Tests/Opc.Ua.PubSub.Tests/Transport/UdpClientCreatorTests.cs +++ b/Tests/Opc.Ua.PubSub.Tests/Transport/UdpClientCreatorTests.cs @@ -42,7 +42,7 @@ namespace Opc.Ua.PubSub.Tests.Transport public partial class UdpClientCreatorTests { private string m_publisherConfigurationFileName = Path.Combine("Configuration", "PublisherConfiguration.xml"); - private string m_urlScheme = string.Format("{0}://", Utils.UriSchemeOpcUdp); + private string m_urlScheme = Utils.Format("{0}://", Utils.UriSchemeOpcUdp); // generic well known address private string m_urlHostName = "192.168.0.1"; @@ -208,7 +208,7 @@ private string ReplaceLastIpByte(string ipAddress, string lastIpByte) byte[] ipAddressBytes = validIp.GetAddressBytes(); for (int pos = 0; pos < ipAddressBytes.Length - 1; pos++) { - newIPAddress += string.Format("{0}.", ipAddressBytes[pos]); + newIPAddress += Utils.Format("{0}.", ipAddressBytes[pos]); } newIPAddress += lastIpByte; return newIPAddress; diff --git a/Tests/Opc.Ua.PubSub.Tests/Transport/UdpPubSubConnectionTests.Publisher.cs b/Tests/Opc.Ua.PubSub.Tests/Transport/UdpPubSubConnectionTests.Publisher.cs index 85184fbf2..4e29ccd76 100644 --- a/Tests/Opc.Ua.PubSub.Tests/Transport/UdpPubSubConnectionTests.Publisher.cs +++ b/Tests/Opc.Ua.PubSub.Tests/Transport/UdpPubSubConnectionTests.Publisher.cs @@ -64,7 +64,7 @@ public void ValidateUdpPubSubConnectionNetworkMessagePublishUnicast() Assert.IsNotNull(unicastIPAddress, "unicastIPAddress is null"); NetworkAddressUrlDataType publisherAddress = new NetworkAddressUrlDataType(); - publisherAddress.Url = string.Format(kUdpUrlFormat, Utils.UriSchemeOpcUdp, unicastIPAddress.ToString()); + publisherAddress.Url = Utils.Format(kUdpUrlFormat, Utils.UriSchemeOpcUdp, unicastIPAddress.ToString()); publisherConfiguration.Connections.First().Address = new ExtensionObject(publisherAddress); //create publisher UaPubSubApplication with changed configuration settings @@ -141,7 +141,7 @@ public void ValidateUdpPubSubConnectionNetworkMessagePublishBroadcast() Assert.IsNotNull(broadcastIPAddress, "broadcastIPAddress is null"); NetworkAddressUrlDataType publisherAddress = new NetworkAddressUrlDataType(); - publisherAddress.Url = string.Format(kUdpUrlFormat, Utils.UriSchemeOpcUdp, broadcastIPAddress.ToString()); + publisherAddress.Url = Utils.Format(kUdpUrlFormat, Utils.UriSchemeOpcUdp, broadcastIPAddress.ToString()); publisherConfiguration.Connections.First().Address = new ExtensionObject(publisherAddress); //create publisher UaPubSubApplication with changed configuration settings @@ -216,7 +216,7 @@ public void ValidateUdpPubSubConnectionNetworkMessagePublishMulticast() Assert.IsNotNull(multicastIPAddress, "multicastIPAddress is null"); NetworkAddressUrlDataType publisherAddress = new NetworkAddressUrlDataType(); - publisherAddress.Url = string.Format(kUdpUrlFormat, Utils.UriSchemeOpcUdp, multicastIPAddress.ToString()); + publisherAddress.Url = Utils.Format(kUdpUrlFormat, Utils.UriSchemeOpcUdp, multicastIPAddress.ToString()); publisherConfiguration.Connections.First().Address = new ExtensionObject(publisherAddress); //create publisher UaPubSubApplication with changed configuration settings @@ -292,7 +292,7 @@ public void ValidateUdpPubSubConnectionNetworkMessageDiscoveryPublish_DataSetMet Assert.IsNotNull(multicastIPAddress, "multicastIPAddress is null"); NetworkAddressUrlDataType publisherAddress = new NetworkAddressUrlDataType(); - publisherAddress.Url = string.Format(kUdpUrlFormat, Utils.UriSchemeOpcUdp, multicastIPAddress.ToString()); + publisherAddress.Url = Utils.Format(kUdpUrlFormat, Utils.UriSchemeOpcUdp, multicastIPAddress.ToString()); publisherConfiguration.Connections[0].Address = new ExtensionObject(publisherAddress); //create publisher UaPubSubApplication with changed configuration settings @@ -374,7 +374,7 @@ public void ValidateUdpPubSubConnectionNetworkMessageDiscoveryPublish_DataSetWri Assert.IsNotNull(multicastIPAddress, "multicastIPAddress is null"); NetworkAddressUrlDataType publisherAddress = new NetworkAddressUrlDataType(); - publisherAddress.Url = string.Format(kUdpUrlFormat, Utils.UriSchemeOpcUdp, multicastIPAddress.ToString()); + publisherAddress.Url = Utils.Format(kUdpUrlFormat, Utils.UriSchemeOpcUdp, multicastIPAddress.ToString()); publisherConfiguration.Connections[0].Address = new ExtensionObject(publisherAddress); //create publisher UaPubSubApplication with changed configuration settings @@ -449,7 +449,7 @@ public void ValidateUdpPubSubConnectionNetworkMessageDiscoveryPublish_PublisherE Assert.IsNotNull(multicastIPAddress, "multicastIPAddress is null"); NetworkAddressUrlDataType publisherAddress = new NetworkAddressUrlDataType(); - publisherAddress.Url = string.Format(kUdpUrlFormat, Utils.UriSchemeOpcUdp, multicastIPAddress.ToString()); + publisherAddress.Url = Utils.Format(kUdpUrlFormat, Utils.UriSchemeOpcUdp, multicastIPAddress.ToString()); publisherConfiguration.Connections[0].Address = new ExtensionObject(publisherAddress); //create publisher UaPubSubApplication with changed configuration settings @@ -543,7 +543,7 @@ private void OnReceive(IAsyncResult result) } catch (Exception ex) { - Assert.Warn(string.Format("OnReceive() failed due to the following reason: {0}", ex.Message)); + Assert.Warn(Utils.Format("OnReceive() failed due to the following reason: {0}", ex.Message)); } } diff --git a/Tests/Opc.Ua.PubSub.Tests/Transport/UdpPubSubConnectionTests.Subscriber.cs b/Tests/Opc.Ua.PubSub.Tests/Transport/UdpPubSubConnectionTests.Subscriber.cs index a9fb154d1..b04bf2895 100644 --- a/Tests/Opc.Ua.PubSub.Tests/Transport/UdpPubSubConnectionTests.Subscriber.cs +++ b/Tests/Opc.Ua.PubSub.Tests/Transport/UdpPubSubConnectionTests.Subscriber.cs @@ -63,7 +63,7 @@ public void ValidateUdpPubSubConnectionNetworkMessageReceiveFromUnicast() Assert.IsNotNull(subscriberConfiguration, "subscriberConfiguration is null"); NetworkAddressUrlDataType subscriberAddress = new NetworkAddressUrlDataType(); - subscriberAddress.Url = string.Format(kUdpUrlFormat, Utils.UriSchemeOpcUdp, localhost.Address.ToString()); + subscriberAddress.Url = Utils.Format(kUdpUrlFormat, Utils.UriSchemeOpcUdp, localhost.Address.ToString()); subscriberConfiguration.Connections.First().Address = new ExtensionObject(subscriberAddress); UaPubSubApplication subscriberApplication = UaPubSubApplication.Create(subscriberConfiguration); Assert.IsNotNull(subscriberApplication, "subscriberApplication is null"); @@ -78,7 +78,7 @@ public void ValidateUdpPubSubConnectionNetworkMessageReceiveFromUnicast() Assert.IsNotNull(publisherConfiguration, "publisherConfiguration is null"); NetworkAddressUrlDataType publisherAddress = new NetworkAddressUrlDataType(); - publisherAddress.Url = string.Format(kUdpUrlFormat, Utils.UriSchemeOpcUdp, localhost.Address.ToString()); + publisherAddress.Url = Utils.Format(kUdpUrlFormat, Utils.UriSchemeOpcUdp, localhost.Address.ToString()); publisherConfiguration.Connections.First().Address = new ExtensionObject(publisherAddress); UaPubSubApplication publisherApplication = UaPubSubApplication.Create(publisherConfiguration); Assert.IsNotNull(publisherApplication, "publisherApplication is null"); @@ -130,7 +130,7 @@ public void ValidateUdpPubSubConnectionNetworkMessageReceiveFromBroadcast() Assert.IsNotNull(subscriberConfiguration, "subscriberConfiguration is null"); NetworkAddressUrlDataType subscriberAddress = new NetworkAddressUrlDataType(); - subscriberAddress.Url = string.Format(kUdpUrlFormat, Utils.UriSchemeOpcUdp, localhost.Address.ToString()); + subscriberAddress.Url = Utils.Format(kUdpUrlFormat, Utils.UriSchemeOpcUdp, localhost.Address.ToString()); subscriberConfiguration.Connections.First().Address = new ExtensionObject(subscriberAddress); UaPubSubApplication subscriberApplication = UaPubSubApplication.Create(subscriberConfiguration); Assert.IsNotNull(subscriberApplication, "subscriberApplication is null"); @@ -148,7 +148,7 @@ public void ValidateUdpPubSubConnectionNetworkMessageReceiveFromBroadcast() Assert.IsNotNull(broadcastIPAddress, "broadcastIPAddress is null"); NetworkAddressUrlDataType publisherAddress = new NetworkAddressUrlDataType(); - publisherAddress.Url = string.Format(kUdpUrlFormat, Utils.UriSchemeOpcUdp, broadcastIPAddress.ToString()); + publisherAddress.Url = Utils.Format(kUdpUrlFormat, Utils.UriSchemeOpcUdp, broadcastIPAddress.ToString()); publisherConfiguration.Connections.First().Address = new ExtensionObject(publisherAddress); UaPubSubApplication publisherApplication = UaPubSubApplication.Create(publisherConfiguration); Assert.IsNotNull(publisherApplication, "publisherApplication is null"); @@ -201,7 +201,7 @@ public void ValidateUdpPubSubConnectionNetworkMessageReceiveFromMulticast() Assert.IsNotNull(subscriberConfiguration, "subscriberConfiguration is null"); NetworkAddressUrlDataType subscriberAddress = new NetworkAddressUrlDataType(); - subscriberAddress.Url = string.Format(kUdpUrlFormat, Utils.UriSchemeOpcUdp, multicastIPAddress.ToString()); + subscriberAddress.Url = Utils.Format(kUdpUrlFormat, Utils.UriSchemeOpcUdp, multicastIPAddress.ToString()); subscriberConfiguration.Connections[0].Address = new ExtensionObject(subscriberAddress); UaPubSubApplication subscriberApplication = UaPubSubApplication.Create(subscriberConfiguration); Assert.IsNotNull(subscriberApplication, "subscriberApplication is null"); @@ -216,7 +216,7 @@ public void ValidateUdpPubSubConnectionNetworkMessageReceiveFromMulticast() Assert.IsNotNull(publisherConfiguration, "publisherConfiguration is null"); NetworkAddressUrlDataType publisherAddress = new NetworkAddressUrlDataType(); - publisherAddress.Url = string.Format(kUdpUrlFormat, Utils.UriSchemeOpcUdp, multicastIPAddress.ToString()); + publisherAddress.Url = Utils.Format(kUdpUrlFormat, Utils.UriSchemeOpcUdp, multicastIPAddress.ToString()); publisherConfiguration.Connections.First().Address = new ExtensionObject(publisherAddress); UaPubSubApplication publisherApplication = UaPubSubApplication.Create(publisherConfiguration); Assert.IsNotNull(publisherApplication, "publisherApplication is null"); @@ -272,7 +272,7 @@ public void ValidateUdpPubSubConnectionNetworkMessageReceiveFromDiscoveryRespons //set address and create subscriber NetworkAddressUrlDataType subscriberAddress = new NetworkAddressUrlDataType(); - subscriberAddress.Url = string.Format(kUdpUrlFormat, Utils.UriSchemeOpcUdp, multicastIPAddress.ToString()); + subscriberAddress.Url = Utils.Format(kUdpUrlFormat, Utils.UriSchemeOpcUdp, multicastIPAddress.ToString()); subscriberConfiguration.Connections[0].Address = new ExtensionObject(subscriberAddress); UaPubSubApplication subscriberApplication = UaPubSubApplication.Create(subscriberConfiguration); Assert.IsNotNull(subscriberApplication, "subscriberApplication is null"); @@ -291,7 +291,7 @@ public void ValidateUdpPubSubConnectionNetworkMessageReceiveFromDiscoveryRespons //set address and create publisher NetworkAddressUrlDataType publisherAddress = new NetworkAddressUrlDataType(); - publisherAddress.Url = string.Format(kUdpUrlFormat, Utils.UriSchemeOpcUdp, multicastIPAddress.ToString()); + publisherAddress.Url = Utils.Format(kUdpUrlFormat, Utils.UriSchemeOpcUdp, multicastIPAddress.ToString()); publisherConfiguration.Connections.First().Address = new ExtensionObject(publisherAddress); UaPubSubApplication publisherApplication = UaPubSubApplication.Create(publisherConfiguration); Assert.IsNotNull(publisherApplication, "publisherApplication is null"); @@ -363,7 +363,7 @@ public void ValidateUadpPubSubConnectionNetworkMessageReceiveFromDiscoveryRespon //set address and create subscriber NetworkAddressUrlDataType subscriberAddress = new NetworkAddressUrlDataType(); - subscriberAddress.Url = string.Format(kUdpUrlFormat, Utils.UriSchemeOpcUdp, multicastIPAddress.ToString()); + subscriberAddress.Url = Utils.Format(kUdpUrlFormat, Utils.UriSchemeOpcUdp, multicastIPAddress.ToString()); subscriberConfiguration.Connections[0].Address = new ExtensionObject(subscriberAddress); UaPubSubApplication subscriberApplication = UaPubSubApplication.Create(subscriberConfiguration); Assert.IsNotNull(subscriberApplication, "subscriberApplication is null"); @@ -381,7 +381,7 @@ public void ValidateUadpPubSubConnectionNetworkMessageReceiveFromDiscoveryRespon Assert.IsNotNull(publisherConfiguration, "publisherConfiguration is null"); NetworkAddressUrlDataType publisherAddress = new NetworkAddressUrlDataType(); - publisherAddress.Url = string.Format(kUdpUrlFormat, Utils.UriSchemeOpcUdp, multicastIPAddress.ToString()); + publisherAddress.Url = Utils.Format(kUdpUrlFormat, Utils.UriSchemeOpcUdp, multicastIPAddress.ToString()); publisherConfiguration.Connections.First().Address = new ExtensionObject(publisherAddress); UaPubSubApplication publisherApplication = UaPubSubApplication.Create(publisherConfiguration); Assert.IsNotNull(publisherApplication, "publisherApplication is null"); @@ -440,7 +440,7 @@ public void ValidateUdpPubSubConnectionNetworkMessageReceiveFromDiscoveryRespons Assert.IsNotNull(subscriberConfiguration, "subscriberConfiguration is null"); NetworkAddressUrlDataType subscriberAddress = new NetworkAddressUrlDataType(); - subscriberAddress.Url = string.Format(kUdpUrlFormat, Utils.UriSchemeOpcUdp, multicastIPAddress.ToString()); + subscriberAddress.Url = Utils.Format(kUdpUrlFormat, Utils.UriSchemeOpcUdp, multicastIPAddress.ToString()); subscriberConfiguration.Connections[0].Address = new ExtensionObject(subscriberAddress); UaPubSubApplication subscriberApplication = UaPubSubApplication.Create(subscriberConfiguration); Assert.IsNotNull(subscriberApplication, "subscriberApplication is null"); @@ -455,7 +455,7 @@ public void ValidateUdpPubSubConnectionNetworkMessageReceiveFromDiscoveryRespons Assert.IsNotNull(publisherConfiguration, "publisherConfiguration is null"); NetworkAddressUrlDataType publisherAddress = new NetworkAddressUrlDataType(); - publisherAddress.Url = string.Format(kUdpUrlFormat, Utils.UriSchemeOpcUdp, multicastIPAddress.ToString()); + publisherAddress.Url = Utils.Format(kUdpUrlFormat, Utils.UriSchemeOpcUdp, multicastIPAddress.ToString()); publisherConfiguration.Connections.First().Address = new ExtensionObject(publisherAddress); UaPubSubApplication publisherApplication = UaPubSubApplication.Create(publisherConfiguration); Assert.IsNotNull(publisherApplication, "publisherApplication is null"); @@ -515,7 +515,7 @@ public void ValidateUdpPubSubConnectionNetworkMessageReceiveFromDiscoveryRespons Assert.IsNotNull(subscriberConfiguration, "subscriberConfiguration is null"); NetworkAddressUrlDataType subscriberAddress = new NetworkAddressUrlDataType(); - subscriberAddress.Url = string.Format(kUdpUrlFormat, Utils.UriSchemeOpcUdp, multicastIPAddress.ToString()); + subscriberAddress.Url = Utils.Format(kUdpUrlFormat, Utils.UriSchemeOpcUdp, multicastIPAddress.ToString()); subscriberConfiguration.Connections[0].Address = new ExtensionObject(subscriberAddress); UaPubSubApplication subscriberApplication = UaPubSubApplication.Create(subscriberConfiguration); Assert.IsNotNull(subscriberApplication, "subscriberApplication is null"); @@ -530,7 +530,7 @@ public void ValidateUdpPubSubConnectionNetworkMessageReceiveFromDiscoveryRespons Assert.IsNotNull(publisherConfiguration, "publisherConfiguration is null"); NetworkAddressUrlDataType publisherAddress = new NetworkAddressUrlDataType(); - publisherAddress.Url = string.Format(kUdpUrlFormat, Utils.UriSchemeOpcUdp, multicastIPAddress.ToString()); + publisherAddress.Url = Utils.Format(kUdpUrlFormat, Utils.UriSchemeOpcUdp, multicastIPAddress.ToString()); publisherConfiguration.Connections.First().Address = new ExtensionObject(publisherAddress); UaPubSubApplication publisherApplication = UaPubSubApplication.Create(publisherConfiguration); Assert.IsNotNull(publisherApplication, "publisherApplication is null"); @@ -590,7 +590,7 @@ public void ValidateUdpPubSubConnectionNetworkMessageReceiveFromDiscoveryRespons Assert.IsNotNull(subscriberConfiguration, "subscriberConfiguration is null"); NetworkAddressUrlDataType subscriberAddress = new NetworkAddressUrlDataType(); - subscriberAddress.Url = string.Format(kUdpUrlFormat, Utils.UriSchemeOpcUdp, multicastIPAddress.ToString()); + subscriberAddress.Url = Utils.Format(kUdpUrlFormat, Utils.UriSchemeOpcUdp, multicastIPAddress.ToString()); subscriberConfiguration.Connections[0].Address = new ExtensionObject(subscriberAddress); UaPubSubApplication subscriberApplication = UaPubSubApplication.Create(subscriberConfiguration); Assert.IsNotNull(subscriberApplication, "subscriberApplication is null"); @@ -605,7 +605,7 @@ public void ValidateUdpPubSubConnectionNetworkMessageReceiveFromDiscoveryRespons Assert.IsNotNull(publisherConfiguration, "publisherConfiguration is null"); NetworkAddressUrlDataType publisherAddress = new NetworkAddressUrlDataType(); - publisherAddress.Url = string.Format(kUdpUrlFormat, Utils.UriSchemeOpcUdp, multicastIPAddress.ToString()); + publisherAddress.Url = Utils.Format(kUdpUrlFormat, Utils.UriSchemeOpcUdp, multicastIPAddress.ToString()); publisherConfiguration.Connections.First().Address = new ExtensionObject(publisherAddress); UaPubSubApplication publisherApplication = UaPubSubApplication.Create(publisherConfiguration); Assert.IsNotNull(publisherApplication, "publisherApplication is null"); @@ -816,7 +816,7 @@ private byte[] BuildNetworkMessages(UdpPubSubConnection publisherConnection, Udp catch (Exception ex) { Assert.Fail(ex.Message); - throw ex; + throw; } } @@ -847,7 +847,7 @@ private byte[] PreparePublisherEndpointsMessage(UdpPubSubConnection publisherCon catch (Exception ex) { Assert.Fail(ex.Message); - throw ex; + throw; } } @@ -920,7 +920,7 @@ private byte[] PrepareDataSetWriterConfigurationMessage(UdpPubSubConnection publ catch (Exception ex) { Assert.Fail(ex.Message); - throw ex; + throw; } } diff --git a/Tests/Opc.Ua.Security.Certificates.Tests/CRLTests.cs b/Tests/Opc.Ua.Security.Certificates.Tests/CRLTests.cs index efb16d534..7d1a5660b 100644 --- a/Tests/Opc.Ua.Security.Certificates.Tests/CRLTests.cs +++ b/Tests/Opc.Ua.Security.Certificates.Tests/CRLTests.cs @@ -30,6 +30,7 @@ using System; using System.Collections.Generic; +using System.Globalization; using System.IO; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; @@ -258,7 +259,7 @@ private string WriteCRL(X509CRL x509Crl) stringBuilder.AppendLine("RevokedCertificates:"); foreach (var revokedCert in x509Crl.RevokedCertificates) { - stringBuilder.AppendFormat("{0:20}", revokedCert.SerialNumber).Append(", ").Append(revokedCert.RevocationDate).Append(", "); + stringBuilder.AppendFormat(CultureInfo.InvariantCulture, "{0:20}", revokedCert.SerialNumber).Append(", ").Append(revokedCert.RevocationDate).Append(", "); foreach (var entryExt in revokedCert.CrlEntryExtensions) { stringBuilder.Append(entryExt.Format(false)).Append(' '); diff --git a/Tests/Opc.Ua.Security.Certificates.Tests/CertificateTestUtils.cs b/Tests/Opc.Ua.Security.Certificates.Tests/CertificateTestUtils.cs index 067531414..2f2cc4a85 100644 --- a/Tests/Opc.Ua.Security.Certificates.Tests/CertificateTestUtils.cs +++ b/Tests/Opc.Ua.Security.Certificates.Tests/CertificateTestUtils.cs @@ -30,6 +30,7 @@ using System; using System.Collections.Generic; +using System.Globalization; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.Text; @@ -221,7 +222,7 @@ public static string WriteCRL(X509CRL x509Crl) stringBuilder.AppendLine("RevokedCertificates:"); foreach (var revokedCert in x509Crl.RevokedCertificates) { - stringBuilder.AppendFormat("{0:20}", revokedCert.SerialNumber).Append(", ").Append(revokedCert.RevocationDate).Append(", "); + stringBuilder.AppendFormat(CultureInfo.InvariantCulture, "{0:20}", revokedCert.SerialNumber).Append(", ").Append(revokedCert.RevocationDate).Append(", "); foreach (var entryExt in revokedCert.CrlEntryExtensions) { stringBuilder.Append(entryExt.Format(false)).Append(' '); diff --git a/Tests/Opc.Ua.Server.Tests/NUnitTestLogger.cs b/Tests/Opc.Ua.Server.Tests/NUnitTestLogger.cs index 96a82cbdf..8f45c39ef 100644 --- a/Tests/Opc.Ua.Server.Tests/NUnitTestLogger.cs +++ b/Tests/Opc.Ua.Server.Tests/NUnitTestLogger.cs @@ -28,6 +28,7 @@ * ======================================================================*/ using System; +using System.Globalization; using System.IO; using System.Text; using System.Threading; @@ -87,7 +88,7 @@ public void Log(LogLevel logLevel, EventId eventId, TState state, Except try { var sb = new StringBuilder(); - sb.AppendFormat("{0:yy-MM-dd HH:mm:ss.fff}: ", DateTime.UtcNow); + sb.AppendFormat(CultureInfo.InvariantCulture, "{0:yy-MM-dd HH:mm:ss.fff}: ", DateTime.UtcNow); sb.Append(formatter(state, exception)); var logEntry = sb.ToString(); diff --git a/Tests/Opc.Ua.Server.Tests/NUnitTraceLogger.cs b/Tests/Opc.Ua.Server.Tests/NUnitTraceLogger.cs index aa1c78f8d..ac9a1888b 100644 --- a/Tests/Opc.Ua.Server.Tests/NUnitTraceLogger.cs +++ b/Tests/Opc.Ua.Server.Tests/NUnitTraceLogger.cs @@ -28,6 +28,7 @@ * ======================================================================*/ using System; +using System.Globalization; using System.IO; namespace Opc.Ua.Server.Tests @@ -85,7 +86,7 @@ public void TraceEventHandler(object sender, TraceEventArgs e) { m_writer.WriteLine(e.Exception); } - m_writer.WriteLine(string.Format(e.Format, e.Arguments ?? Array.Empty())); + m_writer.WriteLine(string.Format(CultureInfo.InvariantCulture, e.Format, e.Arguments ?? Array.Empty())); } } } diff --git a/nuget/Opc.Ua.Symbols.nuspec b/nuget/Opc.Ua.Symbols.nuspec index ab15da629..48ed38e3c 100644 --- a/nuget/Opc.Ua.Symbols.nuspec +++ b/nuget/Opc.Ua.Symbols.nuspec @@ -2,7 +2,7 @@ OPCFoundation.NetStandard.Opc.Ua.Symbols - 1.04.360.0 + 1.04.372.0 OPC UA .Net Standard Library Symbols This package contains the OPC UA reference implementation debug version and is targeting the .NET Standard Library. OPC Foundation diff --git a/nuget/Opc.Ua.nuspec b/nuget/Opc.Ua.nuspec index 7d565ad6b..03a35327e 100644 --- a/nuget/Opc.Ua.nuspec +++ b/nuget/Opc.Ua.nuspec @@ -2,7 +2,7 @@ OPCFoundation.NetStandard.Opc.Ua - 1.04.360.0 + 1.04.372.0 OPC UA .NET Standard Library This package contains the OPC UA reference implementation and is targeting the .NET Standard Library. OPC Foundation