System.Enum.TryParse(string, bool, out TEnum)

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

1273 Examples 7

19 View Source File : IncorrectDeclarationOfDacKeyFix.cs
License : GNU General Public License v3.0
Project Creator : Acumatica

public override async Task RegisterCodeFixesAsync(CodeFixContext context)
		{
			context.CancellationToken.ThrowIfCancellationRequested();

            var diagnostic = context.Diagnostics.FirstOrDefault(d => FixableDiagnosticIds.Contains(d.Id));

            if (diagnostic == null || diagnostic.AdditionalLocations.IsNullOrEmpty() || diagnostic.AdditionalLocations[0] == null ||
				!diagnostic.IsRegisteredForCodeFix() || !diagnostic.Properties.TryGetValue(nameof(RefIntegrityDacKeyType), out string dacKeyTypeString) ||
                dacKeyTypeString.IsNullOrWhiteSpace() || !Enum.TryParse(dacKeyTypeString, out RefIntegrityDacKeyType dacKeyType))
            {
                return;
            }

			var root = await context.Doreplacedent.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);

			if (!(root?.FindNode(context.Span) is ClreplacedDeclarationSyntax keyNode))
				return;

			if (!(root.FindNode(diagnostic.AdditionalLocations[0].SourceSpan) is ClreplacedDeclarationSyntax dacNode))
				return;

			switch (dacKeyType)
			{
				case RefIntegrityDacKeyType.PrimaryKey
				when keyNode.Identifier.Text != ReferentialIntegrity.PrimaryKeyClreplacedName:
					{
						bool shouldChangeLocation = keyNode.Parent != dacNode;  //We need to change location for primary key
						string codeActionResourceName = shouldChangeLocation
							? nameof(Resources.PX1036PK_ChangeNameAndLocationFix)
							: nameof(Resources.PX1036PK_ChangeNameFix);

						var codeActionreplacedle = codeActionResourceName.GetLocalized().ToString();
						var codeAction = CodeAction.Create(codeActionreplacedle,
														   cancellation => ChangeKeyNameAsync(context.Doreplacedent, dacNode, root, keyNode,
																							  ReferentialIntegrity.PrimaryKeyClreplacedName,
																							  shouldChangeLocation, cancellation),
														   equivalenceKey: codeActionreplacedle);

						context.RegisterCodeFix(codeAction, context.Diagnostics);
						return;
					}
				case RefIntegrityDacKeyType.UniqueKey:
					RegisterCodeFixForUniqueKeys(context, dacNode, root, keyNode, diagnostic);
					return;

				case RefIntegrityDacKeyType.ForeignKey:
					{
						List<ClreplacedDeclarationSyntax> keyNodesNotInFK = GetAllKeyNodesNotInContainer(diagnostic, root, keyNode);
						var codeActionreplacedle = nameof(Resources.PX1036FKFix).GetLocalized().ToString();
						var codeAction = CodeAction.Create(codeActionreplacedle,
														   cancellation => MultipleKeyNotInContainerDeclarationsFixAsync(context.Doreplacedent, root, keyNodesNotInFK, dacNode,
																														 RefIntegrityDacKeyType.ForeignKey, cancellation),
														   equivalenceKey: codeActionreplacedle);

						context.RegisterCodeFix(codeAction, context.Diagnostics);
						return;
					}
			}
		}

19 View Source File : IssuesController.cs
License : MIT License
Project Creator : Adoxio

private ActionResult GetIssueForumView(Enreplacedy issueForum, int? page, string filter = "open", string status = "all", string priority = null)
		{
			IssuePriority issuePriority;

			var issueForumDataAdapter = new IssueForumDataAdapter(issueForum);
			
			if (status == "all" && string.Equals(filter, "open", StringComparison.InvariantCultureIgnoreCase))
			{
				issueForumDataAdapter.Status = new[]
				{
					(int)IssueStatus.NewOrUnconfirmed,
					(int)IssueStatus.Confirmed,
					(int)IssueStatus.WorkaroundAvailable,
				};
			}
			else if (status == "all" && string.Equals(filter, "closed", StringComparison.InvariantCultureIgnoreCase))
			{
				issueForumDataAdapter.Status = new[]
				{
					(int)IssueStatus.Resolved,
					(int)IssueStatus.WillNotFix,
					(int)IssueStatus.ByDesign,
					(int)IssueStatus.UnableToReproduce,
				};
			}
			else
			{
				var statusWithoutHyphens = status.Replace("-", string.Empty);

				IssueStatus issueStatus;
				
				if (Enum.TryParse(statusWithoutHyphens, true, out issueStatus))
				{
					issueForumDataAdapter.Status = new[] { (int)issueStatus };
				}
			}

			issueForumDataAdapter.Priority = Enum.TryParse(priority, true, out issuePriority) ? (int)issuePriority : (int?)null;

			var issueForumViewModel = new IssueForumViewModel
			{
				IssueForum = issueForumDataAdapter.Select(),
				Issues = new PaginatedList<IIssue>(page, issueForumDataAdapter.SelectIssueCount(), issueForumDataAdapter.SelectIssues)
			};

			return View("IssueForum", issueForumViewModel);
		}

19 View Source File : HelpCommands.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

[CommandHandler("acecommands", AccessLevel.Player, CommandHandlerFlag.None, 0, "Lists all commands.", "<access level or search>")]
        public static void HandleACECommands(Session session, params string[] parameters)
        {
            var commandList = new List<string>();

            var msgHeader = "Note: You may subsreplacedute a forward slash (/) for the at symbol (@).\n"
                          + "For more information, type @acehelp < command >.\n";

            if (session == null)            
                Console.WriteLine("For more information, type acehelp < command >.");

            var accessLevel = session != null ? session.AccessLevel : AccessLevel.Admin;
            var exact = false;
            string search = null;

            if (parameters.Length > 0)
            {
                var param = parameters[0];
                if (Enum.TryParse(param, true, out AccessLevel pAccessLevel) && pAccessLevel <= accessLevel)
                {
                    accessLevel = pAccessLevel;
                    exact = true;
                }
                else
                    search = param;
            }

            var restrict = session != null ? CommandHandlerFlag.ConsoleInvoke : CommandHandlerFlag.RequiresWorld;

            var commands = from cmd in CommandManager.GetCommands()
                           where (exact ? cmd.Attribute.Access == accessLevel : cmd.Attribute.Access <= accessLevel) && cmd.Attribute.Flags != restrict
                           && (search != null ? $"{cmd.Attribute.Access} {cmd.Attribute.Command} {cmd.Attribute.Description}".Contains(search, StringComparison.OrdinalIgnoreCase) : true)
                           orderby cmd.Attribute.Command
                           select cmd;

            foreach (var command in commands)
                commandList.Add(string.Format("@{0} - {1}", command.Attribute.Command, command.Attribute.Description));

            var msg = string.Join("\n", commandList);

            if (session != null)
                session.Network.EnqueueSend(new GameMessageSystemChat(msgHeader + msg, ChatMessageType.Broadcast));
            else
                Console.WriteLine(msg);
        }

19 View Source File : Runner.cs
License : MIT License
Project Creator : actions

