bool.Parse(string)

Here are the examples of the csharp api bool.Parse(string) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

1465 Examples 7

19 Source : MainWindow.xaml.cs
with GNU General Public License v3.0
from 00000vish

private void addButton_Click(object sender, RoutedEventArgs e)
        {
            AddAccount ASA = new AddAccount();
            String[] newAccount = ASA.Show("lol");
            ASA.Close();
            AccountController.addAccount(newAccount[0], Cryptography.Encrypt(newAccount[1], encryptionKey), bool.Parse(newAccount[2]));
            updateAccountList();
            writeAccountData();
            listView1.SelectedIndex = 0;
        }

19 Source : MetaBoundRef.cs
with MIT License
from 0x0ade

public override void Read(DataContext ctx, MetaTypeWrap data) {
            TypeBoundTo = data["Type"];
            ID = uint.Parse(data["ID"]);
            IsAlive = bool.Parse(data["IsAlive"]);
        }

19 Source : MetaRef.cs
with MIT License
from 0x0ade

public override void Read(DataContext ctx, MetaTypeWrap data) {
            ID = uint.Parse(data["ID"]);
            IsAlive = bool.Parse(data["IsAlive"]);
        }

19 Source : ExprPlainReader.cs
with MIT License
from 0x1000000

public bool TryGetBoolean(IPlainItem node, string propertyName, out bool value)
        {
            value = default;
            if (this.TryGetSubNode(node.Id, propertyName, null, out var prop) && prop.Value != null)
            {
                value = bool.Parse(prop.Value);
                return true;
            }
            return false;
        }

19 Source : CommonMethods.cs
with MIT License
from 1100100

internal static ZooKeeperClientConfigure ReadZooKeeperClientConfigure(IConfigurationSection configurationSection)
        {
            var client = new ZooKeeperClientConfigure();
            if (configurationSection.Exists())
            {
                var connection = configurationSection.GetSection("ConnectionString");
                if (connection.Exists())
                    client.ConnectionString = connection.Value;
                var sessionTimeout = configurationSection.GetSection("SessionTimeout");
                if (sessionTimeout.Exists())
                    client.SessionTimeout = int.Parse(sessionTimeout.Value);

                var canBeReadOnly = configurationSection.GetSection("CanBeReadOnly");
                if (canBeReadOnly.Exists())
                    client.CanBeReadOnly = bool.Parse(canBeReadOnly.Value);
            }
            return client;
        }

19 Source : ConsulServiceDiscovery.cs
with MIT License
from 1100100

public async Task<IReadOnlyList<ServiceDiscoveryInfo>> QueryServiceAsync(string serviceName, CancellationToken cancellationToken = default)
        {
            if (string.IsNullOrWhiteSpace(serviceName))
                throw new ArgumentNullException(nameof(serviceName));
            using (var consul = new ConsulClient(conf =>
            {
                conf.Address = ConsulClientConfigure.Address;
                conf.Datacenter = ConsulClientConfigure.Datacenter;
                conf.Token = ConsulClientConfigure.Token;
                conf.WaitTime = ConsulClientConfigure.WaitTime;
            }))
            {
                try
                {
                    var result = await consul.Health.Service(serviceName, "", true, cancellationToken);

                    if (result.StatusCode != HttpStatusCode.OK)
                    {
                        Logger.LogError("Query the service {0} failed:{0}", serviceName, result.StatusCode);
                        return new List<ServiceDiscoveryInfo>();
                    }

                    if (!result.Response.Any())
                        return new List<ServiceDiscoveryInfo>();

                    return result.Response.Select(p => new ServiceDiscoveryInfo(p.Service.ID, p.Service.Address, p.Service.Port, int.Parse(p.Service.Meta?.FirstOrDefault(m => m.Key == "X-Weight").Value ?? "0"), bool.Parse(p.Service.Meta?.FirstOrDefault(m => m.Key == "X-Tls").Value ?? "false"), p.Service.Meta)).ToList();
                }
                catch (Exception ex)
                {
                    Logger.LogError("Query the service {2} error:{0}\n{1}", ex.Message, ex.StackTrace, serviceName);
                    throw;
                }
            }
        }

19 Source : TypeConverterHelper.cs
with MIT License
from 1iveowl

public static object Convert(string value, string destinationTypeFullName)
        {
            if (string.IsNullOrWhiteSpace(destinationTypeFullName))
            {
                throw new ArgumentNullException(destinationTypeFullName);
            }

            var scope = GetScope(destinationTypeFullName);

            if (string.Equals(scope, "System", StringComparison.Ordinal))
            {
                if (string.Equals(destinationTypeFullName, typeof(string).FullName, StringComparison.Ordinal))
                {
                    return value;
                }
                else if (string.Equals(destinationTypeFullName, typeof(bool).FullName, StringComparison.Ordinal))
                {
                    return bool.Parse(value);
                }
                else if (string.Equals(destinationTypeFullName, typeof(int).FullName, StringComparison.Ordinal))
                {
                    return int.Parse(value);
                }
                else if (string.Equals(destinationTypeFullName, typeof(double).FullName, StringComparison.Ordinal))
                {
                    return double.Parse(value);
                }
            }

            return null;
        }

19 Source : ValueMember.cs
with MIT License
from 404Lcc

private static object ParseDefaultValue(Type type, object value)
        {
			if(true)
            {
                Type tmp = Helpers.GetUnderlyingType(type);
                if (tmp != null) type = tmp;
            }
            switch (Helpers.GetTypeCode(type))
            {
                case ProtoTypeCode.Boolean:
                case ProtoTypeCode.Byte:
                case ProtoTypeCode.Char: // char.Parse missing on CF/phone7
                case ProtoTypeCode.DateTime:
                case ProtoTypeCode.Decimal:
                case ProtoTypeCode.Double:
                case ProtoTypeCode.Int16:
                case ProtoTypeCode.Int32:
                case ProtoTypeCode.Int64:
                case ProtoTypeCode.SByte:
                case ProtoTypeCode.Single:
                case ProtoTypeCode.String:
                case ProtoTypeCode.UInt16:
                case ProtoTypeCode.UInt32:
                case ProtoTypeCode.UInt64:
                case ProtoTypeCode.TimeSpan:
                case ProtoTypeCode.Uri:
                case ProtoTypeCode.Guid:
                    {
                        value = value + "";
                    }
                    break;
            }
            if (value is string)
            {
                string s = (string)value;
                if (Helpers.IsEnum(type)) return Helpers.ParseEnum(type, s);

                switch (Helpers.GetTypeCode(type))
                {
                    case ProtoTypeCode.Boolean: return bool.Parse(s);
                    case ProtoTypeCode.Byte: return byte.Parse(s, NumberStyles.Integer, CultureInfo.InvariantCulture);
                    case ProtoTypeCode.Char: // char.Parse missing on CF/phone7
                        if (s.Length == 1) return s[0];
                        throw new FormatException("Single character expected: \"" + s + "\"");
                    case ProtoTypeCode.DateTime: return DateTime.Parse(s, CultureInfo.InvariantCulture);
                    case ProtoTypeCode.Decimal: return decimal.Parse(s, NumberStyles.Any, CultureInfo.InvariantCulture);
                    case ProtoTypeCode.Double: return double.Parse(s, NumberStyles.Any, CultureInfo.InvariantCulture);
                    case ProtoTypeCode.Int16: return short.Parse(s, NumberStyles.Any, CultureInfo.InvariantCulture);
                    case ProtoTypeCode.Int32: return int.Parse(s, NumberStyles.Any, CultureInfo.InvariantCulture);
                    case ProtoTypeCode.Int64: return long.Parse(s, NumberStyles.Any, CultureInfo.InvariantCulture);
                    case ProtoTypeCode.SByte: return sbyte.Parse(s, NumberStyles.Integer, CultureInfo.InvariantCulture);
                    case ProtoTypeCode.Single: return float.Parse(s, NumberStyles.Any, CultureInfo.InvariantCulture);
                    case ProtoTypeCode.String: return s;
                    case ProtoTypeCode.UInt16: return ushort.Parse(s, NumberStyles.Any, CultureInfo.InvariantCulture);
                    case ProtoTypeCode.UInt32: return uint.Parse(s, NumberStyles.Any, CultureInfo.InvariantCulture);
                    case ProtoTypeCode.UInt64: return ulong.Parse(s, NumberStyles.Any, CultureInfo.InvariantCulture);
                    case ProtoTypeCode.TimeSpan: return TimeSpan.Parse(s);
                    case ProtoTypeCode.Uri: return s; // Uri is decorated as string
                    case ProtoTypeCode.Guid: return new Guid(s);
                }
            }
#if FEAT_IKVM
            if (Helpers.IsEnum(type)) return value; // return the underlying type instead
            System.Type convertType = null;
            switch(Helpers.GetTypeCode(type))
            {
                case ProtoTypeCode.SByte: convertType = typeof(sbyte); break;
                case ProtoTypeCode.Int16: convertType = typeof(short); break;
                case ProtoTypeCode.Int32: convertType = typeof(int); break;
                case ProtoTypeCode.Int64: convertType = typeof(long); break;
                case ProtoTypeCode.Byte: convertType = typeof(byte); break;
                case ProtoTypeCode.UInt16: convertType = typeof(ushort); break;
                case ProtoTypeCode.UInt32: convertType = typeof(uint); break;
                case ProtoTypeCode.UInt64: convertType = typeof(ulong); break;
                case ProtoTypeCode.Single: convertType = typeof(float); break;
                case ProtoTypeCode.Double: convertType = typeof(double); break;
                case ProtoTypeCode.Decimal: convertType = typeof(decimal); break;
            }
            if(convertType != null) return Convert.ChangeType(value, convertType, CultureInfo.InvariantCulture);
            throw new ArgumentException("Unable to process default value: " + value + ", " + type.FullName);
#else
            if (Helpers.IsEnum(type)) return Enum.ToObject(type, value);
            return Convert.ChangeType(value, type, CultureInfo.InvariantCulture);
#endif
        }

19 Source : AuthConfigurer.cs
with MIT License
from 52ABP

public static void Configure(IServiceCollection services, IConfiguration configuration)
        {
            if (bool.Parse(configuration["Authentication:JwtBearer:IsEnabled"]))
            {
                services.AddAuthentication(options => {
                    options.DefaultAuthenticateScheme = "JwtBearer";
                    options.DefaultChallengeScheme = "JwtBearer";
                }).AddJwtBearer("JwtBearer", options =>
                {
                    options.Audience = configuration["Authentication:JwtBearer:Audience"];

                    options.TokenValidationParameters = new TokenValidationParameters
                    {
                        // The signing key must match!
                        ValidateIssuerSigningKey = true,
                        IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(configuration["Authentication:JwtBearer:SecurityKey"])),

                        // Validate the JWT Issuer (iss) claim
                        ValidateIssuer = true,
                        ValidIssuer = configuration["Authentication:JwtBearer:Issuer"],

                        // Validate the JWT Audience (aud) claim
                        ValidateAudience = true,
                        ValidAudience = configuration["Authentication:JwtBearer:Audience"],

                        // Validate the token expiry
                        ValidateLifetime = true,

                        // If you want to allow a certain amount of clock drift, set that here
                        ClockSkew = TimeSpan.Zero
                    };

                    options.Events = new JwtBearerEvents
                    {
                        OnMessageReceived = QueryStringTokenResolver
                    };
                });
            }
        }

19 Source : SettingsHelper.cs
with GNU General Public License v3.0
from 9vult

public static void Initialize()
        {
            string[] info = File.ReadAllLines(FileHelper.GetFile(FileHelper.APP_ROOT, "mikureader.txt").FullName);
            if (info.Length < 2)
            {
                WFClient.logger.Error("'mikureader.txt' did not contain all required fields!");
                throw new FileLoadException("'mikureader.txt' did not contain all required fields!");
            }


            UseDoubleReader = bool.Parse(info[0].Split('/')[0].Trim());
            CheckForUpdates = bool.Parse(info[1].Split('/')[0].Trim());
        }

19 Source : TestAmf0Reader.cs
with MIT License
from a1q123456

[TestMethod]
        public void TestReadBoolean()
        {
            var reader = new Amf0Reader();

            var files = Directory.GetFiles("../../../../samples/amf0/boolean");

            foreach (var file in files)
            {
                var value = bool.Parse(Path.GetFileNameWithoutExtension(file));
                using (var f = new FileStream(file, FileMode.Open))
                {
                    var data = new byte[f.Length];
                    f.Read(data);
                    replacedert.IsTrue(reader.TryGetBoolean(data, out var dataRead, out var consumed));
                    replacedert.AreEqual(dataRead, value);
                    replacedert.AreEqual(consumed, f.Length);
                }
            }
        }

19 Source : TestAmf3Reader.cs
with MIT License
from a1q123456

[TestMethod]
        public void TestReadBoolean()
        {
            var reader = new Amf3Reader();

            var files = Directory.GetFiles("../../../../samples/amf3/boolean");

            foreach (var file in files)
            {
                var value = bool.Parse(Path.GetFileNameWithoutExtension(file));
                using (var f = new FileStream(file, FileMode.Open))
                {
                    var data = new byte[f.Length];
                    f.Read(data);
                    replacedert.IsTrue(reader.TryGetBoolean(data, out var dataRead, out var consumed));
                    replacedert.AreEqual(dataRead, value);
                    replacedert.AreEqual(consumed, f.Length);
                }
            }
        }

19 Source : SyncUsageHelper.cs
with MIT License
from ABTSoftware

public void LoadFromIsolatedStorage()
        {
            using (IsolatedStorageFile isf = IsolatedStorageFile.GetStore(IsolatedStorageScope.User | IsolatedStorageScope.replacedembly, null, null))
            {
                if (isf.FileExists("Usage.xml"))
                {
                    try
                    {
                        using (var stream = new IsolatedStorageFileStream("Usage.xml", FileMode.Open, isf))
                        {
                            var usageXml = "";
                            using (StreamReader reader = new StreamReader(stream))
                            {
                                var encryptedUsage = reader.ReadToEnd();
                                try
                                {
                                    usageXml = _encryptionHelper.Decrypt(encryptedUsage);
                                }
                                catch
                                {
                                    // Old file contents will not decrypt due to encryption changes.  We don't care.
                                }
                            }

                            using (var textReader = new StringReader(usageXml))
                            {
                                var xDoreplacedent = XDoreplacedent.Load(textReader);

                                _usageCalculator.Usages = SerializationUtil.Deserialize(xDoreplacedent);
                                var userIdNode = xDoreplacedent.Root.Attributes("UserId").FirstOrDefault();
                                if (userIdNode != null)
                                {
                                    userId = userIdNode.Value;
                                }
                                var lastSentNode = xDoreplacedent.Root.Attributes("LastSent").FirstOrDefault();
                                if (lastSentNode != null)
                                {
                                    lastSent = DateTime.ParseExact(lastSentNode.Value, "o", null);
                                }
                                var enabledNode = xDoreplacedent.Root.Attributes("Enabled").FirstOrDefault();
                                if (enabledNode != null)
                                {
                                    _enabled = bool.Parse(enabledNode.Value);
                                }
                            }
                        }

                        EnabledChanged?.Invoke(this, EventArgs.Empty);
                    }
                    catch
                    {
                        // If something goes wrong, delete the local file
                        try { isf.DeleteFile("Usage.xml"); }
                        catch { }
                    }
                }
                else
                {
                    // Default on.
                    _enabled = true;
                    EnabledChanged?.Invoke(this, EventArgs.Empty);
                }
            }
        }

