/// <summary> /// Retrieves the value for a given <paramref name="itemName"/> inside a <paramref name="groupName"/> from a <paramref name="fileName"/>. /// </summary> /// <param name="fileName">The full path to the INI-file.</param> /// <param name="groupName">The name of the group in which the setting is expected or <c>null</c> if the item is in no group.</param> /// <param name="itemName">The name of the item.</param> /// <param name="defaultValue">A default value if no value could be found.</param> /// <typeparam name="T">The type of the result.</typeparam> /// <returns>The value associated with the <paramref name="itemName"/>.</returns> /// <exception cref="FileNotFoundException">Is thrown if the file could not be found.</exception> /// <exception cref="InvalidOperationException">Is thrown in case of any other exception.</exception> public static T GetValue <T>(string fileName, string groupName, string itemName, T defaultValue = default(T)) { CheckUtil.ThrowIfNullOrEmpty(() => fileName); CheckUtil.ThrowIfNullOrEmpty(() => itemName); if (!File.Exists(fileName)) { throw new FileNotFoundException("Provided file not found.", fileName); } string[] linesInFile; try { linesInFile = File.ReadAllLines(fileName); } catch (Exception ex) { throw new InvalidOperationException("Error during read of file.", ex); } if (linesInFile == null || !linesInFile.Any()) { throw new InvalidOperationException("Could not read from file."); } var groupSearch = string.Format(CultureInfo.InvariantCulture, "[{0}]", groupName); var groupFound = !string.IsNullOrEmpty(groupName) && linesInFile.Any(line => line.Equals(groupSearch, StringComparison.OrdinalIgnoreCase)); if (!groupFound) { return(defaultValue); } var inGroup = !string.IsNullOrEmpty(groupName); var retVal = defaultValue; linesInFile.ToList().ForEach( line => { if (line.StartsWith("[")) { // check if we will start the parsing or if we stop the complete process if (inGroup) { // we where already inside the desired group return; } inGroup = line.Equals(groupSearch, StringComparison.OrdinalIgnoreCase); } else { if (!inGroup || !line.StartsWith(itemName, StringComparison.OrdinalIgnoreCase)) { return; } // this is the item we are looking for var value = line.Split('=')[1].Trim(); if (value.IsNullOrEmpty()) { return; } try { retVal = (T)Convert.ChangeType(value, typeof(T)); } catch (Exception ex) { TraceUtil.WriteTraceError(ex.Message); } } }); return(retVal); }
/// <summary> /// Tries to open a network connection to a specific port retrieving the result. /// </summary> /// <remarks> /// Stores the result of the last operation in <see cref="LastCheckResult" /> too. /// </remarks> /// <param name="host">IP-Address or host name to check for the port.</param> /// <param name="port">The port-number to check.</param> /// <param name="timeoutSeconds"> /// The timeoutSeconds in seconds to wait for a reply. Defaults to 2 because 1 second is /// mostly too short for .NET. /// </param> /// <param name="useUdp"><c>true</c> if a UDP port should be checked.</param> /// <returns>The result of the operation.</returns> public static PortState GetPortState(string host, int port, int timeoutSeconds = 2, bool useUdp = false) { var outerResult = PortState.Unknown; var tokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(timeoutSeconds)); var token = tokenSource.Token; try { // use a task to enable outer cancellation regardless of the asyncResult-timeoutSeconds which isn't working very well outerResult = Task.Run( () => { var result = PortState.Unknown; if (!useUdp) { // Use TCP var client = new TcpClient(); try { var asyncResult = client.BeginConnect(host, port, null, null); var waitHandle = asyncResult.AsyncWaitHandle; try { if (asyncResult.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(timeoutSeconds), false)) { // The result was positive if (!asyncResult.IsCompleted) { result = PortState.TimedOut; } else { result = client.Connected ? PortState.Open : PortState.Closed; } } // ensure the ending-call client.EndConnect(asyncResult); } finally { // Ensure to close the wait handle. waitHandle.Close(); } } catch (SocketException sockEx) { TraceUtil.WriteTraceError(sockEx.Message); // see https://msdn.microsoft.com/en-us/library/ms740668.aspx for a list of all states switch (sockEx.NativeErrorCode) { case 10060: result = PortState.TimedOut; break; case 10061: result = PortState.Refused; break; } } catch (Exception ex) { TraceUtil.WriteTraceError(ex.Message); } finally { // wait handle didn't came back in time client.Close(); } } else { // Use UDP var client = new UdpClient(); try { client.Connect(host, port); var asyncResult = client.BeginReceive( r => { }, null); asyncResult.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(timeoutSeconds), false); if (!asyncResult.IsCompleted) { return(PortState.TimedOut); } result = PortState.Open; } catch (SocketException sockEx) { TraceUtil.WriteTraceError(sockEx.Message); // see https://msdn.microsoft.com/en-us/library/ms740668.aspx for a list of all states switch (sockEx.NativeErrorCode) { case 10060: result = PortState.TimedOut; break; case 10061: result = PortState.Refused; break; } } catch (Exception ex) { TraceUtil.WriteTraceError(ex.Message); } finally { // wait handle didn't came back in time client.Close(); } } return(result); }, token).ContinueWith( t => { if (t.IsCanceled || token.IsCancellationRequested) { return(PortState.TimedOut); } return(t.Result); }, token).Result; } catch (AggregateException aex) { var flatten = aex.Flatten(); if (flatten.InnerException is TaskCanceledException) { outerResult = PortState.TimedOut; } } catch { // empty catch } LastCheckResult = outerResult; return(outerResult); }