public async Task<int> ExecuteCommand(CommandSettings command)
        {
            try
            {
                VssUtil.InitializeVssClientSettings(HostContext.UserAgents, HostContext.WebProxy);

                _inConfigStage = true;
                _completedCommand.Reset();
                _term.CancelKeyPress += CtrlCHandler;

                //register a SIGTERM handler
                HostContext.Unloading += Runner_Unloading;

                // TODO Unit test to cover this logic
                Trace.Info(nameof(ExecuteCommand));
                var configManager = HostContext.GetService<IConfigurationManager>();

                // command is not required, if no command it just starts if configured

                // TODO: Invalid config prints usage

                if (command.Help)
                {
                    PrintUsage(command);
                    return Constants.Runner.ReturnCode.Success;
                }

                if (command.Version)
                {
                    _term.WriteLine(BuildConstants.RunnerPackage.Version);
                    return Constants.Runner.ReturnCode.Success;
                }

                if (command.Commit)
                {
                    _term.WriteLine(BuildConstants.Source.CommitHash);
                    return Constants.Runner.ReturnCode.Success;
                }

                if (command.Check)
                {
                    var url = command.GetUrl();
                    var pat = command.GetGitHubPersonalAccessToken(required: true);
                    var checkExtensions = HostContext.GetService<IExtensionManager>().GetExtensions<ICheckExtension>();
                    var sortedChecks = checkExtensions.OrderBy(x => x.Order);
                    foreach (var check in sortedChecks)
                    {
                        _term.WriteLine($"**********************************************************************************************************************");
                        _term.WriteLine($"**  Check:               {check.CheckName}");
                        _term.WriteLine($"**  Description:         {check.CheckDescription}");
                        _term.WriteLine($"**********************************************************************************************************************");
                        var result = await check.RunCheck(url, pat);
                        if (!result)
                        {
                            _term.WriteLine($"**                                                                                                                  **");
                            _term.WriteLine($"**                                            F A I L                                                               **");
                            _term.WriteLine($"**                                                                                                                  **");
                            _term.WriteLine($"**********************************************************************************************************************");
                            _term.WriteLine($"** Log: {check.CheckLog}");
                            _term.WriteLine($"** Help Doc: {check.HelpLink}");
                            _term.WriteLine($"**********************************************************************************************************************");
                        }
                        else
                        {
                            _term.WriteLine($"**                                                                                                                  **");
                            _term.WriteLine($"**                                            P A S S                                                               **");
                            _term.WriteLine($"**                                                                                                                  **");
                            _term.WriteLine($"**********************************************************************************************************************");
                            _term.WriteLine($"** Log: {check.CheckLog}");
                            _term.WriteLine($"**********************************************************************************************************************");
                        }

                        _term.WriteLine();
                        _term.WriteLine();
                    }

                    return Constants.Runner.ReturnCode.Success;
                }

                // Configure runner prompt for args if not supplied
                // Unattended configure mode will not prompt for args if not supplied and error on any missing or invalid value.
                if (command.Configure)
                {
                    try
                    {
                        await configManager.ConfigureAsync(command);
                        return Constants.Runner.ReturnCode.Success;
                    }
                    catch (Exception ex)
                    {
                        Trace.Error(ex);
                        _term.WriteError(ex.Message);
                        return Constants.Runner.ReturnCode.TerminatedError;
                    }
                }

                // remove config files, remove service, and exit
                if (command.Remove)
                {
                    try
                    {
                        await configManager.UnconfigureAsync(command);
                        return Constants.Runner.ReturnCode.Success;
                    }
                    catch (Exception ex)
                    {
                        Trace.Error(ex);
                        _term.WriteError(ex.Message);
                        return Constants.Runner.ReturnCode.TerminatedError;
                    }
                }

                _inConfigStage = false;

                // warmup runner process (JIT/CLR)
                // In scenarios where the runner is single use (used and then thrown away), the system provisioning the runner can call `Runner.Listener --warmup` before the machine is made available to the pool for use.
                // this will optimizes the runner process startup time.
                if (command.Warmup)
                {
                    var binDir = HostContext.GetDirectory(WellKnownDirectory.Bin);
                    foreach (var replacedemblyFile in Directory.EnumerateFiles(binDir, "*.dll"))
                    {
                        try
                        {
                            Trace.Info($"Load replacedembly: {replacedemblyFile}.");
                            var replacedembly = replacedembly.LoadFrom(replacedemblyFile);
                            var types = replacedembly.GetTypes();
                            foreach (Type loadedType in types)
                            {
                                try
                                {
                                    Trace.Info($"Load methods: {loadedType.FullName}.");
                                    var methods = loadedType.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static);
                                    foreach (var method in methods)
                                    {
                                        if (!method.IsAbstract && !method.ContainsGenericParameters)
                                        {
                                            Trace.Verbose($"Prepare method: {method.Name}.");
                                            RuntimeHelpers.PrepareMethod(method.MethodHandle);
                                        }
                                    }
                                }
                                catch (Exception ex)
                                {
                                    Trace.Error(ex);
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            Trace.Error(ex);
                        }
                    }

                    return Constants.Runner.ReturnCode.Success;
                }

                RunnerSettings settings = configManager.LoadSettings();

                var store = HostContext.GetService<IConfigurationStore>();
                bool configuredreplacedervice = store.IsServiceConfigured();

                // Run runner
                if (command.Run) // this line is current break machine provisioner.
                {
                    // Error if runner not configured.
                    if (!configManager.IsConfigured())
                    {
                        _term.WriteError("Runner is not configured.");
                        PrintUsage(command);
                        return Constants.Runner.ReturnCode.TerminatedError;
                    }

                    Trace.Verbose($"Configured as service: '{configuredreplacedervice}'");

                    //Get the startup type of the runner i.e., autostartup, service, manual
                    StartupType startType;
                    var startupTypereplacedtring = command.GetStartupType();
                    if (string.IsNullOrEmpty(startupTypereplacedtring) && configuredreplacedervice)
                    {
                        // We need try our best to make the startup type accurate
                        // The problem is coming from runner autoupgrade, which result an old version service host binary but a newer version runner binary
                        // At that time the servicehost won't preplaced --startuptype to Runner.Listener while the runner is actually running as service.
                        // We will guess the startup type only when the runner is configured as service and the guess will based on whether STDOUT/STDERR/STDIN been redirect or not
                        Trace.Info($"Try determine runner startup type base on console redirects.");
                        startType = (Console.IsErrorRedirected && Console.IsInputRedirected && Console.IsOutputRedirected) ? StartupType.Service : StartupType.Manual;
                    }
                    else
                    {
                        if (!Enum.TryParse(startupTypereplacedtring, true, out startType))
                        {
                            Trace.Info($"Could not parse the argument value '{startupTypereplacedtring}' for StartupType. Defaulting to {StartupType.Manual}");
                            startType = StartupType.Manual;
                        }
                    }

                    Trace.Info($"Set runner startup type - {startType}");
                    HostContext.StartupType = startType;

                    if (command.RunOnce)
                    {
                        _term.WriteLine("Warning: '--once' is going to be deprecated in the future, please consider using '--ephemeral' during runner registration.", ConsoleColor.Yellow);
                        _term.WriteLine("https://docs.github.com/en/actions/hosting-your-own-runners/autoscaling-with-self-hosted-runners#using-ephemeral-runners-for-autoscaling", ConsoleColor.Yellow);
                    }

                    // Run the runner interactively or as service
                    return await RunAsync(settings, command.RunOnce || settings.Ephemeral);
                }
                else
                {
                    PrintUsage(command);
                    return Constants.Runner.ReturnCode.Success;
                }
            }
            finally
            {
                _term.CancelKeyPress -= CtrlCHandler;
                HostContext.Unloading -= Runner_Unloading;
                _completedCommand.Set();
            }
        }

19 View Source File : MutationCache.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public static EffectArgumentType GetEffectArgumentType(Effect effect, string operand)
        {
            if (IsNumber(operand) || Enum.TryParse(operand, out WieldRequirement wieldRequirement) || Enum.TryParse(operand, out Skill skill) || Enum.TryParse(operand, out ImbuedEffectType imbuedEffectType))
            {
                if (operand.Contains('.'))
                    return EffectArgumentType.Double;
                else if (effect.Quality != null && effect.Quality.StatType == StatType.Int64)
                    return EffectArgumentType.Int64;
                else
                    return EffectArgumentType.Int;
            }
            else if (GetStatType(operand) != StatType.Undef)
            {
                return EffectArgumentType.Quality;
            }
            else if (operand.StartsWith("Random", StringComparison.OrdinalIgnoreCase))
                return EffectArgumentType.Random;
            else if (operand.StartsWith("Variable", StringComparison.OrdinalIgnoreCase))
                return EffectArgumentType.Variable;
            else
                return EffectArgumentType.Invalid;
        }

19 View Source File : WeenieSQLWriter.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public string GetDefaultSubfolder(Weenie input)
        {
            var subFolder = Enum.GetName(typeof(WeenieType), input.Type) + "\\";

            if (input.Type == (int)WeenieType.Creature)
            {
                var property = input.WeeniePropertiesInt.FirstOrDefault(r => r.Type == (int)PropertyInt.CreatureType);

                if (property != null)
                {
                    Enum.TryParse(property.Value.ToString(), out CreatureType ct);

                    if (Enum.IsDefined(typeof(CreatureType), ct))
                        subFolder += Enum.GetName(typeof(CreatureType), property.Value) + "\\";
                    else
                        subFolder += "UnknownCT_" + property.Value + "\\";
                }
                else
                    subFolder += "Unsorted" + "\\";
            }
            else if (input.Type == (int)WeenieType.House)
            {
                var property = input.WeeniePropertiesInt.FirstOrDefault(r => r.Type == (int)PropertyInt.HouseType);

                if (property != null)
                {
                    Enum.TryParse(property.Value.ToString(), out HouseType ht);

                    if (Enum.IsDefined(typeof(HouseType), ht))
                        subFolder += Enum.GetName(typeof(HouseType), property.Value) + "\\";
                    else
                        subFolder += "UnknownHT_" + property.Value + "\\";
                }
                else
                    subFolder += "Unsorted" + "\\";
            }
            else
            {
                var property = input.WeeniePropertiesInt.FirstOrDefault(r => r.Type == (int)PropertyInt.ItemType);

                if (property != null)
                    subFolder += Enum.GetName(typeof(ItemType), property.Value) + "\\";
                else
                    subFolder += Enum.GetName(typeof(ItemType), ItemType.None) + "\\";
            }

            return subFolder;
        }

19 View Source File : DebugOrganizationService.cs
License : MIT License
Project Creator : Adoxio

public override void Initialize(string name, NameValueCollection config)
		{
			Formatting formatting;

			if (Enum.TryParse(config["formatting"], out formatting))
			{
				Formatting = formatting;
			}

			bool includeResponse;

			if (bool.TryParse(config["includeResponse"], out includeResponse))
			{
				IncludeResponse = includeResponse;
			}

			base.Initialize(name, config);
		}

19 View Source File : DellFanManagementGuiForm.cs
License : GNU General Public License v3.0
Project Creator : AaronKelley

private void ApplyManualModeConfiguration()
        {
            if (operationModeRadioButtonManual.Checked)
            {
                // Apply saved manual mode configuration.
                if (_configurationStore.GetIntOption(ConfigurationOption.ManualModeEcFanControlEnabled) == 0)
                {
                    ecFanControlRadioButtonOff.Checked = true;

                    if (Enum.TryParse(_configurationStore.GetStringOption(ConfigurationOption.ManualModeFan1Level), out FanLevel fan1Level))
                    {
                        switch (fan1Level)
                        {
                            case FanLevel.Off:
                                manualFan1RadioButtonOff.Checked = true;
                                break;
                            case FanLevel.Medium:
                                manualFan1RadioButtonMedium.Checked = true;
                                break;
                            case FanLevel.High:
                                manualFan1RadioButtonHigh.Checked = true;
                                break;
                        }
                    }

                    if (Enum.TryParse(_configurationStore.GetStringOption(ConfigurationOption.ManualModeFan2Level), out FanLevel fan2Level))
                    {
                        switch (fan2Level)
                        {
                            case FanLevel.Off:
                                manualFan2RadioButtonOff.Checked = true;
                                break;
                            case FanLevel.Medium:
                                manualFan2RadioButtonMedium.Checked = true;
                                break;
                            case FanLevel.High:
                                manualFan2RadioButtonHigh.Checked = true;
                                break;
                        }
                    }
                }
            }
        }

19 View Source File : DataReader.cs
License : GNU General Public License v3.0
Project Creator : aenemenate

public static Animal GetAnimal(string name, Block[] map, Point position, Point worldIndex, int currentFloor)
        {
            XElement creatureData = null;

            // load all the creatures
            XElement root = XElement.Load("res/data/OverworldCreatureTypes.xml");
            IEnumerable<XElement> creatures =
                from el in root.Elements("creature")
                select el;

            // choose the right creature
            foreach (XElement c in creatures)
                if (ReadAttribute(c.FirstAttribute).Equals(name))
                    creatureData = c;

            if (creatureData == null)
                return null;

            byte graphic = System.Convert.ToByte(ReadAttribute(creatureData.Attribute("ascii_char")));
            string faction = System.Convert.ToString(ReadAttribute(creatureData.Attribute("faction")));
            int sightDist = System.Convert.ToInt32(ReadAttribute(creatureData.Attribute("sight_dist")));

            byte r = System.Convert.ToByte(ReadAttribute(creatureData.Element("color").Attribute("r"))),
                 g = System.Convert.ToByte(ReadAttribute(creatureData.Element("color").Attribute("g"))),
                 b = System.Convert.ToByte(ReadAttribute(creatureData.Element("color").Attribute("b")));
            Color? color = new Color(r, g, b);

            Enum.TryParse(ReadElement(creatureData.Element("diet")), out DietType diet);

            IEnumerable<XElement> majorAttData = from el in creatureData.Element("clreplaced").Element("major_attributes").Elements("attribute")
                                                 select el;
            List<Attribute> majorAtt = new List<Attribute>();
            foreach (XElement attE in majorAttData) {
                Enum.TryParse(ReadElement(attE), out Attribute att);
                majorAtt.Add(att);
            }

            IEnumerable<XElement> majorSkillsData = from el in creatureData.Element("clreplaced").Element("major_skills").Elements("skill")
                                                    select el;
            List<Skill> majorSkills = new List<Skill>();
            foreach (XElement skillE in majorSkillsData) {
                Enum.TryParse(ReadElement(skillE), out Skill skill);
                majorSkills.Add(skill);
            }

            IEnumerable<XElement> minorSkillsData = from el in creatureData.Element("clreplaced").Element("minor_skills").Elements("skill")
                                                    select el;
            List<Skill> minorSkills = new List<Skill>();
            foreach (XElement skillE in minorSkillsData) {
                Enum.TryParse(ReadElement(skillE), out Skill skill);
                minorSkills.Add(skill);
            }

            Clreplaced uClreplaced = new Clreplaced(majorAtt, majorSkills, minorSkills);

            IEnumerable<XElement> baseDesiresData = from el in creatureData.Element("base_desires").Elements("desire_type")
                                                    select el;
            Dictionary<DesireType, int> baseDesires = new Dictionary<DesireType, int>();
            foreach (XElement desireTypeE in baseDesiresData) {
                Enum.TryParse(ReadAttribute(desireTypeE.FirstAttribute), out DesireType desireType);
                baseDesires.Add(desireType, System.Convert.ToInt32(ReadAttribute(desireTypeE.LastAttribute)));
            }

            return new Animal(map, position, worldIndex, currentFloor, color, sightDist, 3, baseDesires, uClreplaced, name, "male", diet, faction, graphic);
        }

19 View Source File : RegisterUserValidator.cs
License : MIT License
Project Creator : Abdulrhman5

public CommandResult<Models.AppUser> ValidateRegistrationOfNewUser(RegisterUserDto user)
        {
            if(user == null)
            {
                return new CommandResult<Models.AppUser>(new ErrorMessage
                {
                    ErrorCode = "USER.REGISTER.INVALID",
                    Message = "Please fill the required data",
                    StatusCode = HttpStatusCode.BadRequest
                });
            }

            if (user.Email.IsNullOrEmpty())
            {
                return new CommandResult<Models.AppUser>(new ErrorMessage
                {
                    ErrorCode = "USER.REGISTER.EMAIL.NULL",
                    Message = "Please fill the email field",
                    StatusCode = HttpStatusCode.BadRequest
                });
            }

            if (!IsValidEmail(user.Email))
            {
                return new CommandResult<Models.AppUser>(new ErrorMessage
                {
                    ErrorCode = "USER.REGILTER.EMAIL.INVALID",
                    Message = "The Email feild does not represent an email",
                    StatusCode = HttpStatusCode.BadRequest

                });
            }

            if (user.Username.IsNullOrEmpty())
            {
                return new CommandResult<Models.AppUser>(new ErrorMessage
                {
                    ErrorCode = "USER.REGISTER.USERNAME.NULL",
                    Message = "Please fill the user name feild",
                    StatusCode = HttpStatusCode.BadRequest
                });
            }

            if(user.Username.Length <= 5 || user.Username.Length >= 200)
            {
                return new CommandResult<Models.AppUser>(new ErrorMessage
                {
                    ErrorCode = "USER.REGISTER.USERNAME.INVALID",
                    Message = "The user name must be longer than 5 and less than 200",
                    StatusCode = HttpStatusCode.BadRequest

                });
            }

            
            if (user.Gender.IsNullOrEmpty())
            {
                return new CommandResult<Models.AppUser>(new ErrorMessage
                {
                    ErrorCode = "USER.REGISTER.GENDER.NULL",
                    Message = "Please fill the user gender",
                    StatusCode = HttpStatusCode.BadRequest

                });
            }

            if(!Enum.TryParse(user.Gender, true, out Gender gender))
            {
                return new CommandResult<Models.AppUser>(new ErrorMessage
                {
                    ErrorCode = "USER.REGISTER.GENDER.INVALID",
                    Message = "Please fill the gender with valid data",
                    StatusCode = HttpStatusCode.BadRequest

                });
            }

            if (user.PhoneNumber.IsNullOrEmpty())
            {
                return new CommandResult<Models.AppUser>(new ErrorMessage
                {
                    ErrorCode = "USER.REGISTER.PHONE_NUMBER.NULL",
                    Message = "Please fill the phone number feild",
                    StatusCode = HttpStatusCode.BadRequest
                });
            }

            if (IsValidPhoneNumber(user.PhoneNumber))
            {
                return new CommandResult<Models.AppUser>(new ErrorMessage
                {
                    ErrorCode = "USER.REGISTER.PHONE_NUMBER.INVALID",
                    Message = "Please fill the phone number with valid data",
                    StatusCode = HttpStatusCode.BadRequest
                });
            }

            if (user.Preplacedword.IsNullOrEmpty())
            {
                return new CommandResult<Models.AppUser>(new ErrorMessage
                {
                    ErrorCode = "USER.REGISTER.PreplacedWORD.NULL",
                    Message = "Please fill the preplacedword feild",
                    StatusCode = HttpStatusCode.BadRequest
                });
            }

            if (user.PreplacedwordConfirmation.IsNullOrEmpty())
            {
                return new CommandResult<Models.AppUser>(new ErrorMessage
                {
                    ErrorCode = "USER.REGISTER.PreplacedWORD_CONFIRMATION.NULL",
                    Message = "Please fill the preplacedword confirmation feild",
                    StatusCode = HttpStatusCode.BadRequest
                });
            }

            if(user.Preplacedword != user.PreplacedwordConfirmation)
            {
                return new CommandResult<Models.AppUser>(new ErrorMessage
                {
                    ErrorCode = "USER.REGISTER.PreplacedWORD_CONFIRMATION.INVALID",
                    Message = "The preplacedword and confirmation are not the same",
                    StatusCode = HttpStatusCode.BadRequest
                });
            }

            return new CommandResult<Models.AppUser>(new Models.AppUser
            {
                Id = Guid.NewGuid().ToString(),
                Email = user.Email,
                CreatedAt = DateTime.UtcNow,
                PhoneNumber = user.PhoneNumber,
                UserName = user.Email,
                NormalizedName = user.Username,
                Gender = gender,
            });
        }

19 View Source File : LootParser.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public static ChanceTable<TreasureWeaponType> ParseChanceTable_WeaponType(string[] lines, int startLine)
        {
            var chanceTable = new ChanceTable<TreasureWeaponType>();

            for (var i = startLine + 1; i < lines.Length; i++)
            {
                var line = lines[i].Trim();

                if (line.Length < 2)
                    continue;

                if (line.Length == 2)
                    break;

                if (line.StartsWith("//"))
                    continue;

                var match = Regex.Match(line, @"TreasureWeaponType.([^,]+),\s+([\d.]+)");

                if (!match.Success || !System.Enum.TryParse(match.Groups[1].Value, out TreasureWeaponType weaponType) || !float.TryParse(match.Groups[2].Value, out var chance))
                {
                    Console.WriteLine($"Couldn't parse {line}");
                    continue;
                }
                chanceTable.Add((weaponType, chance));
            }

            return chanceTable;
        }

19 View Source File : LootParser.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public static ChanceTable<WeenieClreplacedName> ParseChanceTable_Wcid(string[] lines, int startLine)
        {
            var chanceTable = new ChanceTable<WeenieClreplacedName>();

            for (var i = startLine + 1; i < lines.Length; i++)
            {
                var line = lines[i].Trim();

                if (line.Length < 2)
                    continue;

                if (line.Length == 2)
                    break;

                if (line.StartsWith("//"))
                    continue;

                var match = Regex.Match(line, @"WeenieClreplacedName.([^,]+),\s+([\d.]+)");

                if (!match.Success || !System.Enum.TryParse(match.Groups[1].Value, out WeenieClreplacedName wcid) || !float.TryParse(match.Groups[2].Value, out var chance))
                {
                    Console.WriteLine($"Couldn't parse {line}");
                    continue;
                }
                chanceTable.Add((wcid, chance));
            }

            return chanceTable;
        }

19 View Source File : ScatterSeriesSpeedTest.xaml.cs
License : MIT License
Project Creator : ABTSoftware

public void Execute(TestParameters testParameters, TimeSpan duration, Action<double> fpsResult)
        {
            // Setup
            var dataset = new DataSeriesSet<double, double>();
            _xyDataSeries = new XyDataSeries<double, double>();
            dataset.Add(_xyDataSeries);

            sciChart.DataSet = dataset;

			this.scatterSeries.AntiAliasing = testParameters.AntiAliasing;
			ResamplingMode resamplingMode; if (!Enum.TryParse(testParameters.SamplingMode.ToString(), out resamplingMode)) resamplingMode = ResamplingMode.None;
			this.scatterSeries.ResamplingMode = resamplingMode;

			_generator = testParameters.DataDistribution == DataDistribution.Uniform ? (RandomPointsGenerator)new BrownianMotionPointsGenerator(0, 100, -50, 50) : new CorrelatedDataPointsGenerator(0, 100, -50, 50);
			
            sciChart.XAxis.VisibleRange = new DoubleRange(0, 100);
            sciChart.YAxis.VisibleRange = new DoubleRange(-50, 50);
            var initialData = _generator.GetRandomPoints(testParameters.PointCount);
            _xyDataSeries.Append(initialData.XData, initialData.YData);

            // Execute
            _testRunner = new DispatcherTimerRunner(duration, () => OnAppendData(testParameters.PointCount), fpsResult);
            sciChart.Rendered += _testRunner.OnSciChartRendered;
            _testRunner.Run();
        }

19 View Source File : StepConverter.cs
License : MIT License
Project Creator : actions

public override object ReadJson(
            JsonReader reader,
            Type objectType,
            Object existingValue,
            JsonSerializer serializer)
        {
            if (reader.TokenType != JsonToken.StartObject)
            {
                return null;
            }

            JObject value = JObject.Load(reader);
            if (value.TryGetValue("Type", StringComparison.OrdinalIgnoreCase, out JToken stepTypeValue))
            {
                StepType stepType;
                if (stepTypeValue.Type == JTokenType.Integer)
                {
                    stepType = (StepType)(Int32)stepTypeValue;
                }
                else if (stepTypeValue.Type != JTokenType.String || !Enum.TryParse((String)stepTypeValue, true, out stepType))
                {
                    return null;
                }

                Step stepObject = null;
                switch (stepType)
                {
                    case StepType.Action:
                        stepObject = new ActionStep();
                        break;
                }

                using (var objectReader = value.CreateReader())
                {
                    serializer.Populate(objectReader, stepObject);
                }

                return stepObject;
            }
            else
            {
                return null;
            }
        }

19 View Source File : NpcCommandHandler.cs
License : GNU Lesser General Public License v3.0
Project Creator : 8720826

private async Task<bool> CheckIf(PlayerEnreplacedy player, string condition, List<CaseAttribute> attrs, string input)
        {
            var field = attrs.FirstOrDefault(x => x.Attr == "Field")?.Val;
            var relation = attrs.FirstOrDefault(x => x.Attr == "Relation")?.Val;
            var value = attrs.FirstOrDefault(x => x.Attr == "Value")?.Val;
            var wareName = attrs.FirstOrDefault(x => x.Attr == "WareName")?.Val;
            var number = attrs.FirstOrDefault(x => x.Attr == "Number")?.Val;
            int.TryParse(attrs.FirstOrDefault(x => x.Attr == "QuestId")?.Val, out int questId);

            if (string.IsNullOrEmpty(condition))
            {
                return true;
            }

            if (!Enum.TryParse(condition, true, out ConditionTypeEnum conditionEnum))
            {
                return true;
            }


            switch (conditionEnum)
            {
                case ConditionTypeEnum.角色属性:
                    if (!CheckField(player, field, value, relation))
                    {
                        return false;
                    }
                    break;

                case ConditionTypeEnum.是否拥有物品:
                    if (!await CheckWare(player.Id, wareName, number, relation))
                    {
                        return false;
                    }

                    break;

                case ConditionTypeEnum.是否领取任务:

                    var playerQuest = await _playerQuestDomainService.Get(x => x.QuestId == questId && x.PlayerId == player.Id);
                    if (playerQuest == null)
                    {
                        return false;
                    }
                    break;

                case ConditionTypeEnum.是否完成任务:

                    break;

                case ConditionTypeEnum.活动记录:

                    break;
            }

            return true;
        }

19 View Source File : EmbeddedIconProvider.ios.cs
License : MIT License
Project Creator : adenearnshaw

public async Task<object> CreatePlatformIcon(IShortcutIcon shortcutIcon)
        {
            var isParseSuccessful = Enum.TryParse(shortcutIcon.IconName, out UIApplicationShortcutIconType type);

            if (!isParseSuccessful)
                type = UIApplicationShortcutIconType.Favorite;

            UIApplicationShortcutIcon icon = null;
            new NSObject().BeginInvokeOnMainThread(() =>
            {
                icon = UIApplicationShortcutIcon.FromType(type);
            });

            await Task.Delay(200);

            return icon;
        }

19 View Source File : AccountCommands.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

[CommandHandler("set-accountaccess", AccessLevel.Admin, CommandHandlerFlag.None, 1, 
            "Change the access level of an account.", 
            "accountname (accesslevel)\n" +
            "accesslevel can be a number or enum name\n" +
            "0 = Player | 1 = Advocate | 2 = Sentinel | 3 = Envoy | 4 = Developer | 5 = Admin")]
        public static void HandleAccountUpdateAccessLevel(Session session, params string[] parameters)
        {
            string accountName  = parameters[0].ToLower();

            var accountId = DatabaseManager.Authentication.GetAccountIdByName(accountName);

            if (accountId == 0)
            {
                CommandHandlerHelper.WriteOutputInfo(session, "Account " + accountName + " does not exist.", ChatMessageType.Broadcast);
                return;
            }

            AccessLevel accessLevel = AccessLevel.Player;

            if (parameters.Length > 1)
            {
                if (Enum.TryParse(parameters[1], true, out accessLevel))
                {
                    if (!Enum.IsDefined(typeof(AccessLevel), accessLevel))
                        accessLevel = AccessLevel.Player;
                }
            }

            string articleAorAN = "a";
            if (accessLevel == AccessLevel.Advocate || accessLevel == AccessLevel.Admin || accessLevel == AccessLevel.Envoy)
                articleAorAN = "an";

            if (accountId == 0)
            {
                CommandHandlerHelper.WriteOutputInfo(session, "Account " + accountName + " does not exist.", ChatMessageType.Broadcast);
                return;
            }

            DatabaseManager.Authentication.UpdateAccountAccessLevel(accountId, accessLevel);

            if (DatabaseManager.AutoPromoteNextAccountToAdmin && accessLevel == AccessLevel.Admin)
                DatabaseManager.AutoPromoteNextAccountToAdmin = false;

            CommandHandlerHelper.WriteOutputInfo(session, "Account " + accountName + " updated with access rights set as " + articleAorAN + " " + Enum.GetName(typeof(AccessLevel), accessLevel) + ".", ChatMessageType.Broadcast);
        }

19 View Source File : CmsEntityFileAttachmentHandler.cs
License : MIT License
Project Creator : Adoxio

protected override void ProcessRequest(HttpContext context, ICmsEnreplacedyServiceProvider serviceProvider, Guid portalScopeId, IPortalContext portal, OrganizationServiceContext serviceContext, Enreplacedy enreplacedy, CmsEnreplacedyMetadata enreplacedyMetadata, ICrmEnreplacedySecurityProvider security)
		{
			if (!IsRequestMethod(context.Request, "POST"))
			{
				throw new CmsEnreplacedyServiceException(HttpStatusCode.MethodNotAllowed, "Request method {0} not allowed for this resource.".FormatWith(context.Request.HttpMethod));
			}
			
			var dataAdapterDependencies =
				new PortalConfigurationDataAdapterDependencies(requestContext: context.Request.RequestContext,
					portalName: PortalName);
			var annotationDataAdapter = new AnnotationDataAdapter(dataAdapterDependencies);
			var website = context.GetWebsite();

			var location = website.Settings.Get<string>("WebFiles/StorageLocation");
			StorageLocation storageLocation;
			if (!Enum.TryParse(location, true, out storageLocation))
			{
				storageLocation = StorageLocation.CrmDoreplacedent;
			}

			var maxFileSizeErrorMessage = website.Settings.Get<string>("WebFiles/MaxFileSizeErrorMessage");

			var annotationSettings = new AnnotationSettings(dataAdapterDependencies.GetServiceContext(),
				storageLocation: storageLocation, maxFileSizeErrorMessage: maxFileSizeErrorMessage);

			var files = context.Request.Files;
			var postedFiles = new List<HttpPostedFile>();

			for (var i = 0; i < files.Count; i++)
			{
				postedFiles.Add(files[i]);
			}

			foreach (var file in postedFiles)
			{
				annotationDataAdapter.CreateAnnotation(new Annotation
				{
					Regarding = enreplacedy.ToEnreplacedyReference(),
					FileAttachment = AnnotationDataAdapter.CreateFileAttachment(new HttpPostedFileWrapper(file), annotationSettings.StorageLocation)
				}, annotationSettings);
			}

			context.Response.ContentType = "text/plain";
			context.Response.Write("OK");
		}

19 View Source File : EntityMapperProvider.cs
License : Apache License 2.0
Project Creator : 1448376744

public static T ConvertToEnum<T>(IDataRecord dr, int i) where T : struct
            {
                try
                {
                    if (dr.IsDBNull(i))
                    {
                        return default;
                    }
                    var value = dr.GetValue(i);
                    if (Enum.TryParse(value.ToString(), out T result)) return result;
                    return default;
                }
                catch
                {
                    throw ThrowException<T>(dr, i);
                }
            }

19 View Source File : DataReader.cs
License : GNU General Public License v3.0
Project Creator : aenemenate

public static Monster GetMonster(string name, Block[] map, Point position, Point worldIndex, int currentFloor)
        {
            XElement monsterData = null;

            // load all the effects
            XElement root = XElement.Load( "res/data/MonsterTypes.xml" );
            IEnumerable<XElement> monsters =
                from el in root.Elements( "monster" )
                select el;

            // choose the right effect
            foreach ( XElement m in monsters )
                if ( ReadAttribute( m.FirstAttribute ) == name )
                    monsterData = m;

            if ( monsterData == null )
                return null;

            byte graphic = System.Convert.ToByte( ReadAttribute( monsterData.Attribute( "ascii_char" ) ) );
            string faction = System.Convert.ToString( ReadAttribute( monsterData.Attribute( "faction" ) ) );
            int sightDist = System.Convert.ToInt32( ReadAttribute( monsterData.Attribute( "sight_dist" ) ) );

            byte r = System.Convert.ToByte( ReadAttribute( monsterData.Element( "color" ).Attribute( "r" ) ) ),
                 g = System.Convert.ToByte( ReadAttribute( monsterData.Element( "color" ).Attribute( "g" ) ) ),
                 b = System.Convert.ToByte( ReadAttribute( monsterData.Element( "color" ).Attribute( "b" ) ) );
            Color? color = new Color( r, g, b );

            Enum.TryParse(ReadElement(monsterData.Element("diet")), out DietType diet);

            IEnumerable<XElement> majorAttData = from el in monsterData.Element( "clreplaced" ).Element( "major_attributes" ).Elements( "attribute" )
                                                 select el;
            List<Attribute> majorAtt = new List<Attribute>();
            foreach (XElement attE in majorAttData) {
                Enum.TryParse( ReadElement( attE ), out Attribute att );
                majorAtt.Add( att );
            } // translate IEnumerable to List

            IEnumerable<XElement> majorSkillsData = from el in monsterData.Element( "clreplaced" ).Element( "major_skills" ).Elements( "skill" )
                                                    select el;
            List<Skill> majorSkills = new List<Skill>();
            foreach ( XElement skillE in majorSkillsData ) {
                Enum.TryParse( ReadElement( skillE ), out Skill skill );
                majorSkills.Add( skill );
            } // translate IEnumerable to List

            IEnumerable<XElement> minorSkillsData = from el in monsterData.Element( "clreplaced" ).Element( "minor_skills" ).Elements( "skill" )
                                                    select el;
            List<Skill> minorSkills = new List<Skill>();
            foreach (XElement skillE in minorSkillsData) {
                Enum.TryParse( ReadElement( skillE ), out Skill skill );
                minorSkills.Add( skill );
            } // translate IEnumerable to List

            Clreplaced uClreplaced = new Clreplaced( majorAtt, majorSkills, minorSkills );
            
            IEnumerable<XElement> baseDesiresData = from el in monsterData.Element( "base_desires" ).Elements( "desire_type" )
                                                    select el;
            Dictionary<DesireType, int> baseDesires = new Dictionary<DesireType, int>();
            foreach (XElement desireTypeE in baseDesiresData) {
                Enum.TryParse( ReadAttribute( desireTypeE.FirstAttribute ), out DesireType desireType );
                baseDesires.Add( desireType, System.Convert.ToInt32( ReadAttribute( desireTypeE.LastAttribute ) ) );
            } // translate IEnumerable to List

            return new Monster( map, position, worldIndex, currentFloor, color, sightDist, 3, baseDesires, uClreplaced, name, "male", diet, faction, graphic );
        }

19 View Source File : MutationCache.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

private static EffectArgument ParseEffectArgument(string filename, Effect effect, string operand)
        {
            var effectArgument = new EffectArgument();

            effectArgument.Type = GetEffectArgumentType(effect, operand);

            switch (effectArgument.Type)
            {
                case EffectArgumentType.Int:

                    if (!int.TryParse(operand, out effectArgument.IntVal))
                    {
                        if (effect.Quality != null && effect.Quality.StatType == StatType.Int && effect.Quality.StatIdx == (int)PropertyInt.ImbuedEffect && Enum.TryParse(operand, out ImbuedEffectType imbuedEffectType))
                            effectArgument.IntVal = (int)imbuedEffectType;
                        else if (Enum.TryParse(operand, out WieldRequirement wieldRequirement))
                            effectArgument.IntVal = (int)wieldRequirement;
                        else if (Enum.TryParse(operand, out Skill skill))
                            effectArgument.IntVal = (int)skill;
                        else
                            log.Error($"MutationCache.BuildMutation({filename}) - couldn't parse IntVal {operand}");
                    }
                    break;

                case EffectArgumentType.Int64:

                    if (!long.TryParse(operand, out effectArgument.LongVal))
                    {
                        log.Error($"MutationCache.BuildMutation({filename}) - couldn't parse Int64Val {operand}");
                    }
                    break;

                case EffectArgumentType.Double:

                    if (!double.TryParse(operand, out effectArgument.DoubleVal))
                    {
                        log.Error($"MutationCache.BuildMutation({filename}) - couldn't parse DoubleVal {operand}");
                    }
                    break;

                case EffectArgumentType.Quality:

                    effectArgument.StatType = GetStatType(operand);

                    switch (effectArgument.StatType)
                    {
                        case StatType.Int:

                            if (Enum.TryParse(operand, out PropertyInt propInt))
                                effectArgument.StatIdx = (int)propInt;
                            else
                                log.Error($"MutationCache.BuildMutation({filename}) - couldn't parse PropertyInt.{operand}");
                            break;

                        case StatType.Int64:

                            if (Enum.TryParse(operand, out PropertyInt64 propInt64))
                                effectArgument.StatIdx = (int)propInt64;
                            else
                                log.Error($"MutationCache.BuildMutation({filename}) - couldn't parse PropertyInt64.{operand}");
                            break;

                        case StatType.Float:

                            if (Enum.TryParse(operand, out PropertyFloat propFloat))
                                effectArgument.StatIdx = (int)propFloat;
                            else
                                log.Error($"MutationCache.BuildMutation({filename}) - couldn't parse PropertyFloat.{operand}");
                            break;

                        case StatType.Bool:

                            if (Enum.TryParse(operand, out PropertyBool propBool))
                                effectArgument.StatIdx = (int)propBool;
                            else
                                log.Error($"MutationCache.BuildMutation({filename}) - couldn't parse PropertyBool.{operand}");
                            break;

                        case StatType.DataID:

                            if (Enum.TryParse(operand, out PropertyDataId propDID))
                                effectArgument.StatIdx = (int)propDID;
                            else
                                log.Error($"MutationCache.BuildMutation({filename}) - couldn't parse PropertyBool.{operand}");
                            break;

                        default:
                            log.Error($"MutationCache.BuildMutation({filename}) - unknown PropertyType.{operand}");
                            break;
                    }
                    break;

                case EffectArgumentType.Random:

                    var match = Regex.Match(operand, @"Random\(([\d.-]+), ([\d.-]+)\)");

                    if (!match.Success || !float.TryParse(match.Groups[1].Value, out effectArgument.MinVal) || !float.TryParse(match.Groups[2].Value, out effectArgument.MaxVal))
                        log.Error($"MutationCache.BuildMutation({filename}) - couldn't parse {operand}");

                    break;

                case EffectArgumentType.Variable:

                    match = Regex.Match(operand, @"\[(\d+)\]");

                    if (!match.Success || !int.TryParse(match.Groups[1].Value, out effectArgument.IntVal))
                        log.Error($"MutationCache.BuildMutation({filename}) - couldn't parse {operand}");

                    break;

                default:
                    log.Error($"MutationCache.BuildMutation({filename}) - unknown EffectArgumentType from {operand}");
                    break;
            }
            return effectArgument;
        }

19 View Source File : MutationCache.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public static StatType GetStatType(string operand)
        {
            if (Enum.TryParse(operand, out PropertyInt propInt))
                return StatType.Int;
            else if (Enum.TryParse(operand, out PropertyInt64 propInt64))
                return StatType.Int64;
            else if (Enum.TryParse(operand, out PropertyFloat propFloat))
                return StatType.Float;
            else if (Enum.TryParse(operand, out PropertyBool propBool))
                return StatType.Bool;
            else if (Enum.TryParse(operand, out PropertyDataId propDID))
                return StatType.DataID;
            else
                return StatType.Undef;
        }

19 View Source File : IL.cs
License : MIT License
Project Creator : 71

private static void Emit(CodeGeneratorContext context, IOperation expression, bool used, Action next)
        {
            // Check if we're emitting a method call matching an IL call signature.
            if (expression is IInvocationExpression invocation)
            {
                var target = invocation.TargetMethod;

                if (!target.IsStatic ||
                    target.ReturnType.MetadataName != "Void" ||
                    target.ContainingType?.MetadataName != nameof(IL))
                    goto Default;

                // We got this far, so we're emitting raw IL
                // Find the opcode
                int start = 0;
                var invocationArgs = invocation.ArgumentsInSourceOrder;

                if (!Enum.TryParse(target.Name, out ILOpCode opcode))
                {
                    if (target.Name != nameof(Emit))
                        goto Default;

                    opcode = (ILOpCode)invocationArgs[0].Value.ConstantValue.Value;
                    start = 1;
                }

                // Find the (optional) argument
                if (invocationArgs.Length == start)
                {
                    // No argument, emit the opcode and return
                    context.EmitOpCode(opcode);

                    // Or there is a type parameter
                    if (target.IsGenericMethod)
                        context.EmitSymbolToken(target.TypeArguments[0], invocation.Syntax);

                    return;
                }

                // There is an argument, check it and emit it.
                var arg = invocationArgs[start];
                var val = arg.Value;

                if (val is IConversionExpression conversion && !conversion.IsExplicit)
                    val = conversion.Operand;

                if (val.ConstantValue.HasValue)
                {
                    // Constant value (not including typeof)
                    context.EmitOpCode(opcode);

                    object constantValue = val.ConstantValue.Value;

                    switch (opcode)
                    {
                        default:
                            context.EmitRawConstant(constantValue);
                            break;
                    }

                    return;
                }

                if (val is IInvocationExpression call)
                {
                    // Call: emit method token
                    context.EmitOpCode(opcode);
                    context.EmitSymbolToken(call.TargetMethod, call.Syntax);

                    return;
                }

                if (val is IFieldReferenceExpression field)
                {
                    // Field reference: emit field token
                    context.EmitOpCode(opcode);
                    context.EmitSymbolToken(field.Field, field.Syntax);

                    return;
                }

                if (val is IMethodBindingExpression method)
                {
                    // Method binding: emit method token
                    context.EmitOpCode(opcode);
                    context.EmitSymbolToken(method.Method, method.Syntax);

                    return;
                }

                if (val is ITypeOfExpression type)
                {
                    // Type reference: emit type
                    context.EmitOpCode(opcode);
                    context.EmitSymbolToken(type.TypeOperand, type.Syntax);

                    return;
                }

                // Throwing here is bad, but we don't have much of a choice.
                // Instead, Emit() throws, so we'll have a runtime exception.
            }

            Default: next();
        }

19 View Source File : LootParser.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public static ChanceTable<SpellId> ParseChanceTable_Spell(string[] lines, int startLine)
        {
            var chanceTable = new ChanceTable<SpellId>();

            for (var i = startLine + 1; i < lines.Length; i++)
            {
                var line = lines[i].Trim();

                if (line.Length < 2)
                    continue;

                if (line.Length == 2)
                    break;

                if (line.StartsWith("//"))
                    continue;

                var match = Regex.Match(line, @"SpellId.([^,]+),\s+([\d.]+)");

                if (!match.Success || !System.Enum.TryParse(match.Groups[1].Value, out SpellId spell) || !float.TryParse(match.Groups[2].Value, out var chance))
                {
                    Console.WriteLine($"Couldn't parse {line}");
                    continue;
                }
                chanceTable.Add((spell, chance));
            }

            return chanceTable;
        }

19 View Source File : VisibleIfTypeConverter.cs
License : MIT License
Project Creator : ABTSoftware

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var modifierType = (ModifierType)value;

            ModifierType desiredType;
            var hasTypeParam = Enum.TryParse((string)parameter, out desiredType); 

            if(hasTypeParam && 
                modifierType == desiredType)
            {
                return Visibility.Visible;
            }

            return Visibility.Collapsed;
        }