19 Source : DataManager.cs
with MIT License
from ABTSoftware

public List<WeatherData> LoadWeatherData()
        {
            var values = new List<WeatherData>();
            var asm = replacedembly.GetExecutingreplacedembly();
            var resourceString = asm.GetManifestResourceNames().Single(x => x.Contains("WeatherData.txt.gz"));
            using (var stream = asm.GetManifestResourceStream(resourceString))
            using (var gz = new GZipStream(stream, CompressionMode.Decompress))
            using (var streamReader = new StreamReader(gz))
            {
                string line = streamReader.ReadLine();
                while (line != null)
                {
                    var tokens = line.Split(',');
                    values.Add(new WeatherData
                    {
                        // ID, Date, MinTemp, MaxTemp, Rainfall, Sunshine, UVIndex, WindSpd, WindDir, Forecast, LocalStation
                        ID = int.Parse(tokens[0], NumberFormatInfo.InvariantInfo),
                        Date = DateTime.Parse(tokens[1], DateTimeFormatInfo.InvariantInfo),
                        MinTemp = double.Parse(tokens[2], NumberFormatInfo.InvariantInfo),
                        MaxTemp = double.Parse(tokens[3], NumberFormatInfo.InvariantInfo),
                        Rainfall = double.Parse(tokens[4], NumberFormatInfo.InvariantInfo),
                        Sunshine = double.Parse(tokens[5], NumberFormatInfo.InvariantInfo),
                        UVIndex = int.Parse(tokens[6], NumberFormatInfo.InvariantInfo),
                        WindSpeed = int.Parse(tokens[7], NumberFormatInfo.InvariantInfo),
                        WindDirection = (WindDirection) Enum.Parse(typeof(WindDirection), tokens[8]),
                        Forecast = tokens[9],
                        LocalStation = bool.Parse(tokens[10])
                    });

                    line = streamReader.ReadLine();
                }
            }

            return values;
        }

19 Source : BooleanComponent.xaml.cs
with MIT License
from ADeltaX

public byte[] GetValueData() => FromBoolean(bool.Parse((cmBox.SelectedItem as ComboBoxItem).Tag.ToString()), _timestamp);

19 Source : SelectionValidationRule.cs
with GNU General Public License v3.0
from AdhocAdam

public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            Visibility rv = Visibility.Visible;
            try
            {
                var x = bool.Parse(value.ToString());
                if (x)
                {
                    rv = Visibility.Visible;
                }
                else
                {
                    rv = Visibility.Collapsed;
                }
            }
            catch (Exception)
            {
            }
            return rv;
        }

19 Source : AuthorizeNetHelper.cs
with MIT License
from Adoxio

public static bool GetCreateInvoiceSettingValue(IPortalContext xrm)
		{
			var website = xrm.Website;

			var createInvoiceSetting = xrm.ServiceContext.CreateQuery("adx_sitesetting")
				.Where(ss => ss.GetAttributeValue<EnreplacedyReference>("adx_websiteid").Id == website.GetAttributeValue<Guid>("adx_websiteid"))
				.FirstOrDefault(purl => purl.GetAttributeValue<string>("adx_name") == "Ecommerce/CreateInvoiceOnVerification");

			if (createInvoiceSetting == null)
			{
				return true;
			}

			return bool.Parse(createInvoiceSetting.GetAttributeValue<string>("adx_value"));
		}

19 Source : Extensions.cs
with MIT License
from Adoxio

public static object GetAttribute<T>(this JToken attribute)
		{
			if (attribute == null) return null;
			if (typeof(T).GetUnderlyingType() == typeof(bool)) return bool.Parse(attribute.Value<string>());
			if (typeof(T).GetUnderlyingType() == typeof(int)) return int.Parse(attribute.Value<string>());
			if (typeof(T) == typeof(object)) return attribute.Value<JValue>().Value;

			return null;
		}

19 Source : Extensions.cs
with MIT License
from Adoxio

public static object GetAttribute<T>(this XAttribute attribute)
		{
			if (attribute == null) return null;
			if (typeof(T).GetUnderlyingType() == typeof(bool)) return bool.Parse(attribute.Value);
			if (typeof(T).GetUnderlyingType() == typeof(int)) return int.Parse(attribute.Value);
			if (typeof(T) == typeof(object)) return attribute.Value;

			return null;
		}

19 Source : SyntaxWalkerBase.cs
with MIT License
from adrianoc

private IEnumerable<string> ProcessDllImportAttribute(AttributeSyntax attribute, string methodVar)
        {
            var moduleName = attribute.ArgumentList?.Arguments.First().ToFullString();
            var existingModuleVar = Context.DefinitionVariables.GetVariable(moduleName, MemberKind.ModuleReference);
            
            var moduleVar = existingModuleVar.IsValid 
                ?  existingModuleVar.VariableName
                :  Context.Naming.SyntheticVariable("dllImportModule", ElementKind.LocalVariable); 

            var exps = new List<string>
            {
                $"{methodVar}.PInvokeInfo = new PInvokeInfo({ PInvokeAttributesFrom(attribute) }, { EntryPoint() }, {moduleVar});",
                $"{methodVar}.Body = null;",
                $"{methodVar}.ImplAttributes = {MethodImplAttributes()};",
            };

            if (!existingModuleVar.IsValid)
            {
                exps.InsertRange(0, new []
                {
                    $"var {moduleVar} = new ModuleReference({moduleName});",
                    $"replacedembly.MainModule.ModuleReferences.Add({moduleVar});",
                });
            }

            Context.DefinitionVariables.RegisterNonMethod("", moduleName, MemberKind.ModuleReference, moduleVar);
            
            return exps;
            
            string EntryPoint() => attribute?.ArgumentList?.Arguments.FirstOrDefault(arg => arg.NameEquals?.Name.Identifier.Text == "EntryPoint")?.Expression.ToString() ?? "\"\"";

            string MethodImplAttributes()
            {
                var preserveSig = Boolean.Parse(AttributePropertyOrDefaultValue(attribute, "PreserveSig", "true"));
                return preserveSig 
                    ? "MethodImplAttributes.PreserveSig | MethodImplAttributes.Managed" 
                    : "MethodImplAttributes.Managed";
            }

            string CallingConventionFrom(AttributeSyntax attr)
            {
                var callingConventionStr = attr.ArgumentList?.Arguments.FirstOrDefault(arg => arg.NameEquals?.Name.Identifier.Text == "CallingConvention")?.Expression.ToFullString() 
                                           ?? "Winapi";

                // ensures we use the enum member simple name; Parse() fails if we preplaced a qualified enum member
                var index = callingConventionStr.LastIndexOf('.');
                callingConventionStr = callingConventionStr.Substring(index + 1);
                
                return CallingConventionToCecil(Enum.Parse<CallingConvention>(callingConventionStr));
            }

            string CharSetFrom(AttributeSyntax attr)
            {
                var enumMemberName = AttributePropertyOrDefaultValue(attr, "CharSet", "None");

                // Only use the actual enum member name Parse() fails if we preplaced a qualified enum member
                var index = enumMemberName.LastIndexOf('.');
                enumMemberName = enumMemberName.Substring(index + 1);

                var charSet = Enum.Parse<CharSet>(enumMemberName);
                return charSet == CharSet.None ? string.Empty : $"PInvokeAttributes.CharSet{charSet}";
            }

            string SetLastErrorFrom(AttributeSyntax attr)
            {
                var setLastError = bool.Parse(AttributePropertyOrDefaultValue(attr, "SetLastError", "false"));
                return setLastError ? "PInvokeAttributes.SupportsLastError" : string.Empty;
            }

            string ExactSpellingFrom(AttributeSyntax attr)
            {
                var exactSpelling = bool.Parse(AttributePropertyOrDefaultValue(attr, "ExactSpelling", "false"));
                return exactSpelling ? "PInvokeAttributes.NoMangle" : string.Empty;
            }

            string BestFitMappingFrom(AttributeSyntax attr)
            {
                var bestFitMapping = bool.Parse(AttributePropertyOrDefaultValue(attr, "BestFitMapping", "true"));
                return bestFitMapping ? "PInvokeAttributes.BestFitEnabled" : "PInvokeAttributes.BestFitDisabled";
            }

            string ThrowOnUnmappableCharFrom(AttributeSyntax attr)
            {
                var bestFitMapping = bool.Parse(AttributePropertyOrDefaultValue(attr, "ThrowOnUnmappableChar", "false"));
                return bestFitMapping ? "PInvokeAttributes.ThrowOnUnmappableCharEnabled" : "PInvokeAttributes.ThrowOnUnmappableCharDisabled";
            }

            // For more information and default values see
            // https://docs.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.dllimportattribute
            string PInvokeAttributesFrom(AttributeSyntax attr)
            {
                return CallingConventionFrom(attr)
                    .AppendModifier(CharSetFrom(attr))
                    .AppendModifier(SetLastErrorFrom(attr))
                    .AppendModifier(ExactSpellingFrom(attr))
                    .AppendModifier(BestFitMappingFrom(attr))
                    .AppendModifier(ThrowOnUnmappableCharFrom(attr));
            }

            string AttributePropertyOrDefaultValue(AttributeSyntax attr, string propertyName, string defaultValue)
            {
                return attr.ArgumentList?.Arguments.FirstOrDefault(arg => arg.NameEquals?.Name.Identifier.Text == propertyName)?.Expression.ToFullString() ?? defaultValue;
            }
        }

19 Source : RedisLiteHelper.cs
with MIT License
from AElfProject

private static void HandleEndpointByName(RedisEndpoint endpoint, bool useDefaultPort, string name, string value)
        {
            switch (name)
            {
                case "db":
                    endpoint.Db = int.Parse(value);
                    break;
                case "ssl":
                    endpoint.Ssl = bool.Parse(value);
                    if (useDefaultPort)
                        endpoint.Port = RedisConfig.DefaultPortSsl;
                    break;
                case "client":
                    endpoint.Client = value;
                    break;
                case "preplacedword":
                    endpoint.Preplacedword = value;
                    break;
                case "namespaceprefix":
                    endpoint.NamespacePrefix = value;
                    break;
                case "connecttimeout":
                    endpoint.ConnectTimeout = int.Parse(value);
                    break;
                case "sendtimeout":
                    endpoint.SendTimeout = int.Parse(value);
                    break;
                case "receivetimeout":
                    endpoint.ReceiveTimeout = int.Parse(value);
                    break;
                case "retrytimeout":
                    endpoint.RetryTimeout = int.Parse(value);
                    break;
                case "idletimeout":
                case "idletimeoutsecs":
                    endpoint.IdleTimeOutSecs = int.Parse(value);
                    break;
            }
        }

19 Source : MyPageBase.cs
with Mozilla Public License 2.0
from agebullhu

protected bool GetBoolArg(string name)
        {
            var value = GetArgValue(name);
            if (string.IsNullOrEmpty(value) || value == "undefined" || value == "null")
            {
                return false;
            }
            return value != "0" && (value == "1" || value == "yes" || bool.Parse(value));
        }

19 Source : ApiControlerEx.cs
with Mozilla Public License 2.0
from agebullhu

protected bool GetBoolArg(string name)
        {
            var value = GetArgValue(name);
            if (string.IsNullOrEmpty(value) || value == "undefined" || value == "null") return false;
            return value != "0" && (value == "1" || value == "yes" || bool.Parse(value));
        }

19 Source : MainForm.cs
with GNU General Public License v3.0
from AgentRev

void ReadSettings()
        {
            currentlyReading = true;
            StreamReader sr = null;
            string checkVer = c_toolVer;

            try
            {
                using (sr = new StreamReader(settingsFile))
                {
                    string line;
                    while ((line = sr.ReadLine()) != null)
                    {
                        try
                        {
                            int equalsign = line.IndexOf('=');
                            if (equalsign > 0)
                            {
                                string varName = line.Substring(0, equalsign);
                                string varValue = line.Substring(equalsign + 1);

                                if (varName == "ToolVersion" || varName == "GameVersion")
                                {
                                    checkVer = varValue;
                                }
                                else if (varName == "GameMode")
                                {
                                    rbSingleplayer.Checked = (varValue == "sp");
                                }
                                else if (varName == "Beep")
                                {
                                    chkBeep.Checked = bool.Parse(varValue);
                                }
                                else if (varName == "FoV")
                                {
                                    SetFoV(float.Parse(varValue));
                                }
                                else if (varName == "FoVOffset" || varName == "RelativeFoVOffset")
                                {
                                    dword_ptr tmp = dword_ptr.Parse(varValue, NumberStyles.AllowHexSpecifier);
                                    if (tmp > (dword_ptr)gameMode.GetValue("c_baseAddr"))
                                        pFoV = (varName == "RelativeFoVOffset" ? (dword_ptr)gameMode.GetValue("c_baseAddr") : 0) + tmp;
                                }
                                else if (varName == "UpdateNotify")
                                {
                                    chkUpdate.Checked = bool.Parse(varValue);
                                }
                                else if (varName == "DisableHotkeys")
                                {
                                    chkHotkeys.Checked = bool.Parse(varValue);
                                }
                                else if (varName == "HotkeyIncrease")
                                {
                                    catchKeys[0] = (Keys)int.Parse(varValue);
                                    btnKeyZoomOut.Text = VirtualKeyName(catchKeys[0]);
                                }
                                else if (varName == "HotkeyDecrease")
                                {
                                    catchKeys[1] = (Keys)int.Parse(varValue);
                                    btnKeyZoomIn.Text = VirtualKeyName(catchKeys[1]);
                                }
                                else if (varName == "HotkeyReset")
                                {
                                    catchKeys[2] = (Keys)int.Parse(varValue);
                                    btnKeyReset.Text = VirtualKeyName(catchKeys[2]);
                                }
                            }
                        }
                        catch { }
                    }
                }
            }
            finally
            {
                if (sr != null)
                    sr.Close();
            }

            if (checkVer != c_toolVer)
                pFoV = (dword_ptr)gameMode.GetValue("c_pFoV");

            UpdateCheck();

            currentlyReading = false;
        }

