Skip to content

Commit

Permalink
Fix warnings, no functional changes. Improve globalization. (#2445)
Browse files Browse the repository at this point in the history
Fix warnings regarding localization, CLS compliance, performance. No functional changes.

Many but not all adressed:
CA1859
CA1868
CA1305
CA1310
CA1861

- based on the discussion, use IFormatProvider where appropriate in ToString
  • Loading branch information
mregen committed Feb 14, 2024
1 parent f8f1571 commit 2b9d8f9
Show file tree
Hide file tree
Showing 102 changed files with 688 additions and 639 deletions.
6 changes: 6 additions & 0 deletions .editorconfig
Expand Up @@ -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
Expand Down
9 changes: 7 additions & 2 deletions Applications/ConsoleReferenceServer/ConsoleUtils.cs
Expand Up @@ -29,6 +29,7 @@

using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
Expand Down Expand Up @@ -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;
Expand Down
Expand Up @@ -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;
Expand Down Expand Up @@ -233,7 +234,7 @@ public override void CreateAddressSpace(IDictionary<NodeId, IList<IReference>> 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()
Expand Down Expand Up @@ -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());
Expand Down Expand Up @@ -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);
}
Expand Down Expand Up @@ -1839,9 +1840,9 @@ private AnalogItemState CreateAnalogItemVariable(NodeState parent, string path,
/// <summary>
/// Creates a new variable.
/// </summary>
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);
Expand Down Expand Up @@ -1886,7 +1887,7 @@ private DataItemState CreateTwoStateDiscreteItemVariable(NodeState parent, strin
/// <summary>
/// Creates a new variable.
/// </summary>
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);