19 View Source File : LootParser.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public static ChanceTable<TreasureArmorType> ParseChanceTable_ArmorType(string[] lines, int startLine)
        {
            var chanceTable = new ChanceTable<TreasureArmorType>();

            for (var i = startLine + 1; i < lines.Length; i++)
            {
                var line = lines[i].Trim();

                if (line.Length < 2)
                    continue;

                if (line.Length == 2)
                    break;

                if (line.StartsWith("//"))
                    continue;

                var match = Regex.Match(line, @"TreasureArmorType.([^,]+),\s+([\d.]+)");

                if (!match.Success || !System.Enum.TryParse(match.Groups[1].Value, out TreasureArmorType armorType) || !float.TryParse(match.Groups[2].Value, out var chance))
                {
                    Console.WriteLine($"Couldn't parse {line}");
                    continue;
                }
                chanceTable.Add((armorType, chance));
            }

            return chanceTable;
        }

19 View Source File : LootParser.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public static ChanceTable<TreasureHeritageGroup> ParseChanceTable_Heritage(string[] lines, int startLine)
        {
            var chanceTable = new ChanceTable<TreasureHeritageGroup>();

            for (var i = startLine + 1; i < lines.Length; i++)
            {
                var line = lines[i].Trim();

                if (line.Length < 2)
                    continue;

                if (line.Length == 2)
                    break;

                if (line.StartsWith("//"))
                    continue;

                var match = Regex.Match(line, @"TreasureHeritageGroup.([^,]+),\s+([\d.]+)");

                if (!match.Success || !System.Enum.TryParse(match.Groups[1].Value, out TreasureHeritageGroup heritage) || !float.TryParse(match.Groups[2].Value, out var chance))
                {
                    Console.WriteLine($"Couldn't parse {line}");
                    continue;
                }
                chanceTable.Add((heritage, chance));
            }

            return chanceTable;
        }