19 Source : MainForm.cs
with GNU General Public License v3.0
from AgentRev

void ReadSettings()
        {
            currentlyReading = true;
            StreamReader sr = null;
            string checkVer = c_toolVer;

            try
            {
                using (sr = new StreamReader(settingsFile))
                {
                    string line;
                    while ((line = sr.ReadLine()) != null)
                    {
                        try
                        {
                            int equalsign = line.IndexOf('=');
                            if (equalsign > 0)
                            {
                                string varName = line.Substring(0, equalsign);
                                string varValue = line.Substring(equalsign + 1);

                                if (varName == "ToolVersion" || varName == "GameVersion")
                                {
                                    checkVer = varValue;
                                }
                                else if (varName == "GameMode")
                                {
                                    rbSingleplayer.Checked = (varValue == "sp");
                                }
                                else if (varName == "Beep")
                                {
                                    chkBeep.Checked = bool.Parse(varValue);
                                }
                                else if (varName == "FoV")
                                {
                                    SetFoV(float.Parse(varValue));
                                }
                                else if (varName == "FoVOffset" || varName == "RelativeFoVOffset")
                                {
                                    int tmp = int.Parse(varValue, NumberStyles.AllowHexSpecifier);
                                    if (tmp > (int)gameMode.GetValue("c_baseAddr") && tmp < 0x40000000)
                                        pFoV = (varName == "RelativeFoVOffset" ? (int)gameMode.GetValue("c_baseAddr") : 0) + tmp;
                                }
                                else if (varName == "UpdatePopup" || varName == "UpdateCheck")
                                {
                                    chkUpdate.Checked = bool.Parse(varValue);
                                }
                                else if (varName == "DisableHotkeys")
                                {
                                    chkHotkeys.Checked = bool.Parse(varValue);
                                }
                                else if (varName == "HotkeyIncrease")
                                {
                                    catchKeys[0] = (Keys)int.Parse(varValue);
                                    btnKeyZoomOut.Text = VirtualKeyName(catchKeys[0]);
                                }
                                else if (varName == "HotkeyDecrease")
                                {
                                    catchKeys[1] = (Keys)int.Parse(varValue);
                                    btnKeyZoomIn.Text = VirtualKeyName(catchKeys[1]);
                                }
                                else if (varName == "HotkeyReset")
                                {
                                    catchKeys[2] = (Keys)int.Parse(varValue);
                                    btnKeyReset.Text = VirtualKeyName(catchKeys[2]);
                                }
                            }
                        }
                        catch { }
                    }
                }
            }
            finally
            {
                if (sr != null)
                    sr.Close();
            }

            if (checkVer != c_toolVer)
                pFoV = (int)gameMode.GetValue("c_pFoV");

            if (!requestSent)
            {
                try
                {
                    request = (HttpWebRequest)WebRequest.Create(c_checkURL);
                    request.BeginGetResponse(new AsyncCallback(UpdateResponse), null);
                    requestSent = true;
                }
                catch { }
            }

            currentlyReading = false;
        }

19 Source : BooleanData.cs
with GNU Affero General Public License v3.0
from aianlinb

public override void FromString(string value) {
			Value = bool.Parse(value);
		}

19 Source : SteamVR_ExternalCamera.cs
with MIT License
from ajayyy

public void ReadConfig()
	{
		try
		{
			var mCam = new HmdMatrix34_t();
			var readCamMatrix = false;

			object c = config; // box
			var lines = System.IO.File.ReadAllLines(configPath);
			foreach (var line in lines)
			{
				var split = line.Split('=');
				if (split.Length == 2)
				{
					var key = split[0];
					if (key == "m")
					{
						var values = split[1].Split(',');
						if (values.Length == 12)
						{
							mCam.m0 = float.Parse(values[0]);
							mCam.m1 = float.Parse(values[1]);
							mCam.m2 = float.Parse(values[2]);
							mCam.m3 = float.Parse(values[3]);
							mCam.m4 = float.Parse(values[4]);
							mCam.m5 = float.Parse(values[5]);
							mCam.m6 = float.Parse(values[6]);
							mCam.m7 = float.Parse(values[7]);
							mCam.m8 = float.Parse(values[8]);
							mCam.m9 = float.Parse(values[9]);
							mCam.m10 = float.Parse(values[10]);
							mCam.m11 = float.Parse(values[11]);
							readCamMatrix = true;
						}
					}
#if !UNITY_METRO
					else if (key == "disableStandardreplacedets")
					{
						var field = c.GetType().GetField(key);
						if (field != null)
							field.SetValue(c, bool.Parse(split[1]));
					}
					else
					{
						var field = c.GetType().GetField(key);
						if (field != null)
							field.SetValue(c, float.Parse(split[1]));
					}
#endif
				}
			}
			config = (Config)c; //unbox

			// Convert calibrated camera matrix settings.
			if (readCamMatrix)
			{
				var t = new SteamVR_Utils.RigidTransform(mCam);
				config.x = t.pos.x;
				config.y = t.pos.y;
				config.z = t.pos.z;
				var angles = t.rot.eulerAngles;
				config.rx = angles.x;
				config.ry = angles.y;
				config.rz = angles.z;
			}
		}
		catch { }

		// Clear target so AttachToCamera gets called to pick up any changes.
		target = null;
#if !UNITY_METRO
		// Listen for changes.
		if (watcher == null)
		{
			var fi = new System.IO.FileInfo(configPath);
			watcher = new System.IO.FileSystemWatcher(fi.DirectoryName, fi.Name);
			watcher.NotifyFilter = System.IO.NotifyFilters.LastWrite;
			watcher.Changed += new System.IO.FileSystemEventHandler(OnChanged);
			watcher.EnableRaisingEvents = true;
		}
	}

19 Source : Startup.cs
with MIT License
from alanedwardes

public void ConfigureServices(IServiceCollection services)
        {
            const string LfsBucketVariable = "LFS_BUCKET";
            const string LfsUsernameVariable = "LFS_USERNAME";
            const string LfsPreplacedwordVariable = "LFS_PreplacedWORD";
            const string GitHubOrganisationVariable = "GITHUB_ORGANISATION";
            const string GitHubRepositoryVariable = "GITHUB_REPOSITORY";
            const string BitBucketWorkspaceVariable = "BITBUCKET_WORKSPACE";
            const string BitBucketRepositoryVariable = "BITBUCKET_REPOSITORY";
            const string S3AccelerationVariable = "S3_ACCELERATION";
            const string LfsAzureStorageConnectionStringVariable = "LFS_AZUREBLOB_CONNECTIONSTRING";
            const string LfsAzureStorageContainerNameVariable = "LFS_AZUREBLOB_CONTAINERNAME";

            var config = new ConfigurationBuilder()
                .AddEnvironmentVariables()
                .Build();

            string lfsBucket = config[LfsBucketVariable];
            string lfsAzureStorageConnectionString = config[LfsAzureStorageConnectionStringVariable];
            string lfsUsername = config[LfsUsernameVariable];
            string lfsPreplacedword = config[LfsPreplacedwordVariable];
            string gitHubOrganisation = config[GitHubOrganisationVariable];
            string gitHubRepository = config[GitHubRepositoryVariable];
            string bitBucketWorkspace = config[BitBucketWorkspaceVariable];
            string bitBucketRepository = config[BitBucketRepositoryVariable];
            bool s3Acceleration = bool.Parse(config[S3AccelerationVariable] ?? "false");

            bool isS3Storage = !string.IsNullOrWhiteSpace(lfsBucket);
            bool isAzureStorage = !string.IsNullOrWhiteSpace(lfsAzureStorageConnectionString);
            bool isDictionaryAuthentication = !string.IsNullOrWhiteSpace(lfsUsername) && !string.IsNullOrWhiteSpace(lfsPreplacedword);
            bool isGitHubAuthentication = !string.IsNullOrWhiteSpace(gitHubOrganisation) && !string.IsNullOrWhiteSpace(gitHubRepository);
            bool isBitBucketAuthentication = !string.IsNullOrWhiteSpace(bitBucketWorkspace) && !string.IsNullOrWhiteSpace(bitBucketRepository);

            // If all authentication mechanims are set, or none are set throw an error
            if (new[] {isDictionaryAuthentication, isGitHubAuthentication, isBitBucketAuthentication}.Count(x => x) != 1)
            {
                throw new InvalidOperationException($"Unable to detect authentication mechanism. Please set {LfsUsernameVariable} and {LfsPreplacedwordVariable} for simple user/preplacedword auth" +
                                                    $" or {GitHubOrganisationVariable} and {GitHubRepositoryVariable} for authentication against that repository on GitHub");
            }

            if (isDictionaryAuthentication)
            {
                services.AddLfsDictionaryAuthenticator(new Dictionary<string, string> { { lfsUsername, lfsPreplacedword } });
            }

            if (isGitHubAuthentication)
            {
                services.AddLfsGitHubAuthenticator(new GitHubAuthenticatorConfig { Organisation = gitHubOrganisation, Repository = gitHubRepository });
            }

            if (isBitBucketAuthentication)
            {
                services.AddLfsBitBucketAuthenticator(new BitBucketAuthenticatorConfig { Workspace = bitBucketWorkspace, Repository = bitBucketRepository });
            }

            if (isS3Storage)
            {
                services.AddLfsS3Adapter(new S3BlobAdapterConfig { Bucket = lfsBucket }, new AmazonS3Client(new AmazonS3Config { UseAccelerateEndpoint = s3Acceleration }));
            }
            else if (isAzureStorage)
            {
                services.AddLfsAzureBlobAdapter(new AzureBlobAdapterConfig
                {
                    ConnectionString = lfsAzureStorageConnectionString,
                    ContainerName = config[LfsAzureStorageContainerNameVariable]
                });
            }
            else
            {
                throw new InvalidOperationException($"Missing environment variable {LfsBucketVariable} or {LfsAzureStorageConnectionStringVariable}.");
            }

            services.AddLfsApi();

            services.AddLogging(x => x.AddLambdaLogger());
        }

19 Source : ItemParser.cs
with GNU General Public License v3.0
from AlanMorel