Expand Down Expand Up @@ -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)
{
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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))
{
Expand Down Expand Up @@ -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());
Expand Down Expand Up @@ -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());
Expand All @@ -2307,7 +2308,7 @@ private BaseDataVariableState[] CreateDynamicVariables(NodeState parent, string
/// <summary>
/// Creates a new variable type.
/// </summary>
private BaseVariableTypeState CreateVariableType(NodeState parent, IDictionary<NodeId, IList<IReference>> externalReferences, string path, string name, BuiltInType dataType, int valueRank)
private BaseDataVariableTypeState CreateVariableType(NodeState parent, IDictionary<NodeId, IList<IReference>> externalReferences, string path, string name, BuiltInType dataType, int valueRank)
{
BaseDataVariableTypeState type = new BaseDataVariableTypeState();

Expand Down
Expand Up @@ -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
Expand Down
Expand Up @@ -29,6 +29,7 @@

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.Serialization;
Expand Down Expand Up @@ -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);
}
Expand Down
4 changes: 2 additions & 2 deletions Libraries/Opc.Ua.Client.ComplexTypes/Types/BaseComplexType.cs
Expand Up @@ -200,7 +200,7 @@ public override string ToString()
/// <param name="format">(Unused). Leave this as null</param>
/// <param name="formatProvider">The provider of a mechanism for retrieving an object to control formatting.</param>
/// <returns>
/// A <see cref="System.String"/> containing the value of the current embeded instance in the specified format.
/// A <see cref="System.String"/> containing the value of the current embedded instance in the specified format.
/// </returns>
/// <exception cref="FormatException">Thrown if the <i>format</i> parameter is not null</exception>
public virtual string ToString(string format, IFormatProvider formatProvider)
Expand All @@ -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)";
Expand Down
Expand Up @@ -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)";
Expand Down
Expand Up @@ -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)";
Expand Down
2 changes: 2 additions & 0 deletions Libraries/Opc.Ua.Client/Properties/AssemblyInfo.cs
Expand Up @@ -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
Expand Down
10 changes: 5 additions & 5 deletions Libraries/Opc.Ua.Client/Session.cs
Expand Up @@ -4033,7 +4033,7 @@ protected virtual bool OnKeepAliveError(ServiceResult result)
/// <summary>
/// Prepare a list of subscriptions to delete.
/// </summary>
private bool PrepareSubscriptionsToDelete(IEnumerable<Subscription> subscriptions, IList<Subscription> subscriptionsToDelete)
private bool PrepareSubscriptionsToDelete(IEnumerable<Subscription> subscriptions, List<Subscription> subscriptionsToDelete)
{
bool removed = false;
lock (SyncRoot)
Expand Down Expand Up @@ -4061,7 +4061,7 @@ private bool PrepareSubscriptionsToDelete(IEnumerable<Subscription> subscription
IList<NodeId> nodeIdCollection,
NodeClass nodeClass,
ReadValueIdCollection attributesToRead,
IList<IDictionary<uint, DataValue>> attributesPerNodeId,
List<IDictionary<uint, DataValue>> attributesPerNodeId,
IList<Node> nodeCollection,
bool optionalAttributes)
{
Expand Down Expand Up @@ -4151,7 +4151,7 @@ private void UpdateNamespaceTable(DataValueCollection values, DiagnosticInfoColl
DataValueCollection nodeClassValues,
DiagnosticInfoCollection diagnosticInfos,
ReadValueIdCollection attributesToRead,
IList<IDictionary<uint, DataValue>> attributesPerNodeId,
List<IDictionary<uint, DataValue>> attributesPerNodeId,
IList<Node> nodeCollection,
IList<ServiceResult> errors,
bool optionalAttributes
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -4710,7 +4710,7 @@ bool optionalAttributes
/// <summary>
/// Create a dictionary of attributes to read for a nodeclass.
/// </summary>
private IDictionary<uint, DataValue> CreateAttributes(NodeClass nodeclass = NodeClass.Unspecified, bool optionalAttributes = true)
private SortedDictionary<uint, DataValue> CreateAttributes(NodeClass nodeclass = NodeClass.Unspecified, bool optionalAttributes = true)
{
// Attributes to read for all types of nodes
var attributes = new SortedDictionary<uint, DataValue>() {
Expand Down
6 changes: 3 additions & 3 deletions Libraries/Opc.Ua.Client/Subscription.cs
Expand Up @@ -2433,7 +2433,7 @@ private bool ValidSequentialPublishMessage(IncomingMessage message)
/// </summary>
private bool UpdateMonitoringMode(
IList<MonitoredItem> monitoredItems,
IList<ServiceResult> errors,
List<ServiceResult> errors,
StatusCodeCollection results,
DiagnosticInfoCollection diagnosticInfos,
ResponseHeader responseHeader,
Expand Down Expand Up @@ -2518,7 +2518,7 @@ private MonitoredItemCreateRequestCollection PrepareItemsToCreate(out List<Monit
/// </summary>
private void PrepareItemsToModify(
MonitoredItemModifyRequestCollection requestItems,
IList<MonitoredItem> itemsToModify)
List<MonitoredItem> itemsToModify)
{
lock (m_cache)
{
Expand Down Expand Up @@ -2589,7 +2589,7 @@ private MonitoredItemCreateRequestCollection PrepareItemsToCreate(out List<Monit
/// </summary>
private void PrepareResolveItemNodeIds(
BrowsePathCollection browsePaths,
IList<MonitoredItem> itemsToBrowse)
List<MonitoredItem> itemsToBrowse)
{
lock (m_cache)
{
Expand Down
3 changes: 2 additions & 1 deletion Libraries/Opc.Ua.Configuration/ApplicationInstance.cs
Expand Up @@ -29,6 +29,7 @@

using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
Expand Down Expand Up @@ -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);
Expand Down
44 changes: 44 additions & 0 deletions 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
1 change: 1 addition & 0 deletions Libraries/Opc.Ua.Gds.Client.Common/CertificateWrapper.cs
Expand Up @@ -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;
}

Expand Down

0 comments on commit 2b9d8f9

Please sign in to comment.