19 View Source File : LineSeriesAppendingSpeedTest.xaml.cs
License : MIT License
Project Creator : ABTSoftware

public void Execute(TestParameters testParameters, TimeSpan duration, Action<double> fpsResult)
        {
            var testParams = testParameters as LineAppendTestParameters;

            ResamplingMode rMode;
            if (!Enum.TryParse(testParams.SamplingMode.ToString(), out rMode)) rMode = ResamplingMode.MinMax;

            line0.AntiAliasing = testParameters.AntiAliasing;
            line0.ResamplingMode = rMode;

            line1.AntiAliasing = testParameters.AntiAliasing;
            line1.ResamplingMode = rMode;

            line2.AntiAliasing = testParameters.AntiAliasing;
            line2.ResamplingMode = rMode;

            var dataset = new DataSeriesSet<double, double>();
            dataset.Add(_mainSeries);
            dataset.Add(_maLowSeries);
            dataset.Add(_maHighSeries);
            sciChart.DataSet = dataset;

            xBuffer = new double[testParams.IncrementPoints];
            yBuffer = new double[testParams.IncrementPoints];
            maLowBuffer = new double[testParams.IncrementPoints];
            maHighBuffer = new double[testParams.IncrementPoints];

            // Execute
            //

            // Prime the chart with initial points
            using (sciChart.SuspendUpdates())
                AppendData(testParams.PointCount, testParams.Noisyness);

            // Start the test runner 
            _testRunner = new CompositionTestRunner(duration, () => OnAppendData(testParams.Noisyness), fpsResult);
            sciChart.Rendered += _testRunner.OnSciChartRendered;
            _testRunner.Run();
        }