protected override List<ItemMetadata> Parse()
    {
        // Item breaking ingredients
        Dictionary<int, List<ItemBreakReward>> rewards = new();
        foreach (PackFileEntry entry in Resources.XmlReader.Files)
        {
            if (!entry.Name.StartsWith("table/itembreakingredient"))
            {
                continue;
            }

            XmlDoreplacedent innerDoreplacedent = Resources.XmlReader.GetXmlDoreplacedent(entry);
            XmlNodeList individualItems = innerDoreplacedent.SelectNodes($"/ms2/item");
            foreach (XmlNode nodes in individualItems)
            {
                string locale = nodes.Attributes["locale"]?.Value ?? "";
                if (locale != "NA" && locale != "")
                {
                    continue;
                }
                int itemID = int.Parse(nodes.Attributes["ItemID"].Value);
                rewards[itemID] = new();

                int ingredienreplacedemID1 = int.Parse(nodes.Attributes["IngredienreplacedemID1"]?.Value ?? "0");
                int ingredientCount1 = int.Parse(nodes.Attributes["IngredientCount1"]?.Value ?? "0");
                rewards[itemID].Add(new(ingredienreplacedemID1, ingredientCount1));

                _ = int.TryParse(nodes.Attributes["IngredienreplacedemID2"]?.Value ?? "0", out int ingredienreplacedemID2);
                _ = int.TryParse(nodes.Attributes["IngredientCount2"]?.Value ?? "0", out int ingredientCount2);
                rewards[itemID].Add(new(ingredienreplacedemID2, ingredientCount2));

                _ = int.TryParse(nodes.Attributes["IngredienreplacedemID3"]?.Value ?? "0", out int ingredienreplacedemID3);
                _ = int.TryParse(nodes.Attributes["IngredientCount3"]?.Value ?? "0", out int ingredientCount3);
                rewards[itemID].Add(new(ingredienreplacedemID3, ingredientCount3));
            }
        }

        //Item Name
        Dictionary<int, string> names = new();
        foreach (PackFileEntry entry in Resources.XmlReader.Files)
        {
            if (!entry.Name.StartsWith("string/en/itemname.xml"))
            {
                continue;
            }

            XmlDoreplacedent innerDoreplacedent = Resources.XmlReader.GetXmlDoreplacedent(entry);
            XmlNodeList nodes = innerDoreplacedent.SelectNodes($"/ms2/key");
            foreach (XmlNode node in nodes)
            {
                int itemId = int.Parse(node.Attributes["id"].Value);
                if (node.Attributes["name"] == null)
                {
                    continue;
                }
                string itemName = node.Attributes["name"].Value;
                names[itemId] = itemName;
            }
        }

        // Item rarity
        Dictionary<int, int> rarities = new();
        foreach (PackFileEntry entry in Resources.XmlReader.Files)
        {
            if (!entry.Name.StartsWith("table/na/itemwebfinder"))
            {
                continue;
            }
            XmlDoreplacedent innerDoreplacedent = Resources.XmlReader.GetXmlDoreplacedent(entry);
            XmlNodeList nodes = innerDoreplacedent.SelectNodes($"/ms2/key");
            foreach (XmlNode node in nodes)
            {
                int itemId = int.Parse(node.Attributes["id"].Value);
                int rarity = int.Parse(node.Attributes["grade"].Value);
                rarities[itemId] = rarity;
            }
        }

        // Items
        List<ItemMetadata> items = new();
        foreach (PackFileEntry entry in Resources.XmlReader.Files)
        {
            if (!entry.Name.StartsWith("item/"))
            {
                continue;
            }

            ItemMetadata metadata = new();
            string filename = Path.GetFileNameWithoutExtension(entry.Name);
            int itemId = int.Parse(filename);

            if (items.Exists(item => item.Id == itemId))
            {
                continue;
            }

            metadata.Id = itemId;
            Debug.replacedert(metadata.Id > 0, $"Invalid Id {metadata.Id} from {itemId}");

            // Parse XML
            XmlDoreplacedent doreplacedent = Resources.XmlReader.GetXmlDoreplacedent(entry);
            XmlNode item = doreplacedent.SelectSingleNode("ms2/environment");

            // Tag
            XmlNode basic = item.SelectSingleNode("basic");
            metadata.Tag = basic.Attributes["stringTag"].Value;

            // Gear/Cosmetic slot
            XmlNode slots = item.SelectSingleNode("slots");
            XmlNode slot = slots.FirstChild;
            bool slotResult = Enum.TryParse(slot.Attributes["name"].Value, out metadata.Slot);
            if (!slotResult && !string.IsNullOrEmpty(slot.Attributes["name"].Value))
            {
                Console.WriteLine($"Failed to parse item slot for {itemId}: {slot.Attributes["name"].Value}");
            }

            int totalSlots = slots.SelectNodes("slot").Count;
            if (totalSlots > 1)
            {
                if (metadata.Slot == ItemSlot.CL || metadata.Slot == ItemSlot.PA)
                {
                    metadata.IsDress = true;
                }
                else if (metadata.Slot == ItemSlot.RH || metadata.Slot == ItemSlot.LH)
                {
                    metadata.IsTwoHand = true;
                }
            }

            // Hair data
            if (slot.Attributes["name"].Value == "HR")
            {
                int replacedetNodeCount = slot.SelectNodes("replacedet").Count;
                XmlNode replacedet = slot.FirstChild;

                XmlNode scaleNode = slot.SelectSingleNode("scale");

                if (replacedetNodeCount == 3) // This hair has a front and back positionable hair
                {
                    XmlNode backHair = replacedet.NextSibling; // back hair info
                    XmlNode frontHair = backHair.NextSibling; // front hair info

                    int backHairNodes = backHair.SelectNodes("custom").Count;

                    CoordF[] bPosCord = new CoordF[backHairNodes];
                    CoordF[] bPosRotation = new CoordF[backHairNodes];
                    CoordF[] fPosCord = new CoordF[backHairNodes];
                    CoordF[] fPosRotation = new CoordF[backHairNodes];

                    for (int i = 0; i < backHairNodes; i++)
                    {
                        foreach (XmlNode backPresets in backHair)
                        {
                            if (backPresets.Name == "custom")
                            {
                                bPosCord[i] = CoordF.Parse(backPresets.Attributes["position"].Value);
                                bPosRotation[i] = CoordF.Parse(backPresets.Attributes["rotation"].Value);
                            }
                        }
                        foreach (XmlNode frontPresets in frontHair)
                        {
                            if (frontPresets.Name == "custom")
                            {
                                fPosCord[i] = CoordF.Parse(frontPresets.Attributes["position"].Value);
                                fPosRotation[i] = CoordF.Parse(frontPresets.Attributes["position"].Value);
                            }
                        }
                        HairPresets hairPresets = new()
                        {
                        };

                        hairPresets.BackPositionCoord = bPosCord[i];
                        hairPresets.BackPositionRotation = bPosRotation[i];
                        hairPresets.FrontPositionCoord = fPosCord[i];
                        hairPresets.FrontPositionRotation = fPosRotation[i];
                        hairPresets.MinScale = float.Parse(scaleNode?.Attributes["min"]?.Value ?? "0");
                        hairPresets.MaxScale = float.Parse(scaleNode?.Attributes["max"]?.Value ?? "0");

                        metadata.HairPresets.Add(hairPresets);
                    }
                }
                else if (replacedetNodeCount == 2) // This hair only has back positionable hair
                {
                    XmlNode backHair = replacedet.NextSibling; // back hair info

                    int backHairNodes = backHair.SelectNodes("custom").Count;

                    CoordF[] bPosCord = new CoordF[backHairNodes];
                    CoordF[] bPosRotation = new CoordF[backHairNodes];

                    for (int i = 0; i < backHairNodes; i++)
                    {
                        foreach (XmlNode backPresets in backHair)
                        {
                            if (backPresets.Name == "custom")
                            {
                                bPosCord[i] = CoordF.Parse(backPresets.Attributes["position"].Value);
                                bPosRotation[i] = CoordF.Parse(backPresets.Attributes["rotation"].Value);
                            }
                        }

                        HairPresets hairPresets = new()
                        {
                        };

                        hairPresets.BackPositionCoord = bPosCord[i];
                        hairPresets.BackPositionRotation = bPosRotation[i];
                        hairPresets.FrontPositionCoord = CoordF.Parse("0, 0, 0");
                        hairPresets.FrontPositionRotation = CoordF.Parse("0, 0, 0");
                        hairPresets.MinScale = float.Parse(scaleNode?.Attributes["min"]?.Value ?? "0");
                        hairPresets.MaxScale = float.Parse(scaleNode?.Attributes["max"]?.Value ?? "0");
                        metadata.HairPresets.Add(hairPresets);
                    }
                }
                else // hair does not have back or front positionable hair
                {
                    HairPresets hairPresets = new()
                    {
                    };
                    hairPresets.BackPositionCoord = CoordF.Parse("0, 0, 0");
                    hairPresets.BackPositionRotation = CoordF.Parse("0, 0, 0");
                    hairPresets.FrontPositionCoord = CoordF.Parse("0, 0, 0");
                    hairPresets.FrontPositionRotation = CoordF.Parse("0, 0, 0");
                    hairPresets.MinScale = float.Parse(scaleNode?.Attributes["min"]?.Value ?? "0");
                    hairPresets.MaxScale = float.Parse(scaleNode?.Attributes["max"]?.Value ?? "0");
                    metadata.HairPresets.Add(hairPresets);
                }
            }


            // Color data
            XmlNode customize = item.SelectSingleNode("customize");
            metadata.ColorIndex = int.Parse(customize.Attributes["defaultColorIndex"].Value);
            metadata.ColorPalette = int.Parse(customize.Attributes["colorPalette"].Value);

            // Badge slot
            XmlNode gem = item.SelectSingleNode("gem");
            bool gemResult = Enum.TryParse(gem.Attributes["system"].Value, out metadata.Gem);
            if (!gemResult && !string.IsNullOrEmpty(gem.Attributes["system"].Value))
            {
                Console.WriteLine($"Failed to parse badge slot for {itemId}: {gem.Attributes["system"].Value}");
            }

            // Inventory tab and max stack size
            XmlNode property = item.SelectSingleNode("property");
            try
            {
                byte type = byte.Parse(property.Attributes["type"].Value);
                byte subType = byte.Parse(property.Attributes["subtype"].Value);
                bool skin = byte.Parse(property.Attributes["skin"].Value) != 0;
                metadata.Tab = GetTab(type, subType, skin);
                metadata.IsTemplate = byte.Parse(property.Attributes["skinType"]?.Value ?? "0") == 99;
                metadata.TradeableCount = byte.Parse(property.Attributes["tradableCount"].Value);
                metadata.RepackageCount = byte.Parse(property.Attributes["rePackingLimitCount"].Value);
                metadata.RepackageItemConsumeCount = byte.Parse(property.Attributes["rePackingItemConsumeCount"].Value);
                metadata.BlackMarketCategory = property.Attributes["blackMarketCategory"].Value;

                // sales price
                XmlNode sell = property.SelectSingleNode("sell");
                metadata.SellPrice = sell.Attributes["price"]?.Value.Split(',').Select(int.Parse).ToList() ?? null;
                metadata.SellPriceCustom = sell.Attributes["priceCustom"]?.Value.Split(',').Select(int.Parse).ToList() ?? null;
            }
            catch (Exception e)
            {
                Console.WriteLine($"Failed to parse tab slot for {itemId}: {e.Message}");
            }
            metadata.StackLimit = int.Parse(property.Attributes["slotMax"].Value);

            // Rarity
            XmlNode option = item.SelectSingleNode("option");
            metadata.OptionStatic = int.Parse(option.Attributes["static"].Value);
            metadata.OptionRandom = int.Parse(option.Attributes["random"].Value);
            metadata.OptionConstant = int.Parse(option.Attributes["constant"].Value);
            metadata.OptionLevelFactor = int.Parse(option.Attributes["optionLevelFactor"].Value);

            XmlNode function = item.SelectSingleNode("function");
            string contentType = function.Attributes["name"].Value;
            metadata.FunctionData.Name = contentType;

            // Item boxes
            if (contentType == "OpenItemBox")
            {
                // selection boxes are SelecreplacedemBox and 1,boxid
                // normal boxes are OpenItemBox and 0,1,0,boxid
                // fragments are OpenItemBox and 0,1,0,boxid,required_amount
                if (function.Attributes["parameter"].Value.Contains('l'))
                {
                    continue; // TODO: Implement these CN items. Skipping for now
                }

                List<string> parameters = new(function.Attributes["parameter"].Value.Split(","));
                OpenItemBox box = new();
                box.RequiredItemId = int.Parse(parameters[0]);
                box.ReceiveOneItem = parameters[1] == "1";
                box.BoxId = int.Parse(parameters[3]);
                box.AmountRequired = 1;
                if (parameters.Count == 5)
                {
                    box.AmountRequired = int.Parse(parameters[4]);
                }
                metadata.FunctionData.OpenItemBox = box;
            }
            else if (contentType == "SelecreplacedemBox")
            {
                if (function.Attributes["parameter"].Value.Contains('l'))
                {
                    continue; // TODO: Implement these CN items. Skipping for now
                }

                List<string> parameters = new(function.Attributes["parameter"].Value.Split(","));
                parameters.RemoveAll(param => param.Length == 0);
                SelecreplacedemBox box = new();
                box.GroupId = int.Parse(parameters[0]);
                box.BoxId = int.Parse(parameters[1]);
                metadata.FunctionData.SelecreplacedemBox = box;
            }
            else if (contentType == "ChatEmoticonAdd")
            {
                ChatEmoticonAdd sticker = new();
                string rawParameter = function.Attributes["parameter"].Value;
                string decodedParameter = HttpUtility.HtmlDecode(rawParameter);
                XmlDoreplacedent xmlParameter = new();
                xmlParameter.LoadXml(decodedParameter);
                XmlNode functionParameters = xmlParameter.SelectSingleNode("v");
                sticker.Id = byte.Parse(functionParameters.Attributes["id"].Value);

                sticker.Duration = int.Parse(functionParameters.Attributes["durationSec"]?.Value ?? "0");
                metadata.FunctionData.ChatEmoticonAdd = sticker;
            }
            else if (contentType == "OpenMreplacedive")
            {
                OpenMreplacediveEvent mreplacediveEvent = new();
                string rawParameter = function.Attributes["parameter"].Value;
                string cleanParameter = rawParameter.Remove(1, 1); // remove the unwanted space
                string decodedParameter = HttpUtility.HtmlDecode(cleanParameter);

                XmlDoreplacedent xmlParameter = new();
                xmlParameter.LoadXml(decodedParameter);
                XmlNode functionParameters = xmlParameter.SelectSingleNode("v");
                mreplacediveEvent.FieldId = int.Parse(functionParameters.Attributes["fieldID"].Value);
                mreplacediveEvent.Duration = int.Parse(functionParameters.Attributes["portalDurationTick"].Value);
                mreplacediveEvent.Capacity = byte.Parse(functionParameters.Attributes["maxCount"].Value);
                metadata.FunctionData.OpenMreplacediveEvent = mreplacediveEvent;
            }
            else if (contentType == "LevelPotion")
            {
                LevelPotion levelPotion = new();
                string rawParameter = function.Attributes["parameter"].Value;
                string decodedParameter = HttpUtility.HtmlDecode(rawParameter);
                XmlDoreplacedent xmlParameter = new();
                xmlParameter.LoadXml(decodedParameter);
                XmlNode functionParameters = xmlParameter.SelectSingleNode("v");
                levelPotion.TargetLevel = byte.Parse(functionParameters.Attributes["targetLevel"].Value);
                metadata.FunctionData.LevelPotion = levelPotion;
            }
            else if (contentType == "VIPCoupon")
            {
                VIPCoupon coupon = new();
                string rawParameter = function.Attributes["parameter"].Value;
                string decodedParameter = HttpUtility.HtmlDecode(rawParameter);
                XmlDoreplacedent xmlParameter = new();
                xmlParameter.LoadXml(decodedParameter);
                XmlNode functionParameters = xmlParameter.SelectSingleNode("v");
                coupon.Duration = int.Parse(functionParameters.Attributes["period"].Value);
                metadata.FunctionData.VIPCoupon = coupon;
            }
            else if (contentType == "HongBao")
            {
                HongBaoData hongBao = new();
                string rawParameter = function.Attributes["parameter"].Value;
                string decodedParameter = HttpUtility.HtmlDecode(rawParameter);
                XmlDoreplacedent xmlParameter = new();
                xmlParameter.LoadXml(decodedParameter);
                XmlNode functionParameters = xmlParameter.SelectSingleNode("v");
                hongBao.Id = int.Parse(functionParameters.Attributes["itemId"].Value);
                hongBao.Count = short.Parse(functionParameters.Attributes["totalCount"].Value);
                hongBao.TotalUsers = byte.Parse(functionParameters.Attributes["totalUser"].Value);
                hongBao.Duration = int.Parse(functionParameters.Attributes["durationSec"].Value);
                metadata.FunctionData.HongBao = hongBao;
            }
            else if (contentType == "SuperWorldChat")
            {
                string[] parameters = function.Attributes["parameter"].Value.Split(",");
                metadata.FunctionData.Id = int.Parse(parameters[0]); // only storing the first parameter. Not sure if the server uses the other 2. 
            }
            else if (contentType == "OpenGachaBox")
            {
                string[] parameters = function.Attributes["parameter"].Value.Split(",");
                metadata.FunctionData.Id = int.Parse(parameters[0]); // only storing the first parameter. Unknown what the second parameter is used for.
            }
            else if (contentType == "OpenCoupleEffectBox")
            {
                OpenCoupleEffectBox box = new();
                string[] parameters = function.Attributes["parameter"].Value.Split(",");
                box.Id = int.Parse(parameters[0]);
                box.Rarity = byte.Parse(parameters[1]);
                metadata.FunctionData.OpenCoupleEffectBox = box;
            }
            else if (contentType == "InstallBillBoard")
            {
                InstallBillboard balloon = new();
                string rawParameter = function.Attributes["parameter"].Value;
                string decodedParameter = HttpUtility.HtmlDecode(rawParameter);
                XmlDoreplacedent xmlParameter = new();
                xmlParameter.LoadXml(decodedParameter);
                XmlNode functionParameters = xmlParameter.SelectSingleNode("v");
                balloon.InteractId = int.Parse(functionParameters.Attributes["interactID"].Value);
                balloon.Duration = int.Parse(functionParameters.Attributes["durationSec"].Value);
                balloon.Model = functionParameters.Attributes["model"].Value;
                balloon.replacedet = functionParameters.Attributes["replacedet"]?.Value ?? "";
                balloon.NormalState = functionParameters.Attributes["normal"].Value;
                balloon.Reactable = functionParameters.Attributes["reactable"].Value;
                balloon.Scale = float.Parse(functionParameters.Attributes["scale"]?.Value ?? "0");
                metadata.FunctionData.InstallBillboard = balloon;
            }
            else if (contentType == "replacedleScroll" || contentType == "ItemExchangeScroll" || contentType == "OpenInstrument" || contentType == "StoryBook" || contentType == "FishingRod" || contentType == "ItemChangeBeauty"
                     || contentType == "ItemRePackingScroll")
            {
                metadata.FunctionData.Id = int.Parse(function.Attributes["parameter"].Value);
            }

            // Music score charges
            XmlNode musicScore = item.SelectSingleNode("MusicScore");
            metadata.PlayCount = int.Parse(musicScore.Attributes["playCount"].Value);
            metadata.FileName = musicScore.Attributes["fileName"].Value;
            metadata.IsCustomScore = bool.Parse(musicScore.Attributes["isCustomNote"].Value);

            // Shop ID from currency items
            if (item["Shop"] != null)
            {
                XmlNode shop = item.SelectSingleNode("Shop");
                metadata.ShopID = int.Parse(shop.Attributes["systemShopID"].Value);
            }

            XmlNode skill = item.SelectSingleNode("skill");
            metadata.SkillID = int.Parse(skill.Attributes["skillID"].Value);

            XmlNode limit = item.SelectSingleNode("limit");
            metadata.EnableBreak = byte.Parse(limit.Attributes["enableBreak"].Value) == 1;
            metadata.Level = int.Parse(limit.Attributes["levelLimit"].Value);
            metadata.TransferType = (TransferType) byte.Parse(limit.Attributes["transferType"].Value);
            metadata.Sellable = byte.Parse(limit.Attributes["shopSell"].Value) == 1;
            metadata.RecommendJobs = limit.Attributes["recommendJobs"]?.Value.Split(",").Where(x => !string.IsNullOrEmpty(x)).Select(int.Parse).ToList();
            metadata.Gender = (Gender) byte.Parse(limit.Attributes["genderLimit"].Value);

            XmlNode installNode = item.SelectSingleNode("install");
            metadata.IsCubeSolid = byte.Parse(installNode.Attributes["cubeProp"].Value) == 1;
            metadata.ObjectId = int.Parse(installNode.Attributes["objCode"].Value);

            XmlNode housingNode = item.SelectSingleNode("housing");
            string value = housingNode.Attributes["categoryTag"]?.Value;
            if (value is not null)
            {
                List<string> categories = new(value.Split(","));
                _ = short.TryParse(categories[0], out short category);

                metadata.HousingCategory = (ItemHousingCategory) category;
            }

            // Item breaking ingredients
            if (rewards.ContainsKey(itemId))
            {
                metadata.BreakRewards = rewards[itemId];
            }

            // Item rarities
            if (rarities.ContainsKey(itemId))
            {
                metadata.Rarity = rarities[itemId];
            }

            // Item Names
            if (names.ContainsKey(itemId))
            {
                metadata.Name = names[itemId];
            }

            items.Add(metadata);
        }
        return items;
    }