19 View Source File : Creature.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public void GenerateNewFace()
        {
            var cg = DatManager.PortalDat.CharGen;

            if (!Heritage.HasValue)
            {
                if (!string.IsNullOrEmpty(HeritageGroupName) && Enum.TryParse(HeritageGroupName.Replace("'", ""), true, out HeritageGroup heritage))
                    Heritage = (int)heritage;
            }

            if (!Gender.HasValue)
            {
                if (!string.IsNullOrEmpty(Sex) && Enum.TryParse(Sex, true, out Gender gender))
                    Gender = (int)gender;
            }

            if (!Heritage.HasValue || !Gender.HasValue)
            {
#if DEBUG
                //if (!(NpcLooksLikeObject ?? false))
                    //log.Debug($"Creature.GenerateNewFace: {Name} (0x{Guid}) - wcid {WeenieClreplacedId} - Heritage: {Heritage} | HeritageGroupName: {HeritageGroupName} | Gender: {Gender} | Sex: {Sex} - Data missing or unparsable, Cannot randomize face.");
#endif
                return;
            }

            if (!cg.HeritageGroups.TryGetValue((uint)Heritage, out var heritageGroup) || !heritageGroup.Genders.TryGetValue((int)Gender, out var sex))
            {
#if DEBUG
                log.Debug($"Creature.GenerateNewFace: {Name} (0x{Guid}) - wcid {WeenieClreplacedId} - Heritage: {Heritage} | HeritageGroupName: {HeritageGroupName} | Gender: {Gender} | Sex: {Sex} - Data invalid, Cannot randomize face.");
#endif
                return;
            }

            PaletteBaseId = sex.BasePalette;

            var appearance = new Appearance
            {
                HairStyle = 1,
                HairColor = 1,
                HairHue = 1,

                EyeColor = 1,
                Eyes = 1,

                Mouth = 1,
                Nose = 1,

                SkinHue = 1
            };

            // Get the hair first, because we need to know if you're bald, and that's the name of that tune!
            if (sex.HairStyleList.Count > 1)
            {
                if (PropertyManager.GetBool("npc_hairstyle_fullrange").Item)
                    appearance.HairStyle = (uint)ThreadSafeRandom.Next(0, sex.HairStyleList.Count - 1);
                else
                    appearance.HairStyle = (uint)ThreadSafeRandom.Next(0, Math.Min(sex.HairStyleList.Count - 1, 8)); // retail range data compiled by OptimShi
            }
            else
                appearance.HairStyle = 0;

            if (sex.HairStyleList.Count < appearance.HairStyle)
            {
                log.Warn($"Creature.GenerateNewFace: {Name} (0x{Guid}) - wcid {WeenieClreplacedId} - HairStyle = {appearance.HairStyle} | HairStyleList.Count = {sex.HairStyleList.Count} - Data invalid, Cannot randomize face.");
                return;
            }

            var hairstyle = sex.HairStyleList[Convert.ToInt32(appearance.HairStyle)];

            appearance.HairColor = (uint)ThreadSafeRandom.Next(0, sex.HairColorList.Count - 1);
            appearance.HairHue = ThreadSafeRandom.Next(0.0f, 1.0f);

            appearance.EyeColor = (uint)ThreadSafeRandom.Next(0, sex.EyeColorList.Count - 1);
            appearance.Eyes = (uint)ThreadSafeRandom.Next(0, sex.EyeStripList.Count - 1);

            appearance.Mouth = (uint)ThreadSafeRandom.Next(0, sex.MouthStripList.Count - 1);

            appearance.Nose = (uint)ThreadSafeRandom.Next(0, sex.NoseStripList.Count - 1);

            appearance.SkinHue = ThreadSafeRandom.Next(0.0f, 1.0f);

            //// Certain races (Undead, Tumeroks, Others?) have multiple body styles available. This is controlled via the "hair style".
            ////if (hairstyle.AlternateSetup > 0)
            ////    character.SetupTableId = hairstyle.AlternateSetup;

            if (!EyesTextureDID.HasValue)
                EyesTextureDID = sex.GetEyeTexture(appearance.Eyes, hairstyle.Bald);
            if (!DefaultEyesTextureDID.HasValue)
                DefaultEyesTextureDID = sex.GetDefaultEyeTexture(appearance.Eyes, hairstyle.Bald);
            if (!NoseTextureDID.HasValue)
                NoseTextureDID = sex.GetNoseTexture(appearance.Nose);
            if (!DefaultNoseTextureDID.HasValue)
                DefaultNoseTextureDID = sex.GetDefaultNoseTexture(appearance.Nose);
            if (!MouthTextureDID.HasValue)
                MouthTextureDID = sex.GetMouthTexture(appearance.Mouth);
            if (!DefaultMouthTextureDID.HasValue)
                DefaultMouthTextureDID = sex.GetDefaultMouthTexture(appearance.Mouth);
            if (!HeadObjectDID.HasValue)
                HeadObjectDID = sex.GetHeadObject(appearance.HairStyle);

            // Skin is stored as PaletteSet (list of Palettes), so we need to read in the set to get the specific palette
            var skinPalSet = DatManager.PortalDat.ReadFromDat<PaletteSet>(sex.SkinPalSet);
            if (!SkinPaletteDID.HasValue)
                SkinPaletteDID = skinPalSet.GetPaletteID(appearance.SkinHue);

            // Hair is stored as PaletteSet (list of Palettes), so we need to read in the set to get the specific palette
            var hairPalSet = DatManager.PortalDat.ReadFromDat<PaletteSet>(sex.HairColorList[Convert.ToInt32(appearance.HairColor)]);
            if (!HairPaletteDID.HasValue)
                HairPaletteDID = hairPalSet.GetPaletteID(appearance.HairHue);

            // Eye Color
            if (!EyesPaletteDID.HasValue)
                EyesPaletteDID = sex.EyeColorList[Convert.ToInt32(appearance.EyeColor)];
        }

19 View Source File : MudHub.cs
License : GNU Lesser General Public License v3.0
Project Creator : 8720826

public async Task NpcAction(NpcCommandAction commandAction)
        {
            var result = await DoCommand(async () => {
                var playerId = _account.PlayerId;

                var npcId = commandAction.NpcId;
                var commandId = commandAction.Action.CommandId;
                var commandName = commandAction.Action.Name;
                var input = commandAction.Action.Message;
                var scriptId = commandAction.Action.ScriptId;



                if (scriptId > 0)
                {
                    var command = new NpcScriptCommand(playerId, commandAction.NpcId, commandAction.Action.ScriptId, commandAction.Action.CommandId,  commandAction.Action.Message);
                    await _bus.SendCommand(command);
                }
                else
                {
                    NpcActionEnum actionEnum;
                    if (Enum.TryParse(commandName, out actionEnum))
                    {
                        switch (actionEnum)
                        {
                            case NpcActionEnum.闲聊:

                                await _bus.SendCommand(new ChatWithNpcCommand(playerId, commandAction.NpcId));

                                break;

                            case NpcActionEnum.切磋:

                                await _bus.SendCommand(new FightWithNpcCommand(playerId, commandAction.NpcId));

                                break;

                            case NpcActionEnum.杀死:

                                await _bus.SendCommand(new KillNpcCommand(playerId, commandAction.NpcId));

                                break;

                            case NpcActionEnum.给予:

                                await _bus.SendCommand(new GiveToNpcCommand(playerId, commandAction.NpcId));

                                break;

                            case NpcActionEnum.拜师:

                                await _bus.SendCommand(new ApprenticeToNpcCommand(playerId, commandAction.NpcId));

                                break;

                            case NpcActionEnum.出师:

                                await _bus.SendCommand(new FinishApprenticeToNpcCommand(playerId, commandAction.NpcId));

                                break;

                            case NpcActionEnum.查看武功:

                                await _bus.SendCommand(new ShowNpcSkillCommand(playerId, commandAction.NpcId));

                                break;
                                
                        }
                    }
                }


            });
        }

19 View Source File : ActionStepDefinitionReferenceConverter.cs
License : MIT License
Project Creator : actions

public override object ReadJson(
            JsonReader reader,
            Type objectType,
            Object existingValue,
            JsonSerializer serializer)
        {
            if (reader.TokenType != JsonToken.StartObject)
            {
                return null;
            }

            JObject value = JObject.Load(reader);
            if (value.TryGetValue("Type", StringComparison.OrdinalIgnoreCase, out JToken actionTypeValue))
            {
                ActionSourceType actionType;
                if (actionTypeValue.Type == JTokenType.Integer)
                {
                    actionType = (ActionSourceType)(Int32)actionTypeValue;
                }
                else if (actionTypeValue.Type != JTokenType.String || !Enum.TryParse((String)actionTypeValue, true, out actionType))
                {
                    return null;
                }

                ActionStepDefinitionReference reference = null;
                switch (actionType)
                {
                    case ActionSourceType.Repository:
                        reference = new RepositoryPathReference();
                        break;

                    case ActionSourceType.ContainerRegistry:
                        reference = new ContainerRegistryReference();
                        break;

                    case ActionSourceType.Script:
                        reference = new ScriptReference();
                        break;
                }

                using (var objectReader = value.CreateReader())
                {
                    serializer.Populate(objectReader, reference);
                }

                return reference;
            }
            else
            {
                return null;
            }
        }

19 View Source File : LineSeriesAppendingSpeedTest.xaml.cs
License : MIT License
Project Creator : ABTSoftware

public void Execute(TestParameters testParameters, TimeSpan duration, Action<double> fpsResult)
        {
            var testParams = testParameters as LineAppendTestParameters;

            ResamplingMode rMode;
            if (!Enum.TryParse(testParams.SamplingMode.ToString(), out rMode)) rMode = ResamplingMode.MinMax;
           
            line0.DataSeries = _mainSeries; 
            line0.AntiAliasing = testParameters.AntiAliasing;
            line0.StrokeThickness = (int) testParameters.StrokeThickness;
            line0.ResamplingMode = rMode;

            line1.DataSeries = _maLowSeries; 
            line1.AntiAliasing = testParameters.AntiAliasing;
            line1.StrokeThickness = (int)testParameters.StrokeThickness;
            line1.ResamplingMode = rMode;

            line2.DataSeries = _maHighSeries;
            line2.AntiAliasing = testParameters.AntiAliasing;
            line2.StrokeThickness = (int)testParameters.StrokeThickness;
            line2.ResamplingMode = rMode;

            xBuffer = new double[testParams.IncrementPoints];
            yBuffer = new double[testParams.IncrementPoints];
            maLowBuffer = new double[testParams.IncrementPoints];
            maHighBuffer = new double[testParams.IncrementPoints];

            // Execute
            //

            // Prime the chart with initial points
            using (sciChart.SuspendUpdates())
                AppendData(testParams.PointCount, testParams.Noisyness);

            // Start the test runner 
            if (testParameters.TestRunner == TestRunnerType.Composition)
                _testRunner = new CompositionTestRunner(duration, () => OnAppendData(testParams.Noisyness), fpsResult);
            else
                _testRunner = new DispatcherTimerRunner(duration, () => OnAppendData(testParams.Noisyness), fpsResult);


            sciChart.Rendered += _testRunner.OnSciChartRendered;
            _testRunner.Run();
        }

19 View Source File : IncorrectDeclarationOfDacKeyFix.cs
License : GNU General Public License v3.0
Project Creator : Acumatica

private void RegisterCodeFixForUniqueKeys(CodeFixContext context, ClreplacedDeclarationSyntax dacNode, SyntaxNode root, ClreplacedDeclarationSyntax keyNode, 
												  Diagnostic diagnostic)
		{
			bool isMultipleUniqueKeysFix = diagnostic.Properties.TryGetValue(nameof(UniqueKeyCodeFixType), out string uniqueCodeFixTypeString) &&
										   !uniqueCodeFixTypeString.IsNullOrWhiteSpace() &&
										   Enum.TryParse(uniqueCodeFixTypeString, out UniqueKeyCodeFixType uniqueCodeFixType) &&
										   uniqueCodeFixType == UniqueKeyCodeFixType.MultipleUniqueKeys;
			if (isMultipleUniqueKeysFix)
			{
				List<ClreplacedDeclarationSyntax> keyNodesNotInUK = GetAllKeyNodesNotInContainer(diagnostic, root, keyNode);
				var codeActionreplacedle = nameof(Resources.PX1036MultipleUKFix).GetLocalized().ToString();
				var codeAction = CodeAction.Create(codeActionreplacedle,
												   cancellation => MultipleKeyNotInContainerDeclarationsFixAsync(context.Doreplacedent, root, keyNodesNotInUK, dacNode,
																												 RefIntegrityDacKeyType.UniqueKey, cancellation),
												   equivalenceKey: codeActionreplacedle);

				context.RegisterCodeFix(codeAction, context.Diagnostics);
			}
			else if (keyNode.Identifier.Text != ReferentialIntegrity.UniqueKeyClreplacedName)
			{
				var codeActionreplacedle = nameof(Resources.PX1036SingleUKFix).GetLocalized().ToString();
				var codeAction = CodeAction.Create(codeActionreplacedle,
												   cancellation => ChangeKeyNameAsync(context.Doreplacedent, dacNode, root, keyNode,
																					  ReferentialIntegrity.UniqueKeyClreplacedName,
																					  shouldChangeLocation: false, cancellation),
												   equivalenceKey: codeActionreplacedle);

				context.RegisterCodeFix(codeAction, context.Diagnostics);
			}
		}

19 View Source File : ExprDeserializer.cs
License : MIT License
Project Creator : 0x1000000

private static FrameBorderDirection ReadFrameBorderDirection<TNode>(TNode rootElement, IExprReader<TNode> reader, string name)
        {
            var str = ReadNullableString(rootElement, reader, name);
            if (str == null)
            {
                throw new SqExpressException($"Property \"{name}\" is mandatory");
            }

            if (!Enum.TryParse(str, false, out FrameBorderDirection result))
            {
                throw new SqExpressException($"Could not recognize \"{str}\" as \"{nameof(FrameBorderDirection)}\"");
            }

            return result;
        }

19 View Source File : PublicClassXmlCommentFix.cs
License : GNU General Public License v3.0
Project Creator : Acumatica

public override Task RegisterCodeFixesAsync(CodeFixContext context)
		{
			context.CancellationToken.ThrowIfCancellationRequested();

			var diagnostic = context.Diagnostics
				.FirstOrDefault(d => d.Id.Equals(Descriptors.PX1007_PublicClreplacedXmlComment.Id));

			if (diagnostic?.Properties == null || 
				!diagnostic.Properties.TryGetValue(XmlreplacedyzerConstants.XmlCommentParseResultKey, out string value) ||
				!Enum.TryParse(value, out XmlCommentParseResult parseResult) ||
				parseResult == XmlCommentParseResult.HasExcludeTag || parseResult == XmlCommentParseResult.HasNonEmptySummaryTag)
			{
				return Task.CompletedTask;
			}

			var addDescriptionreplacedle = nameof(Resources.PX1007FixAddDescription).GetLocalized().ToString();
			var addDescriptionAction = CodeAction.Create(
				addDescriptionreplacedle,
				cancellation => AddDescriptionAsync(context.Doreplacedent, context.Span, parseResult, cancellation),
				equivalenceKey: addDescriptionreplacedle);
			context.RegisterCodeFix(addDescriptionAction, context.Diagnostics);

			var excludeClreplacedreplacedle = nameof(Resources.PX1007FixExcludeClreplaced).GetLocalized().ToString();
			var excludeClreplacedAction = CodeAction.Create(
				excludeClreplacedreplacedle,
				cancellation => ExcludeClreplacedAsync(context.Doreplacedent, context.Span, cancellation),
				equivalenceKey: excludeClreplacedreplacedle);
			context.RegisterCodeFix(excludeClreplacedAction, context.Diagnostics);

			return Task.CompletedTask;
		}