19 Source : GachaParser.cs
with GNU General Public License v3.0
from AlanMorel

protected override List<GachaMetadata> Parse()
    {
        Dictionary<int, List<GachaContent>> gachaContent = new();
        foreach (PackFileEntry entry in Resources.XmlReader.Files)
        {
            if (!entry.Name.StartsWith("table/individualitemdrop_newgacha")) // Capsules
            {
                continue;
            }

            XmlDoreplacedent doreplacedent = Resources.XmlReader.GetXmlDoreplacedent(entry);
            XmlNodeList nodes = doreplacedent.SelectNodes("/ms2/individualDropBox");

            foreach (XmlNode node in nodes)
            {
                GachaContent metadata = new()
                {
                    ItemId = int.Parse(node.Attributes["item"].Value),
                    SmartDrop = byte.Parse(node.Attributes["smartDropRate"].Value),
                    SmartGender = bool.Parse(node.Attributes["isApplySmartGenderDrop"]?.Value ?? "false"),
                    MinAmount = short.Parse(node.Attributes["minCount"].Value),
                    MaxAmount = short.Parse(node.Attributes["maxCount"].Value),
                    Rarity = byte.Parse(node.Attributes["PackageUIShowGrade"].Value)
                };

                string individualDropBoxId = node.Attributes["individualDropBoxID"].Value;
                if (gachaContent.ContainsKey(int.Parse(individualDropBoxId)))
                {
                    gachaContent[int.Parse(individualDropBoxId)].Add(metadata);
                }
                else
                {
                    gachaContent[int.Parse(individualDropBoxId)] = new()
                    {
                        metadata
                    };
                }
            }
        }

        List<GachaMetadata> gacha = new();
        foreach (PackFileEntry entry in Resources.XmlReader.Files)
        {

            if (!entry.Name.StartsWith("table/gacha_info"))
            {
                continue;
            }

            XmlDoreplacedent doreplacedent = Resources.XmlReader.GetXmlDoreplacedent(entry);
            foreach (XmlNode node in doreplacedent.DoreplacedentElement.ChildNodes)
            {
                if (node.Name != "randomBox")
                {
                    continue;
                }

                int dropBoxId = int.Parse(node.Attributes["individualDropBoxID"].Value);
                _ = int.TryParse(node.Attributes["shopID"]?.Value ?? "0", out int shopId);
                _ = int.TryParse(node.Attributes["coinItemID"]?.Value ?? "0", out int coinItemId);
                _ = byte.TryParse(node.Attributes["coinItemAmount"]?.Value ?? "0", out byte coinAmount);

                GachaMetadata metadata = new()
                {
                    GachaId = int.Parse(node.Attributes["randomBoxID"].Value),
                    BoxGroup = byte.Parse(node.Attributes["randomBoxGroup"].Value),
                    DropBoxId = dropBoxId,
                    ShopId = shopId,
                    CoinId = coinItemId,
                    CoinAmount = coinAmount
                };

                if (gachaContent.ContainsKey(dropBoxId))
                {
                    metadata.Contents = gachaContent[dropBoxId];
                }

                gacha.Add(metadata);
            }
        }
        return gacha;
    }

19 Source : CourtSystem.cs
with GNU General Public License v3.0
from Albo1125

private static void LoadCourtCasesFromXMLFile(string File)
        {
            try
            {
                XDoreplacedent xdoc = XDoreplacedent.Load(File);
                char[] trim = new char[] { '\'', '\"', ' ' };
                List<CourtCase> AllCourtCases = xdoc.Descendants("CourtCase").Select(x => new CourtCase()
                {
                    SuspectName = ((string)x.Element("SuspectName").Value).Trim(trim),
                    SuspectDOB = DateTime.FromBinary(long.Parse(x.Element("SuspectDOB").Value)),
                    Crime = ((string)x.Element("Crime").Value).Trim(trim),
                    CrimeDate = DateTime.FromBinary(long.Parse(x.Element("CrimeDate").Value)),
                    GuiltyChance = int.Parse(x.Element("GuiltyChance") != null ?  ((string)x.Element("GuiltyChance").Value).Trim(trim) : "100"),
                    CourtVerdict = ((string)x.Element("CourtVerdict").Value).Trim(trim),
                    ResultsPublishTime = DateTime.FromBinary(long.Parse(x.Element("ResultsPublishTime").Value)),
                    ResultsPublished = bool.Parse(((string)x.Element("Published").Value).Trim(trim)),
                    ResultsPublishedNotificationShown = bool.Parse(((string)x.Element("ResultsPublishedNotificationShown").Value).Trim(trim))

                }).ToList<CourtCase>();

                foreach (CourtCase courtcase in AllCourtCases)
                {
                    courtcase.AddToCourtsMenuAndLists();
                }

            }
            catch (System.Threading.ThreadAbortException e) { }
            catch (Exception e)
            {
                Game.LogTrivial("LSPDFR+ encountered an exception reading \'" + File + "\'. It was: " + e.ToString());
                Game.DisplayNotification("~r~LSPDFR+: Error reading CourtCases.xml. Setting default values.");
            }
            finally
            {
                LoadingXMLFileCases = false;
            }


        }

19 Source : DisplayHandler.cs
with GNU General Public License v3.0
from Albo1125

private static List<ButtonPage> SetupButtonPage(string file)
        {
            int ItemCount = 1;
            int Page = 1;
            List<Button> AllButtons = new List<Button>();

            try
            {
                if(!File.Exists(file))
                {
                    generateButtonXML(file);
                    firstTimeLaunch = true;
                }
                XDoreplacedent xdoc = XDoreplacedent.Load(file);
                
                foreach (XElement x in xdoc.Root.Descendants("Button"))
                {
                    if (!string.IsNullOrWhiteSpace((string)x.Element("Plugin")) && !string.IsNullOrWhiteSpace((string)x.Element("Name")) && !string.IsNullOrWhiteSpace((string)x.Element("Enabled")))
                    {
                        Button b = new Button(x.Element("Plugin").Value, x.Element("Name").Value, ItemCount, bool.Parse(x.Element("Enabled").Value));
                        if (!AllButtons.Contains(b))
                        {
                            AllButtons.Add(b);
                            ItemCount++;
                            if (ItemCount > ButtonsPerPage)
                            {
                                Page++;
                                ItemCount = 1;
                            }
                        }

                    }
                    else
                    {
                        Game.LogTrivial("PoliceSmartRadio: button in " + file + " has no Plugin or Name. Skipping.");
                    }
                    
                }
                Game.LogTrivial("Allbuttons ln: " + AllButtons.Count);
            }
            catch (Exception e)
            {
                Game.LogTrivial(e.ToString());
            }

            List<ButtonPage> ButtonsPages = new List<ButtonPage>();
            int addingToPage = 0;
            int itemsOnPage = 0;
            foreach (Button b in AllButtons)
            {
                if (ButtonsPages.Count <= addingToPage)
                {
                    ButtonsPages.Add(new ButtonPage());
                }
                ButtonsPages[addingToPage].Buttons.Add(b);
                itemsOnPage++;
                if (itemsOnPage == ButtonsPerPage)
                {
                    addingToPage++;
                    itemsOnPage = 0;
                }
            }
            AllButtonPages.AddRange(ButtonsPages);
            if (ButtonsPages.Count == 0) { ButtonsPages.Add(new ButtonPage()); }
            return ButtonsPages;           
        }

19 Source : TrafficPolicerHandler.cs
with GNU General Public License v3.0
from Albo1125