19 View Source File : AccountCommands.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

[CommandHandler("accountcreate", AccessLevel.Admin, CommandHandlerFlag.None, 2,
            "Creates a new account.",
            "username preplacedword (accesslevel)\n" +
            "accesslevel can be a number or enum name\n" +
            "0 = Player | 1 = Advocate | 2 = Sentinel | 3 = Envoy | 4 = Developer | 5 = Admin")]
        public static void HandleAccountCreate(Session session, params string[] parameters)
        {
            AccessLevel defaultAccessLevel = (AccessLevel)Common.ConfigManager.Config.Server.Accounts.DefaultAccessLevel;

            if (!Enum.IsDefined(typeof(AccessLevel), defaultAccessLevel))
                defaultAccessLevel = AccessLevel.Player;

            var accessLevel = defaultAccessLevel;

            if (parameters.Length > 2)
            {
                if (Enum.TryParse(parameters[2], true, out accessLevel))
                {
                    if (!Enum.IsDefined(typeof(AccessLevel), accessLevel))
                        accessLevel = defaultAccessLevel;
                }
            }

            string articleAorAN = "a";
            if (accessLevel == AccessLevel.Advocate || accessLevel == AccessLevel.Admin || accessLevel == AccessLevel.Envoy)
                articleAorAN = "an";

            string message = "";

            var accountExists = DatabaseManager.Authentication.GetAccountByName(parameters[0]);
                      
            if (accountExists != null)
            {
                message= "Account already exists. Try a new name.";
            }
            else
            {
                try
                {
                    var account = DatabaseManager.Authentication.CreateAccount(parameters[0].ToLower(), parameters[1], accessLevel, IPAddress.Parse("127.0.0.1"));

                    if (DatabaseManager.AutoPromoteNextAccountToAdmin && accessLevel == AccessLevel.Admin)
                        DatabaseManager.AutoPromoteNextAccountToAdmin = false;

                    message = ("Account successfully created for " + account.AccountName + " (" + account.AccountId + ") with access rights as " + articleAorAN + " " + Enum.GetName(typeof(AccessLevel), accessLevel) + ".");
                }
                catch
                {
                    message = "Account already exists. Try a new name.";
                }
            }

            CommandHandlerHelper.WriteOutputInfo(session, message, ChatMessageType.WorldBroadcast);
        }

19 View Source File : FSDirectorySearchProvider.cs
License : MIT License
Project Creator : Adoxio