private static void loadValuesFromIniFile()
        {
            try
            {
                drunkDriverChance = Int32.Parse(getDrunkDriverChance()) + 1;
                mobilePhoneChance = initialiseFile().ReadInt32("Ambient Event Chances", "MobilePhone", 100) + 1;
                speederChance = Int32.Parse(getSpeederChance()) + 1;
                drugDriverChance = initialiseFile().ReadInt32("Ambient Event Chances", "DrugDriver", 140) + 1;
                noLightAtDarkChance = initialiseFile().ReadInt32("Ambient Event Chances", "NoLightsAtDark", 110) + 1;
                noBrakeLightsChance = initialiseFile().ReadInt32("Ambient Event Chances", "NoBrakeLights", 150) + 1;
                BrokenDownVehicleChance = initialiseFile().ReadInt32("Ambient Event Chances", "BrokenDownVehicle", 220) + 1;
                BurnoutWhenStationaryChance = initialiseFile().ReadInt32("Ambient Event Chances", "BurnoutWhenStationary", 190) + 1;
                RevEngineWhenStationaryChance = initialiseFile().ReadInt32("Ambient Event Chances", "RevEngineWhenStationary", 190) + 1;
                NumberOfAmbientEventsBeforeTimer = initialiseFile().ReadInt32("Ambient Event Chances", "NumberOfAmbientEventsBeforeTimer");
                if (NumberOfAmbientEventsBeforeTimer < 1) { NumberOfAmbientEventsBeforeTimer = 1; }
                motorcyclistWithoutHelmetChance = Int32.Parse(getMotorcyclistWithoutHelmetChance()) + 1;
                unroadworthyVehicleChance = Int32.Parse(getUnroadworthyVehicleChance()) + 1;
                streetRaceChance = Int32.Parse(getStreetRaceChance()) + 1;
                getStolenVehicleChance();
                blipStatus = bool.Parse(getBlipStatus());
                showAmbientEventDescriptionMessage = bool.Parse(getShowAmbientEventDescriptionMessage());
                parkingTicketKey = (Keys)kc.ConvertFromString(getParkingTicketKey());
                trafficStopFollowKey = (Keys)kc.ConvertFromString(getTrafficStopFollowKey());

                parkModifierKey = (Keys)kc.ConvertFromString(getParkModifierKey());
                trafficStopFollowModifierKey = (Keys)kc.ConvertFromString(getTrafficStopFollowModifierKey());
                roadManagementMenuKey = (Keys)kc.ConvertFromString(getRoadManagementMenuKey());
                drugsTestKey = (Keys)kc.ConvertFromString(initialiseFile().ReadString("Keybindings", "DrugalyzerKey", "O"));
                drugsTestModifierKey = (Keys)kc.ConvertFromString(initialiseFile().ReadString("Keybindings", "DrugalyzerModifierKey", "LControlKey"));
                trafficStopMimicKey = (Keys)kc.ConvertFromString(initialiseFile().ReadString("Keybindings", "TrafficStopMimicKey"));
                trafficStopMimicModifierKey = (Keys)kc.ConvertFromString(initialiseFile().ReadString("Keybindings", "TrafficStopMimicModifierKey"));
                RoadManagementModifierKey = (Keys)kc.ConvertFromString(initialiseFile().ReadString("Keybindings", "RoadManagementMenuModifierKey", "None"));
                RepairVehicleKey = (Keys)kc.ConvertFromString(initialiseFile().ReadString("Keybindings", "RepairBrokenDownVehicleKey", "T"));
                RoadSigns.placeSignShortcutKey = (Keys)kc.ConvertFromString(initialiseFile().ReadString("Keybindings", "PlaceSignShortcutKey", "J"));
                RoadSigns.placeSignShortcutModifierKey = (Keys)kc.ConvertFromString(initialiseFile().ReadString("Keybindings", "PlaceSignShortcutModifierKey", "LControlKey"));
                RoadSigns.removeAllSignsKey = (Keys)kc.ConvertFromString(initialiseFile().ReadString("Keybindings", "RemoveAllSignsKey", "J"));
                RoadSigns.removeAllSignsModifierKey = (Keys)kc.ConvertFromString(initialiseFile().ReadString("Keybindings", "RemoveAllSignsModifierKey", "None"));

                SpeedChecker.ToggleSpeedCheckerKey = (Keys)kc.ConvertFromString(initialiseFile().ReadString("Speed Checker Settings", "ToggleSpeedCheckerKey"));
                SpeedChecker.ToggleSpeedCheckerModifierKey = (Keys)kc.ConvertFromString(initialiseFile().ReadString("Speed Checker Settings", "ToggleSpeedCheckerModifierKey"));
                SpeedChecker.SpeedUnit = initialiseFile().ReadString("Speed Checker Settings", "SpeedUnit");
                if (SpeedChecker.SpeedUnit != "MPH" && SpeedChecker.SpeedUnit != "KMH")
                {
                    SpeedChecker.SpeedUnit = "MPH";
                }

                SpeedChecker.speedgunWeapon = initialiseFile().ReadString("Speed Checker Settings", "SpeedgunWeaponreplacedet", "WEAPON_MARKSMANPISTOL");

                SpeedChecker.PositionUpKey = (Keys)kc.ConvertFromString(initialiseFile().ReadString("Speed Checker Settings", "PositionUpKey", "NumPad9"));
                SpeedChecker.PositionRightKey = (Keys)kc.ConvertFromString(initialiseFile().ReadString("Speed Checker Settings", "PositionRightKey", "NumPad6"));
                SpeedChecker.PositionResetKey = (Keys)kc.ConvertFromString(initialiseFile().ReadString("Speed Checker Settings", "PositionResetKey", "NumPad5"));
                SpeedChecker.PositionLeftKey = (Keys)kc.ConvertFromString(initialiseFile().ReadString("Speed Checker Settings", "PositionLeftKey", "NumPad4"));
                SpeedChecker.PositionForwardKey = (Keys)kc.ConvertFromString(initialiseFile().ReadString("Speed Checker Settings", "PositionForwardKey", "NumPad8"));
                SpeedChecker.PositionDownKey = (Keys)kc.ConvertFromString(initialiseFile().ReadString("Speed Checker Settings", "PositionDownKey", "NumPad3"));
                SpeedChecker.PositionBackwardKey = (Keys)kc.ConvertFromString(initialiseFile().ReadString("Speed Checker Settings", "PositionBackwardKey", "NumPad2"));
                SpeedChecker.SecondaryDisableKey = (Keys)kc.ConvertFromString(initialiseFile().ReadString("Speed Checker Settings", "SecondaryDisableKey", "Back"));
                SpeedChecker.MaxSpeedUpKey = (Keys)kc.ConvertFromString(initialiseFile().ReadString("Speed Checker Settings", "MaxSpeedUpKey", "PageUp"));
                SpeedChecker.MaxSpeedDownKey = (Keys)kc.ConvertFromString(initialiseFile().ReadString("Speed Checker Settings", "MaxSpeedDownKey", "PageDown"));
                SpeedChecker.FlagChance = initialiseFile().ReadInt32("Speed Checker Settings", "BringUpFlagChance");
                if (SpeedChecker.FlagChance < 1) { SpeedChecker.FlagChance = 1; }
                else if (SpeedChecker.FlagChance > 100) { SpeedChecker.FlagChance = 100; }
                SpeedChecker.SpeedToColourAt = initialiseFile().ReadInt32("Speed Checker Settings", "SpeedToColourAt");
                SpeedChecker.PlayFlagBlip = initialiseFile().ReadBoolean("Speed Checker Settings", "PlayFlagBlip");

                SpeedChecker.StartStopAverageSpeedCheckKey = (Keys)kc.ConvertFromString(initialiseFile().ReadString("Speed Checker Settings", "StartStopAverageSpeedCheckKey", "PageUp"));
                SpeedChecker.ResetAverageSpeedCheckKey = (Keys)kc.ConvertFromString(initialiseFile().ReadString("Speed Checker Settings", "ResetAverageSpeedCheckKey", "PageDown"));
                DUIEnabled = initialiseFile().ReadBoolean("Callouts", "DriverUnderTheInfluenceEnabled");
                DUIFrequency = initialiseFile().ReadInt32("Callouts", "DriverUnderTheInfluenceFrequency");

                //MimickMeDistanceModifier = initialiseFile().ReadSingle("Features", "MimickMeDistanceModifier", 19f);
                TrafficStopreplacedist.VehicleDoorLockDistance = initialiseFile().ReadSingle("Features", "VehicleDoorLockDistance", 5.2f);
                TrafficStopreplacedist.VehicleDoorUnlockDistance = initialiseFile().ReadSingle("Features", "VehicleDoorUnlockDistance", 3.5f);
                AutoVehicleDoorLock = initialiseFile().ReadBoolean("Features", "AutoVehicleDoorLock", true);
                OtherUnitRespondingAudio = initialiseFile().ReadBoolean("Features", "OtherUnitRespondingAudio", true);

                CustomPulloverLocationKey = (Keys)kc.ConvertFromString(initialiseFile().ReadString("Keybindings", "CustomPulloverLocationKey", "W"));
                CustomPulloverLocationModifierKey = (Keys)kc.ConvertFromString(initialiseFile().ReadString("Keybindings", "CustomPulloverLocationModifierKey", "LControlKey"));

                markMapKey = (Keys)kc.ConvertFromString(getMarkMapKey());
                courtKey = (Keys)kc.ConvertFromString(getCourtKey());
                dispatchCautionMessages = initialiseFile().ReadBoolean("Callouts", "DispatchCautionMessages", true);
                VehicleDetails.AutomaticDetailsChecksEnabledBaseSetting = initialiseFile().ReadBoolean("Features", "VehicleDetailsChecksEnabled");
                ownerWantedCalloutEnabled = bool.Parse(getOwnerWantedCallout());
                ownerWantedFrequency = ownerWantedFrequent();
                drugsRunnersEnabled = bool.Parse(getDrugsRunnersCallout());
                drugsRunnersFrequency = drugsRunnersFrequent();

                Impairment_Tests.Breathalyzer.BreathalyzerKey = (Keys)kc.ConvertFromString(initialiseFile().ReadString("Breathalyzer Settings", "BreathalyzerKey"));
                Impairment_Tests.Breathalyzer.BreathalyzerModifierKey = (Keys)kc.ConvertFromString(initialiseFile().ReadString("Breathalyzer Settings", "BreathalyzerModifierKey"));
                Impairment_Tests.Breathalyzer.AlcoholLimit = initialiseFile().ReadSingle("Breathalyzer Settings", "AlcoholLimit");
                Impairment_Tests.Breathalyzer.AlcoholLimitUnit = initialiseFile().ReadString("Breathalyzer Settings", "AlcoholLimitUnit");

                FailToProvideChance = initialiseFile().ReadInt32("Breathalyzer Settings", "FailToProvideChance", 7);

                getNextEventTimer();

                DetermineUnitBeatStrings();

            }
            catch (Exception e)
            {
                drunkDriverChance = 190;
                mobilePhoneChance = 95;
                speederChance = 90;
                unroadworthyVehicleChance = 200;
                motorcyclistWithoutHelmetChance = 180;
                streetRaceChance = 250;
                stolenVehicleChance = 190;
                drugDriverChance = 140;
                noLightAtDarkChance = 120;
                blipStatus = true;
                showAmbientEventDescriptionMessage = false;
                parkingTicketKey = Keys.E;
                trafficStopFollowKey = Keys.T;

                roadManagementMenuKey = Keys.F6;
                parkModifierKey = Keys.LControlKey;
                drugsTestKey = Keys.O;
                drugsTestModifierKey = Keys.LControlKey;
                trafficStopFollowModifierKey = Keys.LControlKey;

                markMapKey = Keys.D9;
                courtKey = Keys.D0;
                RoadManagementModifierKey = Keys.None;
                nextEventTimer = 15000;

                dispatchCautionMessages = true;
                ownerWantedCalloutEnabled = true;
                ownerWantedFrequency = 3;
                trafficStopMimicKey = Keys.R;
                trafficStopMimicModifierKey = Keys.LControlKey;
                Game.LogTrivial(e.ToString());
                Game.LogTrivial("Loading default Traffic Policer INI file - Error detected in user's INI file.");
                Game.DisplayNotification("~r~~h~Error~s~ reading Traffic Policer ini file. Default values set; replace with default INI file!");
                Albo1125.Common.CommonLibrary.ExtensionMethods.DisplayPopupTextBoxWithConfirmation("Traffic Policer INI file", "Error reading Traffic Policer INI file. To fix this, replace your current INI file with the original one from the download. Loading default values...", true);

            }

        }

19 Source : VectorLayerVisualizer.cs
with MIT License
from alen-smajic

private bool IsFeatureValid(VectorFeatureUnity feature)
		{
			if (feature.Properties.ContainsKey("extrude") && !bool.Parse(feature.Properties["extrude"].ToString()))
				return false;

			if (feature.Points.Count < 1)
				return false;

			return true;
		}

19 Source : LocationLogReader.cs
with MIT License
from alen-smajic

public IEnumerator<Location> GetLocations()
		{

			while (true)
			{
				string line = string.Empty;

				while (1 == 1)
				{
					line = _textReader.ReadLine();
					// rewind if end of log (or last empty line) reached
					if (null == line || string.IsNullOrEmpty(line))
					{
						((StreamReader)_textReader).BaseStream.Position = 0;
						((StreamReader)_textReader).DiscardBufferedData();
						continue;
					}

					// skip comments
					if (line.StartsWith("#")) { continue; } else { break; }
				}

				string[] tokens = line.Split(Delimiter.ToCharArray());
				//simple safety net: check if number of columns matches
				if (tokens.Length != HeaderNames.Length)
				{
					Debug.LogError("unsupported log file");
					yield return new Location();
				}

				Location location = new Location();

				location.IsLocationServiceEnabled = bool.Parse(tokens[(int)LogfileColumns.LocationServiceEnabled]);
				location.IsLocationServiceInitializing = bool.Parse(tokens[(int)LogfileColumns.LocationServiceInitializing]);
				location.IsLocationUpdated = bool.Parse(tokens[(int)LogfileColumns.LocationUpdated]);
				location.IsUserHeadingUpdated = bool.Parse(tokens[(int)LogfileColumns.UserHeadingUpdated]);
				location.Provider = tokens[(int)LogfileColumns.LocationProvider];
				location.ProviderClreplaced = tokens[(int)LogfileColumns.LocationProviderClreplaced];

				DateTime dtDevice;
				string dtDeviceTxt = tokens[(int)LogfileColumns.UtcTimeDevice];
				if (DateTime.TryParseExact(dtDeviceTxt, "yyyyMMdd-HHmmss.fff", _invariantCulture, DateTimeStyles.replacedumeUniversal, out dtDevice))
				{
					location.TimestampDevice = UnixTimestampUtils.To(dtDevice);
				}

				DateTime dtLocation;
				string dtLocationTxt = tokens[(int)LogfileColumns.UtcTimeOfLocation];
				if (DateTime.TryParseExact(dtLocationTxt, "yyyyMMdd-HHmmss.fff", _invariantCulture, DateTimeStyles.replacedumeUniversal, out dtLocation))
				{
					location.Timestamp = UnixTimestampUtils.To(dtLocation);
				}

				double lat;
				string latTxt = tokens[(int)LogfileColumns.Lareplacedude];
				double lng;
				string lngTxt = tokens[(int)LogfileColumns.Longitude];
				if (
					!double.TryParse(latTxt, NumberStyles.Any, _invariantCulture, out lat)
					|| !double.TryParse(lngTxt, NumberStyles.Any, _invariantCulture, out lng)
				)
				{
					location.LareplacedudeLongitude = Vector2d.zero;
				}
				else
				{
					location.LareplacedudeLongitude = new Vector2d(lat, lng);
				}


				float accuracy;
				location.Accuracy = float.TryParse(tokens[(int)LogfileColumns.Accuracy], NumberStyles.Any, _invariantCulture, out accuracy) ? accuracy : 0;
				float userHeading;
				location.UserHeading = float.TryParse(tokens[(int)LogfileColumns.UserHeading], NumberStyles.Any, _invariantCulture, out userHeading) ? userHeading : 0;
				float deviceOrientation;
				location.DeviceOrientation = float.TryParse(tokens[(int)LogfileColumns.DeviceOrientation], NumberStyles.Any, _invariantCulture, out deviceOrientation) ? deviceOrientation : 0;
				float speed;
				location.SpeedMetersPerSecond = float.TryParse(tokens[(int)LogfileColumns.Speed], NumberStyles.Any, _invariantCulture, out speed) ? speed / 3.6f : (float?)null;
				bool hasGpsFix;
				location.HasGpsFix = bool.TryParse(tokens[(int)LogfileColumns.HasGpsFix], out hasGpsFix) ? hasGpsFix : (bool?)null;
				int satellitesUsed;
				location.SatellitesUsed = int.TryParse(tokens[(int)LogfileColumns.SatellitesUsed], out satellitesUsed) ? satellitesUsed : (int?)null;
				int satellitesInView;
				location.SatellitesInView = int.TryParse(tokens[(int)LogfileColumns.SatellitesInView], out satellitesInView) ? satellitesInView : (int?)null;

				yield return location;
			}
		}

19 Source : ProgramSettings.cs
with MIT License
from AlexanderPro

public static ProgramSettings Read(string fileName)
        {
            var doreplacedent = XDoreplacedent.Load(fileName);
            var settings = new ProgramSettings();
            settings.ListerFormKey1 = int.Parse(doreplacedent.XPathSelectElement("//Settings/ListerFormHotKeys").Attribute("key1").Value);
            settings.ListerFormKey2 = int.Parse(doreplacedent.XPathSelectElement("//Settings/ListerFormHotKeys").Attribute("key2").Value);
            settings.ListerFormKey3 = int.Parse(doreplacedent.XPathSelectElement("//Settings/ListerFormHotKeys").Attribute("key3").Value);
            settings.SearchDialogKey1 = int.Parse(doreplacedent.XPathSelectElement("//Settings/SearchDialogHotKeys").Attribute("key1").Value);
            settings.SearchDialogKey2 = int.Parse(doreplacedent.XPathSelectElement("//Settings/SearchDialogHotKeys").Attribute("key2").Value);
            settings.SearchDialogKey3 = int.Parse(doreplacedent.XPathSelectElement("//Settings/SearchDialogHotKeys").Attribute("key3").Value);
            settings.PrintDialogKey1 = int.Parse(doreplacedent.XPathSelectElement("//Settings/PrintDialogHotKeys").Attribute("key1").Value);
            settings.PrintDialogKey2 = int.Parse(doreplacedent.XPathSelectElement("//Settings/PrintDialogHotKeys").Attribute("key2").Value);
            settings.PrintDialogKey3 = int.Parse(doreplacedent.XPathSelectElement("//Settings/PrintDialogHotKeys").Attribute("key3").Value);
            settings.ListerFormMaximized = bool.Parse(doreplacedent.XPathSelectElement("//Settings/ListerForm").Attribute("maximized").Value);
            settings.ListerFormWidth = int.Parse(doreplacedent.XPathSelectElement("//Settings/ListerForm").Attribute("width").Value);
            settings.ListerFormHeight = int.Parse(doreplacedent.XPathSelectElement("//Settings/ListerForm").Attribute("height").Value);
            settings.PluginHighVersion = int.Parse(doreplacedent.XPathSelectElement("//Settings/PluginDefaultSettings").Attribute("highVersion").Value);
            settings.PluginLowVersion = int.Parse(doreplacedent.XPathSelectElement("//Settings/PluginDefaultSettings").Attribute("lowVersion").Value);
            settings.PluginIniFile = doreplacedent.XPathSelectElement("//Settings/PluginDefaultSettings").Attribute("iniFile").Value;
            settings.PluginIniFile = new FileInfo(settings.PluginIniFile).FullName;
            settings.Plugins = doreplacedent.XPathSelectElements("//Settings/Plugins/Plugin").Select(el => new PluginInfo(el.Attribute("path").Value,
                                                                                                                     string.IsNullOrWhiteSpace(el.Attribute("extensions").Value) ? new List<string>() :
                                                                                                                                                                              el.Attribute("extensions").Value.Split(';').ToList())).ToList();
            return settings;
        }

19 Source : AssociationRelationship.cs
with GNU General Public License v3.0
from alexgracianoarj

protected internal override void Deserialize(XmlElement node)
		{
			base.Deserialize(node);

			XmlElement child = node["Direction"];

			RaiseChangedEvent = false;
			if (child != null)
			{                                              // Old file format
				if (child.InnerText == "Unidirectional" || child.InnerText == "SourceDestination")
					Direction = Direction.Unidirectional;
				else
					Direction = Direction.Bidirectional;
			}

			try
			{
				// Old file format
				{
					child = node["IsAggregation"];
					if (child != null && bool.Parse(child.InnerText))
						replacedociationType = replacedociationType.Aggregation;

					child = node["IsComposition"];
					if (child != null && bool.Parse(child.InnerText))
						replacedociationType = replacedociationType.Composition;
				}

				child = node["replacedociationType"];
				if (child != null)
				{
					if (child.InnerText == "Aggregation")
						replacedociationType = replacedociationType.Aggregation;
					else if (child.InnerText == "Composition")
						replacedociationType = replacedociationType.Composition;
					else
						replacedociationType = replacedociationType.replacedociation;
				}

				child = node["StartRole"];
				if (child != null)
					startRole = child.InnerText;

				child = node["EndRole"];
				if (child != null)
					endRole = child.InnerText;

				child = node["StartMultiplicity"];
				if (child != null)
					startMultiplicity = child.InnerText;

				child = node["EndMultiplicity"];
				if (child != null)
					endMultiplicity = child.InnerText;
			}
			catch (ArgumentException)
			{
				// Wrong format
			}
			RaiseChangedEvent = true;
		}

19 Source : FunctionExtensions.cs
with MIT License
from alfa-laboratory

public static object parseBool(string str)
        {
            try
            {
                return bool.Parse(str);
            }
            catch (FormatException ex)
            {
                Log.Logger().LogWarning($"Parsing string to bool return an error {ex.Message}.");
                return str;
            }
        }

19 Source : Reflection.cs
with MIT License
from alfa-laboratory

public static object ConvertObject(object obj, Type type)
        {
            var t = GetObjectType(type);

            if(obj == null)
            {
                return GetDefault(t);
            }

            if(t.IsEnum)
            {
                obj = Enum.Parse(t, obj is string value ? value : obj.ToString(), false);
            }

            if(t == typeof(string))
            {
                if(obj is string convertObject)
                {
                    return convertObject;
                }

                var mi = obj.GetType().GetMethods().SingleOrDefault(m => m.Name == "ToString" && !m.GetMethodParameters().Any());
                return mi?.Invoke(obj, Array.Empty<object>());
            }

            if((obj is string s) && t == typeof(char[]))
            {
                return s.Split();
            }

            if(t.IsArray)
            {
                if(obj is Array arrSrc)
                {
                    var arrDest = (Array)CreateArray(t.GetElementType(), arrSrc.Length);
                    Array.Copy(arrSrc, arrDest, arrSrc.Length);
                    return arrDest;
                }
            }

            if(t == typeof(object))
            {
                return obj;
            }

            if(obj is not string o)
            {
                return Convert.ChangeType(obj, t);
            }

            if(t == typeof(bool))
            {
                if(short.TryParse(o, out var i))
                {
                    return i != 0;
                }

                return bool.Parse(o);
            }

            if(t == typeof(decimal) || t == typeof(float))
            {
                var types = new[] { typeof(string), typeof(NumberStyles), typeof(IFormatProvider), t.MakeByRefType() };
                var args = new[] { o, NumberStyles.Any, new NumberFormatInfo { NumberDecimalSeparator = "," }, GetDefault(t) };

                if((bool)t.GetMethod("TryParse", types)?.Invoke(null, args)!)
                {
                    return args[3];
                }

                types = new[] { typeof(string), typeof(NumberStyles), typeof(IFormatProvider) };
                args = new object[] { o, NumberStyles.Any, new NumberFormatInfo { NumberDecimalSeparator = "." } };
                return t.GetMethod("Parse", types)?.Invoke(null, args);
            }

            if(t == typeof(long)
                || t == typeof(ulong)
                || t == typeof(int)
                || t == typeof(uint)
                || t == typeof(short)
                || t == typeof(ushort)
                || t == typeof(byte)
                || t == typeof(sbyte)
                || t == typeof(char))
            {
                return t.GetMethod("Parse", new[] { typeof(string) })?.Invoke(null, new object[] {o});
            }

            if(t == typeof(DateTime))
            {
                return DateTime.TryParse(o, CultureInfo.GetCultureInfo("ru-RU"), DateTimeStyles.replacedumeLocal, out var dt) ? dt : DateTime.Parse(o, CultureInfo.GetCultureInfo("en-US"), DateTimeStyles.replacedumeLocal);
            }

            return Convert.ChangeType(o, t);
        }

19 Source : ServiceCollectionExtensions.cs
with MIT License
from alirizaadiyahsi

public static void ConfigureSmtp(this IServiceCollection services, IConfiguration configuration)
        {
            services.AddScoped(serviceProvider => new SmtpClient
            {
                Host = configuration["Email:Smtp:Host"],
                Port = int.Parse(configuration["Email:Smtp:Port"]),
                Credentials = new NetworkCredential(configuration["Email:Smtp:Username"], configuration["Email:Smtp:Preplacedword"]),
                EnableSsl = bool.Parse(configuration["Email:Smtp:EnableSsl"])
            });
        }

19 Source : RatAttack.cs
with GNU General Public License v3.0
from alterNERDtive

public void ParseString(string serialization)
            {
                try
                {
                    string[] parts = serialization.Split(separator);
                    Signal = parts[0];
                    Announce = Boolean.Parse(parts[1]);
                }
                catch (Exception e)
                {
                    throw new ArgumentException($"Invalid serialized RATSIGNAL: '{serialization}'", e);
                }
            }

19 Source : InstanceRepository.cs
with BSD 3-Clause "New" or "Revised" License
from Altinn

private static IQueryable<Instance> BuildQueryFromParameters(Dictionary<string, StringValues> queryParams, IQueryable<Instance> queryBuilder)
        {
            foreach (KeyValuePair<string, StringValues> param in queryParams)
            {
                string queryParameter = param.Key;
                StringValues queryValues = param.Value;

                if (queryParameter.Equals("appId"))
                {
                    queryBuilder = queryBuilder.Where(i => queryValues.Contains(i.AppId));
                    continue;
                }

                if (queryParameter.Equals("instanceOwner.partyId"))
                {
                    queryBuilder = queryBuilder.Where(i => queryValues.Contains(i.InstanceOwner.PartyId));
                    continue;
                }

                foreach (string queryValue in queryValues)
                {
                    switch (queryParameter)
                    {
                        case "size":
                        case "continuationToken":
                            // handled outside this method, it is a valid parameter.
                            break;
                        case "org":
                            queryBuilder = queryBuilder.Where(i => i.Org == queryValue);
                            break;
                        case "lastChanged":
                            queryBuilder = QueryBuilderForLastChangedDateTime(queryBuilder, queryValue);
                            break;

                        case "dueBefore":
                            queryBuilder = QueryBuilderForDueBefore(queryBuilder, queryValue);
                            break;

                        case "visibleAfter":
                            queryBuilder = QueryBuilderForVisibleAfter(queryBuilder, queryValue);
                            break;

                        case "created":
                            queryBuilder = QueryBuilderForCreated(queryBuilder, queryValue);
                            break;

                        case "process.currentTask":
                            queryBuilder = queryBuilder.Where(i => i.Process.CurrentTask.ElementId == queryValue);
                            break;

                        case "process.isComplete":
                            bool isComplete = bool.Parse(queryValue);
                            if (isComplete)
                            {
                                queryBuilder = queryBuilder.Where(i => i.Process.Ended != null);
                            }
                            else
                            {
                                queryBuilder = queryBuilder.Where(i => i.Process.CurrentTask != null);
                            }

                            break;

                        case "process.ended":
                            queryBuilder = QueryBuilderForEnded(queryBuilder, queryValue);
                            break;

                        case "excludeConfirmedBy":
                            queryBuilder = QueryBuilderExcludeConfirmedBy(queryBuilder, queryValue);
                            break;
                        case "language":
                            break;
                        case "status.isArchived":
                            bool isArchived = bool.Parse(queryValue);
                            queryBuilder = queryBuilder.Where(i => i.Status.IsArchived == isArchived);

                            break;
                        case "status.isSoftDeleted":
                            bool isSoftDeleted = bool.Parse(queryValue);
                            queryBuilder = queryBuilder.Where(i => i.Status.IsSoftDeleted == isSoftDeleted);

                            break;
                        case "status.isHardDeleted":
                            bool isHardDeleted = bool.Parse(queryValue);
                            queryBuilder = queryBuilder.Where(i => i.Status.IsHardDeleted == isHardDeleted);

                            break;
                        case "status.isArchivedOrSoftDeleted":
                            if (bool.Parse(queryValue))
                            {
                                queryBuilder = queryBuilder.Where(i => i.Status.IsArchived || i.Status.IsSoftDeleted);
                            }

                            break;
                        case "status.isActiveorSoftDeleted":
                            if (bool.Parse(queryValue))
                            {
                                queryBuilder = queryBuilder.Where(i => !i.Status.IsArchived || i.Status.IsSoftDeleted);
                            }

                            break;
                        case "sortBy":
                            queryBuilder = QueryBuilderForSortBy(queryBuilder, queryValue);

                            break;
                        case "archiveReference":
                            queryBuilder = queryBuilder.Where(i => i.Id.EndsWith(queryValue.ToLower()));

                            break;
                        default:
                            throw new ArgumentException($"Unknown query parameter: {queryParameter}");
                    }
                }
            }

            return queryBuilder;
        }

19 Source : MessageboxInstancesControllerTests.cs
with BSD 3-Clause "New" or "Revised" License
from Altinn

[Fact]
        public async void Search_IncludeActivedAndDeleted_OriginalQuerySuccesfullyConverted()
        {
            // Arrange
            Dictionary<string, StringValues> actual = new Dictionary<string, StringValues>();
            Mock<IInstanceRepository> instanceRepositoryMock = new Mock<IInstanceRepository>();
            instanceRepositoryMock
                .Setup(ir => ir.GetInstancesFromQuery(It.IsAny<Dictionary<string, StringValues>>(), It.IsAny<string>(), It.IsAny<int>()))
                .Callback<Dictionary<string, StringValues>, string, int>((query, cont, size) => { actual = query; })
                .ReturnsAsync((InstanceQueryResponse)null);

            int expectedParamCount = 4;

            HttpClient client = GetTestClient(instanceRepositoryMock);
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", PrincipalUtil.GetToken(3, 1606, 3));

            // Act
            HttpResponseMessage responseMessage = await client.GetAsync($"{BasePath}/sbl/instances/search?includeActive=true&includeDeleted=true&instanceOwner.partyId=1606");

            // replacedert
            replacedert.Equal(HttpStatusCode.OK, responseMessage.StatusCode);
            replacedert.True(actual.ContainsKey("instanceOwner.partyId"));
            actual.TryGetValue("status.isActiveOrSoftDeleted", out StringValues actualIsArchivedOrSoftDeleted);
            replacedert.True(bool.Parse(actualIsArchivedOrSoftDeleted.First()));
            replacedert.Equal(expectedParamCount, actual.Keys.Count);
        }

19 Source : MessageboxInstancesControllerTests.cs
with BSD 3-Clause "New" or "Revised" License
from Altinn

[Fact]
        public async void Search_ArchiveReferenceNoStateFilter_OriginalQuerySuccesfullyConverted()
        {
            // Arrange
            Dictionary<string, StringValues> actual = new Dictionary<string, StringValues>();
            Mock<IInstanceRepository> instanceRepositoryMock = new Mock<IInstanceRepository>();
            instanceRepositoryMock
                .Setup(ir => ir.GetInstancesFromQuery(It.IsAny<Dictionary<string, StringValues>>(), It.IsAny<string>(), It.IsAny<int>()))
                .Callback<Dictionary<string, StringValues>, string, int>((query, cont, size) => { actual = query; })
                .ReturnsAsync((InstanceQueryResponse)null);

            HttpClient client = GetTestClient(instanceRepositoryMock);
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", PrincipalUtil.GetToken(1, 1600, 3));

            // Act
            HttpResponseMessage responseMessage = await client.GetAsync($"{BasePath}/sbl/instances/search?instanceOwner.partyId=1600&archiveReference=bdb2a09da7ea");

            // replacedert
            replacedert.Equal(HttpStatusCode.OK, responseMessage.StatusCode);
            replacedert.True(actual.ContainsKey("instanceOwner.partyId"));
            actual.TryGetValue("status.isArchivedOrSoftDeleted", out StringValues actualIsArchivedOrSoftDeleted);
            replacedert.True(bool.Parse(actualIsArchivedOrSoftDeleted.First()));
        }

19 Source : MessageboxInstancesControllerTests.cs
with BSD 3-Clause "New" or "Revised" License
from Altinn

[Fact]
        public async void Search_ArchiveReferenceIncludeActiveAndSoftDeleted_OriginalQuerySuccesfullyConverted()
        {
            // Arrange
            Dictionary<string, StringValues> actual = new Dictionary<string, StringValues>();
            Mock<IInstanceRepository> instanceRepositoryMock = new Mock<IInstanceRepository>();
            instanceRepositoryMock
                .Setup(ir => ir.GetInstancesFromQuery(It.IsAny<Dictionary<string, StringValues>>(), It.IsAny<string>(), It.IsAny<int>()))
                .Callback<Dictionary<string, StringValues>, string, int>((query, cont, size) => { actual = query; })
                .ReturnsAsync((InstanceQueryResponse)null);

            HttpClient client = GetTestClient(instanceRepositoryMock);
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", PrincipalUtil.GetToken(1, 1600, 3));

            // Act
            HttpResponseMessage responseMessage = await client.GetAsync($"{BasePath}/sbl/instances/search?instanceOwner.partyId=1600&archiveReference=bdb2a09da7ea&includeActive=true&includeDeleted=true");

            // replacedert
            replacedert.Equal(HttpStatusCode.OK, responseMessage.StatusCode);
            replacedert.True(actual.ContainsKey("instanceOwner.partyId"));
            actual.TryGetValue("status.isSoftDeleted", out StringValues actualIsArchived);
            replacedert.True(bool.Parse(actualIsArchived.First()));
        }