public override void Initialize(string name, NameValueCollection config)
		{
			if (config == null)
			{
				throw new ArgumentNullException("config");
			}

			if (string.IsNullOrEmpty(name))
			{
				name = GetType().Name;
			}

			base.Initialize(name, config);

			var dataContextName = config["dataContextName"];

			SearchDataContextName = config["searchDataContextName"] ?? dataContextName;
			UpdateDataContextName = config["updateDataContextName"] ?? dataContextName;

			var indexPath = config["indexPath"];

			if (string.IsNullOrEmpty(indexPath))
			{
				throw new ProviderException("The search provider {0} requires the attribute indexPath to be set.".FormatWith(name));
			}

			IndexDirectory = new DirectoryInfo(
				(indexPath.StartsWith(@"~/", StringComparison.Ordinal) || indexPath.StartsWith(@"~\", StringComparison.Ordinal))
					? HostingEnvironment.MapPath(indexPath) ?? indexPath
					: indexPath);

			var useEncryptedDirectory = false;
			bool.TryParse(config["useEncryptedDirectory"], out useEncryptedDirectory);
			UseEncryptedDirectory = useEncryptedDirectory;

			var isOnlinePortal = false;
			bool.TryParse(config["isOnlinePortal"], out isOnlinePortal);
			IsOnlinePortal = isOnlinePortal;

			IndexQueryName = config["indexQueryName"] ?? _defaultIndexQueryName;
			Stemmer = CultureInfo.CurrentUICulture.Parent.EnglishName;

			var stopWords = config["stopWords"];

			StopWords = string.IsNullOrEmpty(stopWords)
				? new string[] { }
				: stopWords.Split(',').Select(word => word.Trim()).Where(word => !string.IsNullOrEmpty(word)).ToArray();

			var searcherCacheMode = config["indexSearcherCacheMode"];

			IndexSearcherCacheMode mode;

			_searcherPool = !string.IsNullOrEmpty(searcherCacheMode) && Enum.TryParse(searcherCacheMode, out mode) && mode == IndexSearcherCacheMode.SingleUse
				? new SingleUseIndexSearcherPool()
				: _sharedSearcherPool;

			var indexVersion = config["indexVersion"];

			Version version;

			Version = !string.IsNullOrEmpty(indexVersion) && Enum.TryParse(indexVersion, out version)
				? version
				: Version.LUCENE_23;

			Guid websiteId;
			WebsiteId = Guid.TryParse(config["websiteId"], out websiteId)
				? websiteId
				: (Guid?)null;

			var recognizedAttributes = new List<string>
			{
				"name",
				"description",
				"dataContextName",
				"indexPath",
				"indexQueryName",
				"indexSearcherCacheMode",
				"indexVersion",
				"searchDataContextName",
				"stemmer",
				"stopWords",
				"updateDataContextName",
				"isOnlinePortal",
				"useEncryptedDirectory",
				"websiteId",
			};

			// Remove all of the known configuration values. If there are any left over, they are unrecognized.
			recognizedAttributes.ForEach(config.Remove);

			if (config.Count > 0)
			{
				var unrecognizedAttribute = config.GetKey(0);

				if (!string.IsNullOrEmpty(unrecognizedAttribute))
				{
					throw new ProviderException("The search provider {0} does not currently recognize or support the attribute {1}.".FormatWith(name, unrecognizedAttribute));
				}
			}
		}

19 View Source File : PlayerActionCommandHandler.cs
License : GNU Lesser General Public License v3.0
Project Creator : 8720826

public async Task<Unit> Handle(PlayerActionCommand command, CancellationToken cancellationToken)
        {

            var targetId = command.TargetId;
            var playerId = command.PlayerId;
            var commandName = command.CommandName;

            var player = await _playerDomainService.Get(playerId);
            if (player == null)
            {
                await _bus.RaiseEvent(new DomainNotification($"角色不存在!"));
                return Unit.Value;
            }

            var target = await _playerDomainService.Get(targetId);
            if (target == null)
            {
                await _bus.RaiseEvent(new DomainNotification($"npc不存在!"));
                return Unit.Value;
            }


            //await DoPlayerAction(player, target, commandName);

            PlayerActionEnum actionEnum;
            if (!Enum.TryParse(commandName, out actionEnum))
            {
                return Unit.Value;
            }

            switch (actionEnum)
            {
                case PlayerActionEnum.添加好友:
                    await Friend(player, target);
                    break;

                case PlayerActionEnum.割袍断义:
                    await UnFriend(player, target);
                    break;

                case PlayerActionEnum.查看武功:
                    await ShowFriendSkill(player, target);
                    break;
            }

            if (await Commit())
            {
                //Do nothing
            }

            return Unit.Value;
        }

19 View Source File : UploadCommand.cs
License : MIT License
Project Creator : Adoxio

private static void CreateFiles(ICommandContext commandContext, DirectoryUploadInfo uploadInfo, IEnumerable<HttpPostedFile> files, EnreplacedyReference publishingState, out List<string> @select, out List<Tuple<string, string>> errors)
		{
			@select = new List<string>();
			errors = new List<Tuple<string, string>>();
			
			var dataAdapterDependencies = new PortalConfigurationDataAdapterDependencies();
			var annotationDataAdapter = new AnnotationDataAdapter(dataAdapterDependencies);
			var website = HttpContext.Current.GetWebsite();

			var location = website.Settings.Get<string>("WebFiles/StorageLocation");

			StorageLocation storageLocation;
			if (!Enum.TryParse(location, true, out storageLocation))
			{
				storageLocation = StorageLocation.CrmDoreplacedent;
			}

			var maxFileSizeErrorMessage = website.Settings.Get<string>("WebFiles/MaxFileSizeErrorMessage");

			var annotationSettings = new AnnotationSettings(dataAdapterDependencies.GetServiceContext(),
				storageLocation: storageLocation, maxFileSizeErrorMessage: maxFileSizeErrorMessage);
						
			foreach (var file in files)
			{
				var serviceContext = commandContext.CreateServiceContext();

				try
				{
					var webFile = new Enreplacedy("adx_webfile");

					var fileName = Path.GetFileName(file.FileName);

					webFile.Attributes["adx_name"] = fileName;
					webFile.Attributes["adx_partialurl"] = GetPartialUrlFromFileName(fileName);
					webFile.Attributes["adx_websiteid"] = website.Enreplacedy.ToEnreplacedyReference();
					webFile.Attributes["adx_publishingstateid"] = publishingState;
					webFile.Attributes["adx_hiddenfromsitemap"] = true;
					webFile.Attributes[uploadInfo.WebFileForeignKeyAttribute] = uploadInfo.EnreplacedyReference;

					serviceContext.AddObject(webFile);
					serviceContext.SaveChanges();

					annotationDataAdapter.CreateAnnotation(new Annotation
					{
						Regarding = webFile.ToEnreplacedyReference(),
						FileAttachment = AnnotationDataAdapter.CreateFileAttachment(new HttpPostedFileWrapper(file), annotationSettings.StorageLocation)
					}, annotationSettings);

					@select.Add(new DirectoryContentHash(webFile.ToEnreplacedyReference()).ToString());
				}
				catch (Exception e)
				{
					ADXTrace.Instance.TraceError(TraceCategory.Application, string.Format(@"Exception uploading file: {0}",  e.ToString()));

                    errors.Add(new Tuple<string, string>(file.FileName, e.Message));
				}
			}
		}

19 View Source File : CharacterCommands.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

[CommandHandler("set-characteraccess", AccessLevel.Admin, CommandHandlerFlag.None, 1,
            "Sets the access level for the character",
            "charactername (accesslevel)\n" +
            "accesslevel can be a number or enum name\n" +
            "0 = Player | 1 = Advocate | 2 = Sentinel | 3 = Envoy | 4 = Developer | 5 = Admin")]
        public static void HandleCharacterTokenization(Session session, params string[] parameters)
        {
            string characterName = parameters[0];

            AccessLevel accessLevel = AccessLevel.Player;
            if (parameters.Length > 1)
                if (Enum.TryParse(parameters[1], true, out accessLevel))
                    if (!Enum.IsDefined(typeof(AccessLevel), accessLevel))
                        accessLevel = AccessLevel.Player;

            DatabaseManager.Shard.SetCharacterAccessLevelByName(characterName.ToLower(), accessLevel, ((uint characterId) =>
            {
                if (characterId > 0)
                {
                    string articleAorAN = "a";
                    if (accessLevel == AccessLevel.Advocate || accessLevel == AccessLevel.Admin || accessLevel == AccessLevel.Envoy)
                        articleAorAN = "an";

                    CommandHandlerHelper.WriteOutputInfo(session, "Character " + characterName + " has been made " + articleAorAN + " " + Enum.GetName(typeof(AccessLevel), accessLevel) + ".", ChatMessageType.Broadcast);
                }
                else
                {
                    CommandHandlerHelper.WriteOutputInfo(session, "There is no character by the name of " + characterName + " found in the database. Has it been deleted?", ChatMessageType.Broadcast);
                }
            }));
        }

19 View Source File : FetchXml.cs
License : MIT License
Project Creator : Adoxio

private CrmEnreplacedyPermissionRight GetRight(Context context)
		{
			string right;
			CrmEnreplacedyPermissionRight parsedRight;

			return TryGetAttributeValue(context, "right", out right) && Enum.TryParse(right, true, out parsedRight)
				? parsedRight
				: CrmEnreplacedyPermissionRight.Read;
		}

19 View Source File : ExprDeserializer.cs
License : MIT License
Project Creator : 0x1000000

private static ExprJoinedTable.ExprJoinType ReadExprJoinType<TNode>(TNode rootElement, IExprReader<TNode> reader, string name)
        {
            var str = ReadNullableString(rootElement, reader, name);
            if (str == null)
            {
                throw new SqExpressException($"Property \"{name}\" is mandatory");
            }

            if (!Enum.TryParse(str, false, out ExprJoinedTable.ExprJoinType result))
            {
                throw new SqExpressException($"Could not recognize \"{str}\" as \"{nameof(ExprJoinedTable.ExprJoinType)}\"");
            }

            return result;
        }

19 View Source File : PhoneInput.cs
License : GNU General Public License v3.0
Project Creator : aedenthorn

public static void PressKey(MobileApp app)
        {
            if(app.closePhone)
                PhoneUtils.TogglePhone(false);

            if (!Enum.TryParse(app.keyPress, out SButton keyPress))
            {
                Monitor.Log($"Error on app invoke: {app.keyPress} isn't a valid key", LogLevel.Error);
                return;
            }

            // get SMAPI's input handler
            var input = Game1.input;

            // get OverrideButton method
            var method = input.GetType().GetMethod("OverrideButton");
            if (method == null)
            {
                Monitor.Log("Can't find 'OverrideButton' method on SMAPI's input clreplaced.", LogLevel.Error);
                return;
            }

            // call method
            // The arguments are the button to override, and whether to mark the button pressed (true) or raised (false)
            method.Invoke(input, new object[] { keyPress, true });
            return;
        }

19 View Source File : PlayerCommands.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

[CommandHandler("config", AccessLevel.Player, CommandHandlerFlag.RequiresWorld, 1, "Manually sets a character option on the server.\nUse /config list to see a list of settings.", "<setting> <on/off>")]
        public static void HandleConfig(Session session, params string[] parameters)
        {
            if (!PropertyManager.GetBool("player_config_command").Item)
            {
                session.Network.EnqueueSend(new GameMessageSystemChat("The command \"config\" is not currently enabled on this server.", ChatMessageType.Broadcast));
                return;
            }

            // /config list - show character options
            if (parameters[0].Equals("list", StringComparison.OrdinalIgnoreCase))
            {
                foreach (var line in configList)
                    session.Network.EnqueueSend(new GameMessageSystemChat(line, ChatMessageType.Broadcast));

                return;
            }

            // translate GDLE CharacterOptions for existing plugins
            if (!translateOptions.TryGetValue(parameters[0], out var param) || !Enum.TryParse(param, out CharacterOption characterOption))
            {
                session.Network.EnqueueSend(new GameMessageSystemChat($"Unknown character option: {parameters[0]}", ChatMessageType.Broadcast));
                return;
            }

            var option = session.Player.GetCharacterOption(characterOption);

            // modes of operation:
            // on / off / toggle

            // - if none specified, default to toggle
            var mode = "toggle";

            if (parameters.Length > 1)
            {
                if (parameters[1].Equals("on", StringComparison.OrdinalIgnoreCase))
                    mode = "on";
                else if (parameters[1].Equals("off", StringComparison.OrdinalIgnoreCase))
                    mode = "off";
            }

            // set character option
            if (mode.Equals("on"))
                option = true;
            else if (mode.Equals("off"))
                option = false;
            else
                option = !option;

            session.Player.SetCharacterOption(characterOption, option);

            session.Network.EnqueueSend(new GameMessageSystemChat($"Character option {parameters[0]} is now {(option ? "on" : "off")}.", ChatMessageType.Broadcast));

            // update client
            session.Network.EnqueueSend(new GameEventPlayerDescription(session));
        }

19 View Source File : DellFanManagementGuiForm.cs
License : GNU General Public License v3.0
Project Creator : AaronKelley

private void ApplyConfiguration()
        {
            // The tray icon is enabled by default; disable only if that has been explicitly set.
            if (_configurationStore.GetIntOption(ConfigurationOption.TrayIconEnabled) == 0)
            {
                trayIconCheckBox.Checked = false;
            }

            // Similar for tray icon animation.
            if (_configurationStore.GetIntOption(ConfigurationOption.TrayIconAnimationEnabled) == 0)
            {
                animatedCheckBox.Checked = false;
            }

            // Consistency mode settings.
            int? lowerTemperatureThreshold = _configurationStore.GetIntOption(ConfigurationOption.ConsistencyModeLowerTemperatureThreshold);
            int? upperTemperatureThreshold = _configurationStore.GetIntOption(ConfigurationOption.ConsistencyModeUpperTemperatureThreshold);

            if (lowerTemperatureThreshold != null && lowerTemperatureThreshold >= 0 && lowerTemperatureThreshold < 100 &&
                upperTemperatureThreshold != null && upperTemperatureThreshold >= 0 && upperTemperatureThreshold < 100 &&
                lowerTemperatureThreshold <= upperTemperatureThreshold)
            {
                consistencyModeLowerTemperatureThresholdTextBox.Text = lowerTemperatureThreshold.ToString();
                consistencyModeUpperTemperatureThresholdTextBox.Text = upperTemperatureThreshold.ToString();
            }

            int? rpmThreshold = _configurationStore.GetIntOption(ConfigurationOption.ConsistencyModeRpmThreshold);
            if (rpmThreshold != null && rpmThreshold > 0 && rpmThreshold < 10000)
            {
                consistencyModeRpmThresholdTextBox.Text = rpmThreshold.ToString();
            }

            // Read previous operation mode from configuration.
            bool modeSet = false;
            if (Enum.TryParse(_configurationStore.GetStringOption(ConfigurationOption.OperationMode), out OperationMode operationMode))
            {
                switch (operationMode)
                {
                    case OperationMode.Automatic:
                        operationModeRadioButtonAutomatic.Checked = true;
                        modeSet = true;
                        break;
                    case OperationMode.Manual:
                        if (operationModeRadioButtonManual.Enabled)
                        {
                            operationModeRadioButtonManual.Checked = true;
                            modeSet = true;
                        }
                        break;
                    case OperationMode.Consistency:
                        if (operationModeRadioButtonConsistency.Enabled)
                        {
                            operationModeRadioButtonConsistency.Checked = true;
                            modeSet = true;
                        }
                        break;
                }
            }
            if (!modeSet)
            {
                // Default to automatic mode.
                operationModeRadioButtonAutomatic.Checked = true;
            }
        }

19 View Source File : ExprDeserializer.cs
License : MIT License
Project Creator : 0x1000000

private static ExprQueryExpressionType ReadExprQueryExpressionType<TNode>(TNode rootElement, IExprReader<TNode> reader, string name)
        {
            var str = ReadNullableString(rootElement, reader, name);
            if (str == null)
            {
                throw new SqExpressException($"Property \"{name}\" is mandatory");
            }

            if (!Enum.TryParse(str, false, out ExprQueryExpressionType result))
            {
                throw new SqExpressException($"Could not recognize \"{str}\" as \"{nameof(ExprQueryExpressionType)}\"");
            }

            return result;
        }

19 View Source File : ExprDeserializer.cs
License : MIT License
Project Creator : 0x1000000

private static DateAddDatePart ReadDateAddDatePart<TNode>(TNode rootElement, IExprReader<TNode> reader, string name)
        {
            var str = ReadNullableString(rootElement, reader, name);
            if (str == null)
            {
                throw new SqExpressException($"Property \"{name}\" is mandatory");
            }

            if (!Enum.TryParse(str, false, out DateAddDatePart result))
            {
                throw new SqExpressException($"Could not recognize \"{str}\" as \"{nameof(DateAddDatePart)}\"");
            }

            return result;
        }

19 View Source File : MudHub.cs
License : GNU Lesser General Public License v3.0
Project Creator : 8720826

public async Task PlayerAction(PlayerCommandAction commandAction)
        {
            var result = await DoCommand(async () => {
                var playerId = _account.PlayerId;
                var targetId = commandAction.TargetId;
                var commandName = commandAction.CommandName;

                PlayerActionEnum actionEnum;
                if (!Enum.TryParse(commandName, out actionEnum))
                {
                    return;
                }

                switch (actionEnum)
                {
                    case PlayerActionEnum.添加好友:
                        await _bus.SendCommand(new FriendToCommand(playerId, commandAction.TargetId));
                        break;

                    case PlayerActionEnum.割袍断义:
                        await _bus.SendCommand(new UnFriendToCommand(playerId, commandAction.TargetId));
                        break;

                    case PlayerActionEnum.查看武功:
                        await _bus.SendCommand(new ShowFriendSkillCommand(playerId, commandAction.TargetId));
                        break;
                }


            });
        }

19 View Source File : FifoLineSeriesSpeedTest.xaml.cs
License : MIT License
Project Creator : ABTSoftware

public void Execute(TestParameters testParameters, TimeSpan duration, Action<double> fpsResult)
        {
            // Setup
            var dataset = new DataSeriesSet<double, double>();
            _xyDataSeries = new XyDataSeries<double, double>() { FifoCapacity = testParameters.PointCount };
            dataset.Add(_xyDataSeries);
            sciChart.DataSet = dataset;

            this.lineSeries.AntiAliasing = testParameters.AntiAliasing;
            ResamplingMode resamplingMode;
            if (!Enum.TryParse(testParameters.SamplingMode.ToString(), out resamplingMode)) resamplingMode = ResamplingMode.MinMax;
            this.lineSeries.ResamplingMode = resamplingMode; 

            _generator = new RandomLinesGenerator();
            var initialData = _generator.GetRandomLinesSeries(testParameters.PointCount);
           _xyDataSeries.Append(initialData.XData, initialData.YData);

            // Execute
           _testRunner = new DispatcherTimerRunner(duration, OnAppendData, fpsResult);
           sciChart.Rendered += _testRunner.OnSciChartRendered;
            _testRunner.Run();
        }

19 View Source File : LootParser.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public static ChanceTable<TreasureItemType_Orig> ParseChanceTable_ItemType(string[] lines, int startLine)
        {
            var chanceTable = new ChanceTable<TreasureItemType_Orig>();

            for (var i = startLine + 1; i < lines.Length; i++)
            {
                var line = lines[i].Trim();

                if (line.Length < 2)
                    continue;

                if (line.Length == 2)
                    break;

                if (line.StartsWith("//"))
                    continue;

                var match = Regex.Match(line, @"TreasureItemType_Orig.([^,]+),\s+([\d.]+)");

                if (!match.Success || !System.Enum.TryParse(match.Groups[1].Value, out TreasureItemType_Orig itemType) || !float.TryParse(match.Groups[2].Value, out var chance))
                {
                    Console.WriteLine($"Couldn't parse {line}");
                    continue;
                }
                chanceTable.Add((itemType, chance));
            }

            return chanceTable;
        }

See More Examples