19 Source : MessageboxInstancesControllerTests.cs
with BSD 3-Clause "New" or "Revised" License
from Altinn

[Fact]
        public async void Search_IncludeArchivedAndDeleted_OriginalQuerySuccesfullyConverted()
        {
            // Arrange
            Dictionary<string, StringValues> actual = new Dictionary<string, StringValues>();
            Mock<IInstanceRepository> instanceRepositoryMock = new Mock<IInstanceRepository>();
            instanceRepositoryMock
                .Setup(ir => ir.GetInstancesFromQuery(It.IsAny<Dictionary<string, StringValues>>(), It.IsAny<string>(), It.IsAny<int>()))
                .Callback<Dictionary<string, StringValues>, string, int>((query, cont, size) => { actual = query; })
                .ReturnsAsync((InstanceQueryResponse)null);

            int expectedParamCount = 4;
            string expectedSortBy = "desc:lastChanged";

            HttpClient client = GetTestClient(instanceRepositoryMock);
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", PrincipalUtil.GetToken(3, 1606, 3));

            // Act
            HttpResponseMessage responseMessage = await client.GetAsync($"{BasePath}/sbl/instances/search?includeArchived=true&includeDeleted=true&instanceOwner.partyId=1606");

            // replacedert
            replacedert.Equal(HttpStatusCode.OK, responseMessage.StatusCode);
            replacedert.True(actual.ContainsKey("instanceOwner.partyId"));
            actual.TryGetValue("status.isArchivedOrSoftDeleted", out StringValues actualIsArchivedOrSoftDeleted);
            replacedert.True(bool.Parse(actualIsArchivedOrSoftDeleted.First()));
            actual.TryGetValue("sortBy", out StringValues actualSortBy);
            replacedert.Equal(expectedSortBy, actualSortBy.First());
            replacedert.Equal(expectedParamCount, actual.Keys.Count);
        }

19 Source : LauncherUpdater.cs
with GNU General Public License v3.0
from AM2R-Community-Developers

public static void Main()
        {
            log.Info("Running update check...");

            string version = VERSION.Replace(".", "");

            //update section

            //delete old files that have been left
            if (File.Exists(CrossPlatformOperations.CURRENTPATH + "/AM2RLauncher.bak"))
            {
                log.Info("AM2RLauncher.bak detected. Removing file.");
                File.Delete(CrossPlatformOperations.CURRENTPATH + "/AM2RLauncher.bak");
            }
            if (currentPlatform.IsWinForms && File.Exists(oldConfigPath))
            {
                log.Info(CrossPlatformOperations.LAUNCHERNAME + ".oldCfg detected. Removing file.");
                File.Delete(oldConfigPath);
            }
            if (currentPlatform.IsWinForms && Directory.Exists(CrossPlatformOperations.CURRENTPATH + "/oldLib"))
            {
                log.Info("Old lib folder detected, removing folder.");
                Directory.Delete(CrossPlatformOperations.CURRENTPATH + "/oldLib", true);
            }

            // Clean up old update libs
            if (currentPlatform.IsWinForms && Directory.Exists(CrossPlatformOperations.CURRENTPATH + "/lib"))
            {
                foreach (FileInfo file in new DirectoryInfo(CrossPlatformOperations.CURRENTPATH + "/lib").GetFiles())
                {
                    if (file.Name.EndsWith(".bak"))
                        file.Delete();
                }

                // Do the same for each subdir
                foreach (DirectoryInfo dir in new DirectoryInfo(CrossPlatformOperations.CURRENTPATH + "/lib").GetDirectories())
                {
                    foreach (FileInfo file in dir.GetFiles())
                    {
                        if (file.Name.EndsWith(".bak"))
                            file.Delete();
                    }
                }
            }

            //check settings if autoUpdateLauncher is set to true
            bool autoUpdate = bool.Parse(CrossPlatformOperations.ReadFromConfig("AutoUpdateLauncher"));

            if (autoUpdate)
            {
                log.Info("AutoUpdate Launcher set to true!");

                //this is supposed to fix the updater throwing an exception on windows 7 and earlier(?)
                //see this for information: https://stackoverflow.com/questions/2859790/the-request-was-aborted-could-not-create-ssl-tls-secure-channel and https://stackoverflow.com/a/50977774
                if (currentPlatform.IsWinForms)
                {
                    ServicePointManager.Expect100Continue = true;
                    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
                }

                HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://github.com/AM2R-Community-Developers/AM2RLauncher/releases/latest");
                HttpWebResponse response = null;
                try
                {        
                    response = (HttpWebResponse)request.GetResponse();
                }
                catch (WebException)
                {
                    log.Error("WebException caught! Displaying MessageBox.");
                    MessageBox.Show(Language.Text.NoInternetConnection);
                    return;
                }

                Uri realUri = response.ResponseUri;
                string onlineVersion = realUri.AbsoluteUri.Substring(realUri.AbsoluteUri.LastIndexOf('/') + 1);
                bool isCurrentVersionOutdated = false;

                string[] localVersionArray = VERSION.Split('.');
                string[] onlineVersionArray = onlineVersion.Split('.');

                for (int i = 0; i < localVersionArray.Length; i++)
                {
                    if (int.Parse(onlineVersionArray[i]) > int.Parse(localVersionArray[i]))
                    {
                        isCurrentVersionOutdated = true;
                        break;
                    }
                }

                if (isCurrentVersionOutdated)
                {
                    log.Info("Current version (" + VERSION + ") is outdated! Initiating update for version " + onlineVersion + ".");

                    string tmpUpdatePath = CrossPlatformOperations.CURRENTPATH + "/tmpupdate/";
                    string zipPath = CrossPlatformOperations.CURRENTPATH + "/launcher.zip";

                    // Clean tmpupdate
                    if (Directory.Exists(tmpUpdatePath))
                        Directory.Delete(tmpUpdatePath);
                    if (!Directory.Exists(tmpUpdatePath))
                        Directory.CreateDirectory(tmpUpdatePath);

                    try
                    { 
                        using (var client = new WebClient())
                        {
                            string platformSuffix = "";
                            if (currentPlatform.IsWinForms) platformSuffix = "_win";
                            else if (currentPlatform.IsGtk) platformSuffix = "_lin";

                            log.Info("Downloading https://github.com/AM2R-Community-Developers/AM2RLauncher/releases/latest/download/AM2RLauncher_" + onlineVersion + platformSuffix + ".zip to " + zipPath + ".");
                            
                            client.DownloadFile("https://github.com/AM2R-Community-Developers/AM2RLauncher/releases/latest/download/AM2RLauncher_" + onlineVersion + platformSuffix + ".zip", zipPath);

                            log.Info("File successfully downloaded.");
                        }
                    }
                    catch(UnauthorizedAccessException)
                    {
                        log.Error("UnauthorizedAccessException caught! Displaying MessageBox.");
                        MessageBox.Show(Language.Text.UnauthorizedAccessMessage);
                        return;
                    }

                    ZipFile.ExtractToDirectory(zipPath, tmpUpdatePath);
                    log.Info("Updates successfully extracted to " + tmpUpdatePath);

                    File.Delete(zipPath);
                    File.Move(updatePath + "/" + CrossPlatformOperations.LAUNCHERNAME, CrossPlatformOperations.CURRENTPATH + "/AM2RLauncher.bak");
                    if (currentPlatform.IsWinForms) File.Move(CrossPlatformOperations.LAUNCHERNAME + ".config", CrossPlatformOperations.LAUNCHERNAME + ".oldCfg");

                    foreach (var file in new DirectoryInfo(tmpUpdatePath).GetFiles())
                    {
                        log.Info("Moving " +  file.FullName + " to " + CrossPlatformOperations.CURRENTPATH + "/" + file.Name);
                        File.Copy(file.FullName, updatePath + "/" + file.Name, true);
                    }
                    // for windows, the actual application is in "AM2RLauncher.dll". Which means, we need to update the lib folder as well.
                    if (currentPlatform.IsWinForms && Directory.Exists(CrossPlatformOperations.CURRENTPATH + "/lib"))
                    {
                        // Directory.Move(CrossPlatformOperations.CURRENTPATH + "/lib", CrossPlatformOperations.CURRENTPATH + "/oldLib");
                        // So, because Windows behavior is dumb...

                        // Rename all files in lib to *.bak
                        foreach (FileInfo file in new DirectoryInfo(CrossPlatformOperations.CURRENTPATH + "/lib").GetFiles())
                        {
                            file.CopyTo(file.Directory + file.Name + ".bak");
                        }

                        // Do the same for each subdir
                        foreach(DirectoryInfo dir in new DirectoryInfo(CrossPlatformOperations.CURRENTPATH + "/lib").GetDirectories())
                        {
                            foreach (FileInfo file in dir.GetFiles())
                            {
                                file.CopyTo(file.Directory + file.Name + ".bak");
                            }
                        }

                        // Yes, the above calls could be recursive. No, I can't be bothered to make them as such.

                        HelperMethods.DirectoryCopy(tmpUpdatePath + "lib", CrossPlatformOperations.CURRENTPATH + "/lib", true);
                    }
                    
                    Directory.Delete(tmpUpdatePath, true);

                    CrossPlatformOperations.CopyOldConfigToNewConfig();

                    log.Info("Files extracted. Preparing to restart executable...");

                    if (currentPlatform.IsGtk) System.Diagnostics.Process.Start("chmod", "+x ./AM2RLauncher.Gtk");

                    System.Diagnostics.Process.Start(updatePath + "/" + CrossPlatformOperations.LAUNCHERNAME);
                    Environment.Exit(0);
                }
            }
            else
            {
                log.Info("AutoUpdate Launcher set to false. Exiting update check.");
            }
        }

19 Source : BuildSLNUtilities.cs
with MIT License
from anderm

public static void ParseBuildCommandLine(ref BuildInfo buildInfo)
        {
            string[] arguments = Environment.GetCommandLineArgs();

            buildInfo.IsCommandLine = true;

            for (int i = 0; i < arguments.Length; ++i)
            {
                // Can't use -buildTarget which is something Unity already takes as an argument for something.
                if (string.Equals(arguments[i], "-duskBuildTarget", StringComparison.InvariantCultureIgnoreCase))
                {
                    buildInfo.BuildTarget = (BuildTarget)Enum.Parse(typeof(BuildTarget), arguments[++i]);
                }
                else if (string.Equals(arguments[i], "-wsaSDK", StringComparison.InvariantCultureIgnoreCase))
                {
                    string wsaSdkArg = arguments[++i];

                    buildInfo.WSASdk = (WSASDK)Enum.Parse(typeof(WSASDK), wsaSdkArg);
                }
                else if (string.Equals(arguments[i], "-wsaUwpSdk", StringComparison.InvariantCultureIgnoreCase))
                {
                    buildInfo.WSAUwpSdk = arguments[++i];
                }
                else if (string.Equals(arguments[i], "-wsaUWPBuildType", StringComparison.InvariantCultureIgnoreCase))
                {
                    buildInfo.WSAUWPBuildType = (WSAUWPBuildType)Enum.Parse(typeof(WSAUWPBuildType), arguments[++i]);
                }
                else if (string.Equals(arguments[i], "-wsaGenerateReferenceProjects", StringComparison.InvariantCultureIgnoreCase))
                {
                    buildInfo.WSAGenerateReferenceProjects = bool.Parse(arguments[++i]);
                }
                else if (string.Equals(arguments[i], "-buildOutput", StringComparison.InvariantCultureIgnoreCase))
                {
                    buildInfo.OutputDirectory = arguments[++i];
                }
                else if (string.Equals(arguments[i], "-buildDesc", StringComparison.InvariantCultureIgnoreCase))
                {
                    ParseBuildDescriptionFile(arguments[++i], ref buildInfo);
                }
                else if (string.Equals(arguments[i], "-unityBuildSymbols", StringComparison.InvariantCultureIgnoreCase))
                {
                    string newBuildSymbols = arguments[++i];
                    buildInfo.AppendSymbols(newBuildSymbols.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries));
                }
            }
        }

19 Source : XAttributeExtensions.cs
with GNU General Public License v3.0
from AndreiFedarets

public static bool ValueAsBoolean(this XAttribute attribute)
        {
            string value = attribute.Value;
            return bool.Parse(value);
        }

19 Source : CrmWorkflowBase.cs
with MIT License
from AndrewButenko

public Dictionary<string, object> DeserializeDictionary(string dictionaryString)
        {
            var result = new Dictionary<string, object>();

            if (string.IsNullOrEmpty(dictionaryString))
                return result;

            var request = XElement.Parse(dictionaryString);

            request.Elements().ToList().ForEach(e =>
            {
                object fieldValue;

                if (e.Attribute("IsNull")?.Value == "true")
                    fieldValue = null;
                else
                {
                    if (e.Attribute("Type") == null)
                        throw new InvalidPluginExecutionException(
                            $"Attribute {e.Name} is not null and doesn't contain field type, can't deserialize");

                    var typeName = e.Attribute("Type").Value;

                    switch (typeName)
                    {
                        case "System.Boolean":
                            fieldValue = bool.Parse(e.Value);
                            break;
                        case "System.String":
                            fieldValue = e.Value;
                            break;
                        case "System.Int32":
                            fieldValue = int.Parse(e.Value);
                            break;
                        case "System.DateTime":
                            fieldValue = DateTime.Parse(e.Value);
                            break;
                        case "System.Decimal":
                            fieldValue = decimal.Parse(e.Value);
                            break;
                        case "Microsoft.Xrm.Sdk.OptionSetValue":
                            fieldValue = new OptionSetValue(int.Parse(e.Value));
                            break;
                        case "Microsoft.Xrm.Sdk.Money":
                            fieldValue = new Money(decimal.Parse(e.Value));
                            break;
                        case "Microsoft.Xrm.Sdk.EnreplacedyReference":
                            if (e.Element("Id") == null)
                                throw new InvalidPluginExecutionException(
                                    $"Can't parse {e.Name} node with {typeName} type - Id node is not available");

                            if (e.Element("LogicalName") == null)
                                throw new InvalidPluginExecutionException(
                                    $"Can't parse {e.Name} node with {typeName} type - LogicalName node is not available");

                            fieldValue = new EnreplacedyReference(e.Element("LogicalName").Value,
                                new Guid(e.Element("Id").Value));
                            break;
                        default:
                            throw new InvalidPluginExecutionException(
                                $"Serialization is not implemented for {typeName} clreplaced");
                    }

                    result.Add(e.Name.ToString(), fieldValue);
                }
            });

            return result;
        }

See More Examples