System.Enum.Parse(System.Type, string)

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

1701 Examples 7

19 View Source File : JcApiHelper_InitParam.cs
License : MIT License
Project Creator : 279328316

private static ParamModel GetParam(FieldInfo fi, int index = 0)
        {
            PTypeModel ptype = GetPType(fi.FieldType);
            int? value = null;
            if (fi.FieldType.IsEnum)
            {
                try
                {
                    value = Convert.ToInt32(Enum.Parse(fi.FieldType, fi.Name));
                }
                catch
                {   //如转换失败,忽略不做处理
                }
            }

            string fiId = null;
            if (fi.DeclaringType != null)
            {
                fiId = $"F:{fi.DeclaringType.ToString()}.{fi.Name}";
            }

            ParamModel param = new ParamModel()
            {
                Name = fi.Name,
                Id = fiId,
                PType = ptype,
                ParamValue = value,
                CustomAttrList = fi.CustomAttributes.Select(a => GetCustomAttribute(a)).ToList(),
                Position = index + 1
            };

            if (fi.CustomAttributes.Count() > 0)
            {

            }
            return param;
        }

19 View Source File : DOTweenAnimation.cs
License : MIT License
Project Creator : 39M

public static TargetType TypeToDOTargetType(Type t)
        {
            string str = t.ToString();
            int dotIndex = str.LastIndexOf(".");
            if (dotIndex != -1) str = str.Substring(dotIndex + 1);
            if (str.IndexOf("Renderer") != -1 && (str != "SpriteRenderer")) str = "Renderer";
            return (TargetType)Enum.Parse(typeof(TargetType), str);
        }

19 View Source File : StringExpand.cs
License : MIT License
Project Creator : 404Lcc

public static PanelType ToPanelType(this string name)
        {
            name = name.Substring(0, name.IndexOf("Panel"));
            return (PanelType)Enum.Parse(typeof(PanelType), name);
        }

19 View Source File : JsonExtension.cs
License : MIT License
Project Creator : 4egod

public static T ToEnum<T>(this string str)
        {
            var enumType = typeof(T);
            foreach (var name in Enum.GetNames(enumType))
            {
                var enumMemberAttribute = ((EnumMemberAttribute[])enumType.GetField(name).GetCustomAttributes(typeof(EnumMemberAttribute), true)).Single();
                if (enumMemberAttribute.Value == str) return (T)Enum.Parse(enumType, name);
            }
            //throw exception or whatever handling you want or
            return default(T);
        }

19 View Source File : EnumExtensions.cs
License : MIT License
Project Creator : 52ABP

public static void Each(this Type enumType, Action<string, string, string> action)
        {
            if (enumType.BaseType != typeof (Enum))
            {
                return;
            }
            var arr = Enum.GetValues(enumType);
            foreach (var name in arr)
            {
                var value = (int) Enum.Parse(enumType, name.ToString());
                var fieldInfo = enumType.GetField(name.ToString());
                var description = "";
                if (fieldInfo != null)
                {
                    var attr = Attribute.GetCustomAttribute(fieldInfo,
                        typeof (DescriptionAttribute), false) as DescriptionAttribute;
                    if (attr != null)
                    {
                        description = attr.Description;
                    }
                }
                action(name.ToString(), value.ToString(), description);
            }
        }

19 View Source File : Mana.cs
License : GNU General Public License v3.0
Project Creator : a2659802

private void Start()
            {
                string reqStr = ((ItemDef.ManaRequirement)item).Requires;
                if (!string.IsNullOrEmpty(reqStr))
                {
                    Dictionary<ManaType, int> r = new Dictionary<ManaType, int>();
                    try
                    {
                        for (int i = 0; i < reqStr.Length; i++)
                        {
                            char c = reqStr[i];
                            ManaType t = (ManaType)Enum.Parse(typeof(ManaType), c.ToString());
                            if (r.ContainsKey(t))
                            {
                                r[t]++;
                            }
                            else
                            {
                                r.Add(t, 1);
                            }
                        }
                        require = r;
                    }
                    catch (Exception e)
                    {
                        Logger.LogError("ManaRequire Parse Error");
                        Logger.LogError(e);
                    }
                }
                else
                {
                    Logger.LogDebug("Not Set Requirement");
                }
                if (require == null)
                {
                    require = new Dictionary<ManaType, int> { { ManaType.U, 2 }, { ManaType.G, 3 }, { ManaType.R, 1 }, { ManaType.C, 3 }, };
                    ((ItemDef.ManaRequirement)item).Requires = "UUGGGRCCC";
                }
                UpdateRequire();
            }

19 View Source File : Inspector.cs
License : GNU General Public License v3.0
Project Creator : a2659802

public static void Show()
        {
            OpLock.Apply();
            try
            {
                Item item = ItemManager.Instance.currentSelect.GetComponent<CustomDecoration>().item;
                

                if (!cache_prop.ContainsKey(item.GetType()))
                {
                    _reflectProps(item.GetType());
                }
                if (cache_prop.TryGetValue(item.GetType(), out var itemProps))
                {
                    var insp = new InspectPanel();
                    currentEdit = insp;
                    int idx = 0;
                    foreach (var kv in itemProps)
                    {
                        string name = kv.Key;
                        Type propType = kv.Value.PropertyType;
                        object value = kv.Value.GetValue(item, null);
                        value = Convert.ToSingle(value);
                        ConstraintAttribute con = kv.Value.GetCustomAttributes(typeof(ConstraintAttribute), true).OfType<ConstraintAttribute>().FirstOrDefault();

                        LogProp(propType, name, value);

                        if(idx == 0)
                        {
                            insp.UpdateName(idx,name);
                            if(con is IntConstraint)
                            {
                                //Logger.LogDebug($"Check1 {con.Min}-{con.Max}");
                                insp.UpdateSliderConstrain(name,idx, (float)Convert.ChangeType(con.Min, typeof(float)), Convert.ToInt32(con.Max), true);
                            }
                            else if(con is FloatConstraint)
                            {
                                //Logger.LogDebug($"Check2 {con.Min}-{con.Max}");
                                insp.UpdateSliderConstrain(name,idx, (float)(con.Min), (float)(con.Max), false);
                            }
                            else
                            {
                                throw new ArgumentException();
                            }
                            //Logger.LogDebug($"Check3 {value}-{value.GetType()}");
                            insp.UpdateValue(idx, (float)value);
                        }
                        else
                        {
                            insp.AppendPropPanel(name);
                            if (con is IntConstraint)
                            {
                                insp.UpdateSliderConstrain(name,idx, (int)con.Min, (int)con.Max, true);
                            }
                            else if (con is FloatConstraint)
                            {
                                insp.UpdateSliderConstrain(name,idx, (float)con.Min, (float)con.Max, false);
                            }
                            else
                            {
                                throw new ArgumentException();
                            }
                            insp.UpdateValue(idx, (float)value);
                            insp.UpdateTextDelegate(idx);//insp.AddListener(idx, insp.UpdateTextDelegate(idx));

                        }
                        //insp.AddListener(idx, (v) => { kv.Value.SetValue(item, Convert.ChangeType(v, kv.Value.PropertyType), null); });
                        insp.AddListener(idx, (v) => {
                            if (ItemManager.Instance.currentSelect == null)
                                return;
                            object val;
                            try
                            {
                                if (kv.Value.PropertyType.IsSubclreplacedOf(typeof(Enum)))
                                {
                                    val = Enum.Parse(kv.Value.PropertyType, v.ToString("0"));
                                }
                                else
                                    val = Convert.ChangeType(v, kv.Value.PropertyType);
                                ItemManager.Instance.currentSelect.GetComponent<CustomDecoration>().Setup(handler[kv.Value], val);
                            }
                            catch
                            {
                                Logger.LogError("Error occour at Inspect OnValue Chnaged");
                                Hide();
                            }
                        });
                        idx++;
                    }
                }
                else
                {
                    Logger.LogError($"KeyNotFount at cache_prop,{item.GetType()}");
                }
                
            }
            catch(NullReferenceException e)
            {
                Logger.LogError($"NulRef Error at Inspector.Show:{e}");
                OpLock.Undo();
            }
       
        }

19 View Source File : UnityPlayerBuildTools.cs
License : Apache License 2.0
Project Creator : abist-co-ltd

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

            for (int i = 0; i < arguments.Length; ++i)
            {
                switch (arguments[i])
                {
                    case "-autoIncrement":
                        buildInfo.AutoIncrement = true;
                        break;
                    case "-sceneList":
                        buildInfo.Scenes = buildInfo.Scenes.Union(SplitSceneList(arguments[++i]));
                        break;
                    case "-sceneListFile":
                        string path = arguments[++i];
                        if (File.Exists(path))
                        {
                            buildInfo.Scenes = buildInfo.Scenes.Union(SplitSceneList(File.ReadAllText(path)));
                        }
                        else
                        {
                            Debug.LogWarning($"Scene list file at '{path}' does not exist.");
                        }
                        break;
                    case "-buildOutput":
                        buildInfo.OutputDirectory = arguments[++i];
                        break;
                    case "-colorSpace":
                        buildInfo.ColorSpace = (ColorSpace)Enum.Parse(typeof(ColorSpace), arguments[++i]);
                        break;
                    case "-scriptingBackend":
                        buildInfo.ScriptingBackend = (ScriptingImplementation)Enum.Parse(typeof(ScriptingImplementation), arguments[++i]);
                        break;
                    case "-x86":
                    case "-x64":
                    case "-arm":
                    case "-arm64":
                        buildInfo.BuildPlatform = arguments[i].Substring(1);
                        break;
                    case "-debug":
                    case "-master":
                    case "-release":
                        buildInfo.Configuration = arguments[i].Substring(1).ToLower();
                        break;
                    case "-logDirectory":
                        buildInfo.LogDirectory = arguments[++i];
                        break;
                }
            }
        }

19 View Source File : MatchmakingManager.cs
License : MIT License
Project Creator : absurd-joy

private void ProcessRemoteMove(string moveString)
		{
			Debug.Log("Processing remote move string: " + moveString);
			string[] tokens = moveString.Split(':');

			GamePiece.Piece piece = (GamePiece.Piece)Enum.Parse(typeof(GamePiece.Piece), tokens[0]);
			int x = Int32.Parse(tokens[1]);
			int y = Int32.Parse(tokens[2]);

			// swap the coordinates since each player replacedumes they are player 0
			x = GameBoard.LENGTH_X-1 - x;
			y = GameBoard.LENGTH_Y-1 - y;

			m_gameController.MakeRemoteMove(piece, x, y);
		}

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

private void PanSciChartOn_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (zoomPanModifier != null)
                zoomPanModifier.ExecuteOn = (ExecuteOn)Enum.Parse(typeof(ExecuteOn), (string)panSciChartOn.SelectedValue);
        }

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

private void PanXYDirection_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (zoomPanModifier != null)
            {
                zoomPanModifier.XyDirection = (XyDirection) Enum.Parse(typeof(XyDirection), (string) panXYDirection.SelectedValue);

                if (zoomExtentsPanel != null)
                {
                    zoomExtentsPanel.Visibility = zoomPanModifier.XyDirection == XyDirection.XDirection
                        ? Visibility.Visible
                        : Visibility.Collapsed;
                }
            }
        }

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

public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value == null)
                return typeof(LineAnnotation);

            var annotationType = (AnnotationType)Enum.Parse(typeof(AnnotationType), (string)value);

            switch (annotationType)
            {
                case AnnotationType.LineAnnotation:
                    return typeof(LineAnnotation);
                case AnnotationType.AxisMarkerAnnotation:
                    return typeof(AxisMarkerAnnotation);
                case AnnotationType.BoxAnnotation:
                    return typeof(BoxAnnotation);
                case AnnotationType.HorizontalLineAnnotation:
                    return typeof(HorizontalLineAnnotation);
                case AnnotationType.LineArrowAnnotation:
                    return typeof(LineArrowAnnotation);
                case AnnotationType.MyCustomAnnotation:
                    return typeof(MyCustomAnnotation);
                case AnnotationType.TextAnnotation:
                    return typeof(TextAnnotation);
                case AnnotationType.VerticalLineAnnotation:
                    return typeof(VerticalLineAnnotation);
                default:
                    return null;

            }
        }

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

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var snapStr = value as string;

            var visibility = Visibility.Collapsed;
            if (snapStr != null)
            {
                var snappingMode = (CursorSnappingMode)Enum.Parse(typeof(CursorSnappingMode), snapStr);

                visibility = snappingMode == CursorSnappingMode.TooltipToCrosshair
                    ? Visibility.Collapsed
                    : Visibility.Visible;
            }

            return visibility;
        }

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

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

                    line = streamReader.ReadLine();
                }
            }

            return values;
        }

19 View Source File : CorreiosWebservice.cs
License : MIT License
Project Creator : ACBrNet

public override ACBrEndereco[] BuscarPorCEP(string cep)
		{
			try
			{
				var request = (HttpWebRequest)WebRequest.Create(CORREIOS_URL);
				request.ProtocolVersion = HttpVersion.Version10;
				request.UserAgent = "Mozilla/4.0 (compatible; Synapse)";
				request.Method = "POST";

				var postData = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>" +
							   "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" " +
							   "xmlns:cli=\"http://cliente.bean.master.sigep.bsb.correios.com.br/\"> " +
							   " <soapenv:Header/>" +
							   " <soapenv:Body>" +
							   " <cli:consultaCEP>" +
							   " <cep>" + cep.OnlyNumbers() + "</cep>" +
							   " </cli:consultaCEP>" +
							   " </soapenv:Body>" +
							   " </soapenv:Envelope>";

				var byteArray = Encoding.UTF8.GetBytes(postData);
				var dataStream = request.GetRequestStream();
				dataStream.Write(byteArray, 0, byteArray.Length);
				dataStream.Close();

				string retorno;

				// ReSharper disable once replacedignNullToNotNullAttribute
				using (var stHtml = new StreamReader(request.GetResponse().GetResponseStream(), ACBrEncoding.ISO88591))
					retorno = stHtml.ReadToEnd();

				var doc = XDoreplacedent.Parse(retorno);
				var element = doc.ElementAnyNs("Envelope").ElementAnyNs("Body").ElementAnyNs("consultaCEPResponse").ElementAnyNs("return");

				var endereco = new ACBrEndereco();
				endereco.CEP = element.Element("cep").GetValue<string>();
				endereco.Bairro = element.Element("bairro").GetValue<string>();
				endereco.Municipio = element.Element("cidade").GetValue<string>();
				endereco.Complemento = $"{element.Element("complemento").GetValue<string>()}{Environment.NewLine}{element.Element("complemento2").GetValue<string>()}";
				endereco.Logradouro = element.Element("end").GetValue<string>();
				endereco.UF = (ConsultaUF)Enum.Parse(typeof(ConsultaUF), element.Element("uf").GetValue<string>());

				endereco.TipoLogradouro = endereco.Logradouro.Split(' ')[0];
				endereco.Logradouro = endereco.Logradouro.SafeReplace(endereco.TipoLogradouro, string.Empty);

				return new[] { endereco };
			}
			catch (Exception exception)
			{
				throw new ACBrException(exception, "Erro ao consulta CEP.");
			}
		}

19 View Source File : ConsultaSintegraBA.cs
License : MIT License
Project Creator : ACBrNet

private static ACBrEmpresa ProcessResponse(string retorno)
        {
            var result = new ACBrEmpresa();

            try
            {
                var dadosRetorno = new List<string>();
                dadosRetorno.AddText(retorno.StripHtml());
                dadosRetorno.RemoveEmptyLines();

                result.CNPJ = LerCampo(dadosRetorno, "CNPJ:");
                result.InscricaoEstadual = LerCampo(dadosRetorno, "Inscrição Estadual:");
                result.RazaoSocial = LerCampo(dadosRetorno, "Social:");
                result.Logradouro = LerCampo(dadosRetorno, "Logradouro:");
                result.Numero = LerCampo(dadosRetorno, "Número:");
                result.Complemento = LerCampo(dadosRetorno, "Complemento:");
                result.Bairro = LerCampo(dadosRetorno, "Bairro:");
                result.Municipio = LerCampo(dadosRetorno, "Município:");
                result.UF = (ConsultaUF)Enum.Parse(typeof(ConsultaUF), LerCampo(dadosRetorno, "UF:").ToUpper());
                result.CEP = LerCampo(dadosRetorno, "CEP:").FormataCEP();
                result.EndEletronico = LerCampo(dadosRetorno, "Eletrônico:");
                result.Telefone = LerCampo(dadosRetorno, "Telefone:");
                result.AtividadeEconomica = LerCampo(dadosRetorno, "Econômica:");
                result.DataAbertura = LerCampo(dadosRetorno, "da Inscrição Estadual:").ToData();
                result.Situacao = LerCampo(dadosRetorno, "Situação Cadastral Atual:");
                result.DataSituacao = LerCampo(dadosRetorno, "desta Situação Cadastral:").ToData();
                result.RegimeApuracao = LerCampo(dadosRetorno, "de Apuração de ICMS:");
                result.DataEmitenteNFe = LerCampo(dadosRetorno, "Emitente de NFe desde:").ToData();
            }
            catch (Exception exception)
            {
                throw new ACBrException(exception, "Erro ao processar retorno.");
            }

            return result;
        }

19 View Source File : ACBrIBGE.cs
License : MIT License
Project Creator : ACBrNet

private void ProcessarResposta(string resposta)
		{
			try
			{
				Resultados.Clear();

				var buffer = resposta.ToLower();
				var pos = buffer.IndexOf("<div id=\"miolo_interno\">", StringComparison.Ordinal);
				if (pos <= 0) return;

				buffer = buffer.Substring(pos, buffer.Length - pos);
				buffer = buffer.GetStrBetween("<table ", "</table>");

				var rows = Regex.Matches(buffer, @"(?<1><TR[^>]*>\s*<td.*?</tr>)", RegexOptions.Singleline | RegexOptions.IgnoreCase)
								.Cast<Match>()
								.Select(t => t.Value)
								.ToArray();

				if (rows.Length < 2) return;

				for (var i = 1; i < rows.Length; i++)
				{
					var columns = Regex.Matches(rows[i], @"<td[^>](.+?)<\/td>", RegexOptions.Singleline | RegexOptions.IgnoreCase)
									   .Cast<Match>()
									   .Select(t => t.Value.StripHtml().Replace(" ", string.Empty).Trim())
									   .ToArray();

					var municipio = new ACBrMunicipio
					{
						CodigoUF = columns[0].ToInt32(),
						UF = (ConsultaUF)Enum.Parse(typeof(ConsultaUF), columns[1].ToUpper()),
						Codigo = columns[2].ToInt32(),
						Nome = columns[3].ToreplacedleCase(),
						Area = columns[4].ToDecimal()
					};

					Resultados.Add(municipio);
				}
			}
			catch (Exception exception)
			{
				throw new ACBrException(exception, "Erro ao processar retorno.");
			}
		}

19 View Source File : ACBrConsultaCNPJ.cs
License : MIT License
Project Creator : ACBrNet

private static ACBrEmpresa ProcessResponse(string retorno)
		{
			var result = new ACBrEmpresa();

			try
			{
				var retornoRfb = new List<string>();
				retornoRfb.AddText(retorno.StripHtml());
				retornoRfb.RemoveEmptyLines();

				result.CNPJ = LerCampo(retornoRfb, "NÚMERO DE INSCRIÇÃO");
				if (!result.CNPJ.IsEmpty()) result.TipoEmpresa = LerCampo(retornoRfb, result.CNPJ);
				result.DataAbertura = LerCampo(retornoRfb, "DATA DE ABERTURA").ToData();
				result.RazaoSocial = LerCampo(retornoRfb, "NOME EMPRESARIAL");
				result.NomeFantasia = LerCampo(retornoRfb, "TÍTULO DO ESTABELECIMENTO (NOME DE FANTASIA)");
				result.CNAE1 = LerCampo(retornoRfb, "CÓDIGO E DESCRIÇÃO DA ATIVIDADE ECONÔMICA PRINCIPAL");
				result.Logradouro = LerCampo(retornoRfb, "LOGRADOURO");
				result.Numero = LerCampo(retornoRfb, "NÚMERO");
				result.Complemento = LerCampo(retornoRfb, "COMPLEMENTO");
				result.CEP = LerCampo(retornoRfb, "CEP").FormataCEP();
				result.Bairro = LerCampo(retornoRfb, "BAIRRO/DISTRITO");
				result.Municipio = LerCampo(retornoRfb, "MUNICÍPIO");
				result.UF = (ConsultaUF)Enum.Parse(typeof(ConsultaUF), LerCampo(retornoRfb, "UF").ToUpper());
				result.Situacao = LerCampo(retornoRfb, "SITUAÇÃO CADASTRAL");
				result.DataSituacao = LerCampo(retornoRfb, "DATA DA SITUAÇÃO CADASTRAL").ToData();
				result.NaturezaJuridica = LerCampo(retornoRfb, "CÓDIGO E DESCRIÇÃO DA NATUREZA JURÍDICA");
				result.EndEletronico = LerCampo(retornoRfb, "ENDEREÇO ELETRÔNICO");
				if (result.EndEletronico == "TELEFONE") result.EndEletronico = string.Empty;
				result.Telefone = LerCampo(retornoRfb, "TELEFONE");
				result.EFR = LerCampo(retornoRfb, "ENTE FEDERATIVO RESPONSÁVEL (EFR)");
				result.MotivoSituacao = LerCampo(retornoRfb, "MOTIVO DE SITUAÇÃO CADASTRAL");
				result.SituacaoEspecial = LerCampo(retornoRfb, "SITUAÇÃO ESPECIAL");
				result.DataSituacaoEspecial = LerCampo(retornoRfb, "DATA DA SITUAÇÃO ESPECIAL").ToData();

				var listCNAE2 = new List<string>();
				var aux = LerCampo(retornoRfb, "CÓDIGO E DESCRIÇÃO DAS ATIVIDADES ECONÔMICAS SECUNDÁRIAS");
				if (!aux.IsEmpty()) listCNAE2.Add(aux.RemoveDoubleSpaces());

				do
				{
					aux = LerCampo(retornoRfb, aux);
					if (!aux.IsEmpty()) listCNAE2.Add(aux.RemoveDoubleSpaces());
				} while (!aux.IsEmpty());

				result.CNAE2 = listCNAE2.ToArray();
			}
			catch (Exception exception)
			{
				throw new ACBrException(exception, "Erro ao processar retorno.");
			}

			return result;
		}

19 View Source File : ConsultaSintegraES.cs
License : MIT License
Project Creator : ACBrNet

private static ACBrEmpresa ProcessResponse(string retorno)
        {
            var result = new ACBrEmpresa();
            var dadosRetorno = new List<string>();
            dadosRetorno.AddText(retorno.StripHtml());
            dadosRetorno.RemoveEmptyLines();
            try
            {
                result.CNPJ = LerCampo(dadosRetorno, "CNPJ:");
                result.InscricaoEstadual = LerCampo(dadosRetorno, "Inscri��o Estadual:");
                result.RazaoSocial = LerCampo(dadosRetorno, "Raz�o Social :");
                result.Logradouro = LerCampo(dadosRetorno, "Logradouro:");
                result.Numero = LerCampo(dadosRetorno, "N�mero:");
                result.Complemento = LerCampo(dadosRetorno, "Complemento:");
                result.Municipio = LerCampo(dadosRetorno, "Munic�pio:");
                result.UF = (ConsultaUF)Enum.Parse(typeof(ConsultaUF), LerCampo(dadosRetorno, "UF:").ToUpper());
                result.CEP = LerCampo(dadosRetorno, "CEP:").FormataCEP();
                result.Telefone = LerCampo(dadosRetorno, "Telefone:");
                result.AtividadeEconomica = LerCampo(dadosRetorno, "Atividade Econ�mica:");
                result.DataInicioAtividade = LerCampo(dadosRetorno, "Data de Inicio de Atividade:").ToData();
                result.Situacao = LerCampo(dadosRetorno, "Situa��o Cadastral Vigente:");
                result.DataSituacao = LerCampo(dadosRetorno, "Data desta Situa��o Cadastral:").ToData();
                result.RegimeApuracao = LerCampo(dadosRetorno, "Regime de Apura��o:");
                result.DataEmitenteNFe = LerCampo(dadosRetorno, "Emitente de NFe desde:").ToData();
            }
            catch (Exception exception)
            {
                throw new ACBrException(exception, "Erro ao processar retorno.");
            }

            return result;
        }

19 View Source File : ConsultaSintegraGO.cs
License : MIT License
Project Creator : ACBrNet

private static ACBrEmpresa ProcessResponse(string retorno)
        {
            var result = new ACBrEmpresa();
            var dadosRetorno = ProcessTableHtml(retorno);
            try
            {
                result.CNPJ = LerCampo(dadosRetorno, "CNPJ:");
                result.InscricaoEstadual = LerCampo(dadosRetorno, "Inscrição Estadual - CCE :");
                result.RazaoSocial = LerCampo(dadosRetorno, "Nome Empresarial:");
                result.Logradouro = LerCampo(dadosRetorno, "Logradouro:");
                result.Numero = LerCampo(dadosRetorno, "Número:");
                result.Complemento = LerCampo(dadosRetorno, "Complemento:");

                var dadosRetorno2 = new List<string>();
                dadosRetorno2.AddText(WebUtility.HtmlDecode(retorno.StripHtml().Replace(" ", Environment.NewLine)).Trim());
                dadosRetorno2.RemoveEmptyLines();
                result.Bairro = LerCampo(dadosRetorno2, "Bairro:");
                dadosRetorno2 = null;

                result.Municipio = LerCampo(dadosRetorno, "Município:");
                result.UF = (ConsultaUF)Enum.Parse(typeof(ConsultaUF), LerCampo(dadosRetorno, "UF:").ToUpper());
                result.CEP = LerCampo(dadosRetorno, "CEP:").FormataCEP();
                result.Telefone = LerCampo(dadosRetorno, "Telefone:");
                result.AtividadeEconomica = LerCampo(dadosRetorno, "Atividade Principal");
                result.DataAbertura = LerCampo(dadosRetorno, "Data de Cadastramento:").ToData();
                result.Situacao = LerCampo(dadosRetorno, "Situação Cadastral Vigente:");
                result.DataSituacao = LerCampo(dadosRetorno, "Data desta Situação Cadastral:").ToData();
                result.RegimeApuracao = LerCampo(dadosRetorno, "Regime de Apuração:");
                result.DataEmitenteNFe = LerCampo(dadosRetorno, "Emitente de NFe desde:").ToData();
            }
            catch (Exception exception)
            {
                throw new ACBrException(exception, "Erro ao processar retorno.");
            }

            return result;
        }

19 View Source File : ConsultaSintegraMS.cs
License : MIT License
Project Creator : ACBrNet

private static ACBrEmpresa ProcessResponse(string retorno)
        {
            var result = new ACBrEmpresa();

            try
            {
                var dadosRetorno = new List<string>();
                dadosRetorno.AddText(retorno.StripHtml());
                dadosRetorno.RemoveEmptyLines();

                result.InscricaoEstadual = LerCampo(dadosRetorno, "Inscri��o Estadual");
                result.DataAbertura = LerCampo(dadosRetorno, "Data de In�cio da Atividade").ToData();
                result.CNPJ = LerCampo(dadosRetorno, "CNPJ");
                result.RazaoSocial = LerCampo(dadosRetorno, "Raz�o Social/Nome");
                result.Logradouro = LerCampo(dadosRetorno, "Logradouro");
                result.Numero = LerCampo(dadosRetorno, "Numero");
                result.Complemento = LerCampo(dadosRetorno, "Complemento");
                result.CEP = LerCampo(dadosRetorno, "CEP").FormataCEP();
                result.Bairro = LerCampo(dadosRetorno, "Bairro");
                result.Municipio = LerCampo(dadosRetorno, "Munic�pio");
                result.UF = (ConsultaUF)Enum.Parse(typeof(ConsultaUF), LerCampo(dadosRetorno, "UF").ToUpper());
                result.Situacao = LerCampo(dadosRetorno, "Situa��o Cadastral");
                result.DataSituacao = LerCampo(dadosRetorno, "Data da �ltima Atualiza��o").ToData();
                result.MotivoSituacao = LerCampo(dadosRetorno, "Motivo da Situa��o");
            }
            catch (Exception exception)
            {
                throw new ACBrException(exception, "Erro ao processar retorno.");
            }

            return result;
        }

19 View Source File : ConsultaSintegraMT.cs
License : MIT License
Project Creator : ACBrNet

private static ACBrEmpresa ProcessResponse(string retorno)
        {
            var result = new ACBrEmpresa();

            try
            {
                var dadosRetorno = new List<string>();
                retorno = HttpUtility.HtmlDecode(retorno);
                retorno = retorno.StripHtml();
                dadosRetorno.AddText(retorno.Replace(" ", Environment.NewLine));
                dadosRetorno.RemoveEmptyLines();

                result.CNPJ = LerCampo(dadosRetorno, "CPF/CNPJ:");
                result.InscricaoEstadual = LerCampo(dadosRetorno, "Inscri��o estadual:");
                result.RazaoSocial = LerCampo(dadosRetorno, "Raz�o social:").Replace("amp;", string.Empty);
                result.Logradouro = LerCampo(dadosRetorno, "Logradouro:");
                result.Numero = LerCampo(dadosRetorno, "N�mero:");
                result.Complemento = LerCampo(dadosRetorno, "Complemento:");
                result.Bairro = LerCampo(dadosRetorno, "Bairro:");
                result.Municipio = LerCampo(dadosRetorno, "Munic�pio/UF:");
                result.UF = (ConsultaUF)Enum.Parse(typeof(ConsultaUF), LerCampo(dadosRetorno, result.Municipio).ToUpper());
                result.Municipio = result.Municipio.Substring(0, result.Municipio.Length - 2);
                result.CEP = LerCampo(dadosRetorno, "CEP:").FormataCEP();
                result.Telefone = LerCampo(dadosRetorno, "Telefone:");
                result.AtividadeEconomica = LerCampo(dadosRetorno, "Atividade Econ�mica:");
                result.DataAbertura = LerCampo(dadosRetorno, "Data de in�cio no Simples Nacional:").ToData();
                result.Situacao = LerCampo(dadosRetorno, "Situa��o cadastral atual:");
                result.DataSituacao = LerCampo(dadosRetorno, "Data desta situa��o cadastral:").ToData();
                result.RegimeApuracao = LerCampo(dadosRetorno, "Data desta situa��o cadastral:");
                result.DataEmitenteNFe = LerCampo(dadosRetorno, "Emitente de NFe desde:").ToData();

                result.CNAE1 = LerCampo(dadosRetorno, "CNAE Fiscal:");
                var cnae = LerCampo(dadosRetorno, result.CNAE1);
                if (cnae != "CNAE Secund�rio:") result.CNAE1 += $" {cnae}";

                var listCnae2 = new List<string>();
                var aux = LerCampo(dadosRetorno, "CNAE Secund�rio:");
                if (!aux.IsEmpty()) listCnae2.Add(aux);

                do
                {
                    aux = LerCampo(dadosRetorno, aux);
                    if (aux == "Credenciado de of�cio como emissor de NF-e:") break;

                    if (!aux.IsEmpty() && char.IsDigit(aux, 0))
                    {
                        listCnae2.Add(aux);
                    }
                    else
                    {
                        listCnae2[listCnae2.Count - 1] += $" {aux}";
                    }
                } while (!aux.IsEmpty());

                result.CNAE2 = listCnae2.ToArray();
            }
            catch (Exception exception)
            {
                throw new ACBrException(exception, "Erro ao processar retorno.");
            }

            return result;
        }

19 View Source File : ConsultaSintegraDF.cs
License : MIT License
Project Creator : ACBrNet

private static ACBrEmpresa ProcessResponse(string retorno)
        {
            const string tableExpression = "<table.*?>(.*?)</table>";
            const string trPattern = "<tr(.*?)</tr>";
            const string tdPattern = "<td.*?>(.*?)</td>";

            var result = new ACBrEmpresa();
            try
            {
                var dadosRetorno = new List<string>();
                var tableContents = GetContents(retorno, tableExpression);
                foreach (var tableContent in tableContents)
                {
                    var trContents = GetContents(tableContent, trPattern);
                    foreach (var trContent in trContents)
                    {
                        var tdContents = GetContents(trContent, tdPattern);
                        foreach (var item in tdContents)
                        {
                            dadosRetorno.AddText((Regex.Replace(item, "<.*?>", string.Empty).Trim()));
                        }
                    }
                }
                result.CNPJ = LerCampo(dadosRetorno, "CNPJ/CPF");
                result.InscricaoEstadual = LerCampo(dadosRetorno, "CF/DF");
                result.RazaoSocial = LerCampo(dadosRetorno, "RAZÃO SOCIAL");
                result.Logradouro = LerCampo(dadosRetorno, "LOGRADOURO");
                result.Numero = LerCampo(dadosRetorno, "Número:");
                result.Complemento = LerCampo(dadosRetorno, "Complemento:");
                result.Bairro = LerCampo(dadosRetorno, "BAIRRO");
                result.Municipio = LerCampo(dadosRetorno, "MUNICÍPIO");
                result.UF = (ConsultaUF)Enum.Parse(typeof(ConsultaUF), LerCampo(dadosRetorno, "UF").ToUpper());
                result.CEP = LerCampo(dadosRetorno, "CEP").FormataCEP();
                result.Telefone = LerCampo(dadosRetorno, "Telefone");
                result.AtividadeEconomica = LerCampo(dadosRetorno, "ATIVIDADE PRINCIPAL");
                result.DataAbertura = LerCampo(dadosRetorno, "DATA DESSA SITUAÇÃO CADASTRAL").ToData();
                result.Situacao = LerCampo(dadosRetorno, "SITUAÇÃO CADASTRAL");
                result.DataSituacao = LerCampo(dadosRetorno, "DATA DESSA SITUAÇÃO CADASTRAL").ToData();
                result.RegimeApuracao = LerCampo(dadosRetorno, "REGIME DE APURAÇÃO");
                result.DataEmitenteNFe = LerCampo(dadosRetorno, "Emitente de NFe desde:").ToData();
            }
            catch (Exception exception)
            {
                throw new ACBrException(exception, "Erro ao processar retorno.");
            }

            return result;
        }

19 View Source File : ConsultaSintegraSP.cs
License : MIT License
Project Creator : ACBrNet

private static ACBrEmpresa ProcessResponse(string retorno)
        {
            var result = new ACBrEmpresa();

            try
            {
                var dadosRetorno = new List<string>();
                dadosRetorno.AddText(WebUtility.HtmlDecode(retorno.StripHtml().Replace(" ", Environment.NewLine)));
                dadosRetorno.RemoveEmptyLines();

                result.CNPJ = LerCampo(dadosRetorno, "CNPJ:");
                result.InscricaoEstadual = LerCampo(dadosRetorno, "Inscri��o Estadual:");
                result.RazaoSocial = LerCampo(dadosRetorno, "Raz�o Social:");
                result.Logradouro = LerCampo(dadosRetorno, "Logradouro:");
                result.Numero = LerCampo(dadosRetorno, "N�mero:");
                result.Complemento = LerCampo(dadosRetorno, "Complemento:");
                result.Bairro = LerCampo(dadosRetorno, "Bairro:");
                result.Municipio = LerCampo(dadosRetorno, "Munic�pio:");
                result.UF = (ConsultaUF)Enum.Parse(typeof(ConsultaUF), LerCampo(dadosRetorno, "UF:").ToUpper());
                result.CEP = LerCampo(dadosRetorno, "CEP:").FormataCEP();

                result.Telefone = LerCampo(dadosRetorno, "Telefone:");
                result.AtividadeEconomica = LerCampo(dadosRetorno, "Atividade Econ�mica:");
                result.DataAbertura = LerCampo(dadosRetorno, "Data de Inicio de Atividade:").ToData();
                result.Situacao = LerCampo(dadosRetorno, "Situa��o Cadastral Vigente:");
                result.DataSituacao = LerCampo(dadosRetorno, "Data desta Situa��o Cadastral:").ToData();
                result.RegimeApuracao = LerCampo(dadosRetorno, "Regime de Apura��o:");
                result.DataEmitenteNFe = LerCampo(dadosRetorno, "Emitente de NFe desde:").ToData();
            }
            catch (Exception exception)
            {
                throw new ACBrException(exception, "Erro ao processar retorno.");
            }

            return result;
        }

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

public void CreateSentinelBuffPlayers(IEnumerable<Player> players, bool self = false, ulong maxLevel = 8)
        {
            if (!(Session.AccessLevel >= AccessLevel.Sentinel)) return;

            var SelfOrOther = self ? "Self" : "Other";

            // ensure level 8s are installed
            var maxSpellLevel = Math.Clamp(maxLevel, 1, 8);
            if (maxSpellLevel == 8 && DatabaseManager.World.GetCachedSpell((uint)SpellId.ArmorOther8) == null)
                maxSpellLevel = 7;

            var tySpell = typeof(SpellId);
            List<BuffMessage> buffMessages = new List<BuffMessage>();
            // prepare messages
            List<string> buffsNotImplementedYet = new List<string>();
            foreach (var spell in Buffs)
            {
                var spellNamPrefix = spell;
                bool isBane = false;
                if (spellNamPrefix.StartsWith("@"))
                {
                    isBane = true;
                    spellNamPrefix = spellNamPrefix.Substring(1);
                }
                string fullSpellEnumName = spellNamPrefix + ((isBane) ? string.Empty : SelfOrOther) + maxSpellLevel;
                string fullSpellEnumNameAlt = spellNamPrefix + ((isBane) ? string.Empty : ((SelfOrOther == "Self") ? "Other" : "Self")) + maxSpellLevel;
                uint spellID = (uint)Enum.Parse(tySpell, fullSpellEnumName);
                var buffMsg = BuildBuffMessage(spellID);

                if (buffMsg == null)
                {
                    spellID = (uint)Enum.Parse(tySpell, fullSpellEnumNameAlt);
                    buffMsg = BuildBuffMessage(spellID);
                }

                if (buffMsg != null)
                {
                    buffMsg.Bane = isBane;
                    buffMessages.Add(buffMsg);
                }
                else
                {
                    buffsNotImplementedYet.Add(fullSpellEnumName);
                }
            }
            // buff each player
            players.ToList().ForEach(targetPlayer =>
            {
                if (buffMessages.Any(k => !k.Bane))
                {
                    // bake player into the messages
                    buffMessages.Where(k => !k.Bane).ToList().ForEach(k => k.SetTargetPlayer(targetPlayer));
                    // update client-side enchantments
                    targetPlayer.Session.Network.EnqueueSend(buffMessages.Where(k => !k.Bane).Select(k => k.SessionMessage).ToArray());
                    // run client-side effect scripts, omitting duplicates
                    targetPlayer.EnqueueBroadcast(buffMessages.Where(k => !k.Bane).ToList().GroupBy(m => m.Spell.TargetEffect).Select(a => a.First().LandblockMessage).ToArray());
                    // update server-side enchantments

                    var buffsForPlayer = buffMessages.Where(k => !k.Bane).ToList().Select(k => k.Enchantment);

                    var lifeBuffsForPlayer = buffsForPlayer.Where(k => k.Spell.School == MagicSchool.LifeMagic).ToList();
                    var critterBuffsForPlayer = buffsForPlayer.Where(k => k.Spell.School == MagicSchool.CreatureEnchantment).ToList();
                    var itemBuffsForPlayer = buffsForPlayer.Where(k => k.Spell.School == MagicSchool.ItemEnchantment).ToList();

                    lifeBuffsForPlayer.ForEach(spl =>
                    {
                        CreateEnchantmentSilent(spl.Spell, targetPlayer);
                    });
                    critterBuffsForPlayer.ForEach(spl =>
                    {
                        CreateEnchantmentSilent(spl.Spell, targetPlayer);
                    });
                    itemBuffsForPlayer.ForEach(spl =>
                    {
                        CreateEnchantmentSilent(spl.Spell, targetPlayer);
                    });
                }
                if (buffMessages.Any(k => k.Bane))
                {
                    // Impen/bane
                    var items = targetPlayer.EquippedObjects.Values.ToList();
                    var itembuffs = buffMessages.Where(k => k.Bane).ToList();
                    foreach (var itemBuff in itembuffs)
                    {
                        foreach (var item in items)
                        {
                            if ((item.WeenieType == WeenieType.Clothing || item.IsShield) && item.IsEnchantable)
                                CreateEnchantmentSilent(itemBuff.Spell, item);
                        }
                    }
                }
            });
        }

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

protected override void OnEventWritten(EventWrittenEventArgs eventData)
        {
            if (eventData == null)
            {
                return;
            }

            string message = eventData.Message;
            object[] payload = new object[0];
            if (eventData.Payload != null && eventData.Payload.Count > 0)
            {
                payload = eventData.Payload.ToArray();
            }

            try
            {
                if (_vssHttpMethodEventIds.Contains(eventData.EventId))
                {
                    payload[0] = Enum.Parse(typeof(VssHttpMethod), ((int)payload[0]).ToString());
                }
                else if (_vssHttpCredentialEventIds.Contains(eventData.EventId))
                {
                    payload[0] = Enum.Parse(typeof(GitHub.Services.Common.VssCredentialsType), ((int)payload[0]).ToString());
                }

                if (payload.Length > 0)
                {
                    message = String.Format(eventData.Message.Replace("%n", Environment.NewLine), payload);
                }

                switch (eventData.Level)
                {
                    case EventLevel.Critical:
                    case EventLevel.Error:
                        _actionsHttpTrace.Error(message);
                        break;
                    case EventLevel.Warning:
                        _actionsHttpTrace.Warning(message);
                        break;
                    case EventLevel.Informational:
                        _actionsHttpTrace.Info(message);
                        break;
                    default:
                        _actionsHttpTrace.Verbose(message);
                        break;
                }
            }
            catch (Exception ex)
            {
                _actionsHttpTrace.Error(ex);
                _actionsHttpTrace.Info(eventData.Message);
                _actionsHttpTrace.Info(string.Join(", ", eventData.Payload?.ToArray() ?? new string[0]));
            }
        }

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

public static object ParseKnownFlags(Type enumType, string stringValue)
        {
            ArgumentUtility.CheckForNull(enumType, nameof(enumType));
            if (!enumType.IsEnum)
            {
                throw new ArgumentException(PipelinesWebApiResources.FlagEnumTypeRequired());
            }

            // Check for the flags attribute in debug. Skip this reflection in release.
            Debug.replacedert(enumType.GetCustomAttributes(typeof(FlagsAttribute), inherit: false).Any(), "FlagsEnum only intended for enums with the Flags attribute.");

            // The exception types below are based on Enum.TryParseEnum (http://index/?query=TryParseEnum&rightProject=mscorlib&file=system%5Cenum.cs&rightSymbol=bhaeh2vnegwo)
            if (stringValue == null)
            {
                throw new ArgumentNullException(stringValue);
            }

            if (String.IsNullOrWhiteSpace(stringValue))
            {
                throw new ArgumentException(PipelinesWebApiResources.NonEmptyEnumElementsRequired(stringValue));
            }

            if (UInt64.TryParse(stringValue, NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out ulong ulongValue))
            {
                return Enum.Parse(enumType, stringValue);
            }

            var enumNames = Enum.GetNames(enumType).ToHashSet(name => name, StringComparer.OrdinalIgnoreCase);
            var enumMemberMappings = new Lazy<IDictionary<string, string>>(() =>
            {
                IDictionary<string, string> mappings = null;
                foreach (var field in enumType.GetFields())
                {
                    if (field.GetCustomAttributes(typeof(EnumMemberAttribute), false).FirstOrDefault() is EnumMemberAttribute enumMemberAttribute)
                    {
                        if (mappings == null)
                        {
                            mappings = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
                        }
                        mappings.Add(enumMemberAttribute.Value, field.GetValue(null).ToString());
                    }
                }

                return mappings;
            });

            var values = stringValue.Split(s_enumSeparatorCharArray);

            var matches = new List<string>();
            for (int i = 0; i < values.Length; i++)
            {
                string value = values[i].Trim();

                if (String.IsNullOrEmpty(value))
                {
                    throw new ArgumentException(PipelinesWebApiResources.NonEmptyEnumElementsRequired(stringValue));
                }

                if (enumNames.Contains(value))
                {
                    matches.Add(value);
                }
                else if (enumMemberMappings.Value != null && enumMemberMappings.Value.TryGetValue(value, out string matchingValue))
                {
                    matches.Add(matchingValue);
                }
            }

            if (!matches.Any())
            {
                return Enum.Parse(enumType, "0");
            }

            string matchesString = String.Join(", ", matches);
            return Enum.Parse(enumType, matchesString, ignoreCase: true);
        }

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

public static object Parse(Type enumType, string stringValue)
        {
            var underlyingType = Nullable.GetUnderlyingType(enumType);
            enumType = underlyingType != null ? underlyingType : enumType;

            var names = Enum.GetNames(enumType);
            if (!string.IsNullOrEmpty(stringValue))
            {
                var match = names.FirstOrDefault(name => string.Equals(name, stringValue, StringComparison.OrdinalIgnoreCase));
                if (match != null)
                {
                    return Enum.Parse(enumType, match);
                }

                // maybe we have an enum member with an EnumMember attribute specifying a custom name
                foreach (var field in enumType.GetFields())
                {
                    var enumMemberAttribute = field.GetCustomAttributes(typeof(EnumMemberAttribute), false).FirstOrDefault() as EnumMemberAttribute;
                    if (enumMemberAttribute != null && string.Equals(enumMemberAttribute.Value, stringValue, StringComparison.OrdinalIgnoreCase))
                    {
                        // we already have the field, no need to do enum.parse on it
                        return field.GetValue(null);
                    }
                }
            }

            return Enum.Parse(enumType, UnknownName);
        }

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

public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            // Newtonsoft doesn't call CanConvert if you specify the converter using a JsonConverter attribute
            // they just replacedume you know what you're doing :)
            if (!CanConvert(objectType))
            {
                // if there's no Unknown value, fall back to the StringEnumConverter behavior
                return base.ReadJson(reader, objectType, existingValue, serializer);
            }

            if (reader.TokenType == JsonToken.Integer)
            {
                var intValue = Convert.ToInt32(reader.Value);
                var values = (int[])Enum.GetValues(objectType);
                if (values.Contains(intValue))
                {
                    return Enum.Parse(objectType, intValue.ToString());
                }
            }

            if (reader.TokenType == JsonToken.String)
            {
                var stringValue = reader.Value.ToString();
                return UnknownEnum.Parse(objectType, stringValue);
            }

            // we know there's an Unknown value because CanConvert returned true
            return Enum.Parse(objectType, UnknownName);
        }

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

protected T TryGetValueOrDefault<T>(string key)
            {
                object ret;
                if(TryGetValue(key, out ret))
                {
                    //we have to special case DateTime
                    if (typeof(T) == typeof(DateTime))
                    {
                        return (T)(object)ConvertDateTime(ret);
                    }
                    if (typeof(T).GetTypeInfo().IsEnum && ret is string)
                    {
                        return (T)Enum.Parse(typeof(T), (string)ret);
                    }
                    return (T)Convert.ChangeType(ret, typeof(T));
                }

                return default(T);
            }

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

public static T ToEnum<T>(this string enumName)
		{
			return (T)Enum.Parse(typeof(T), enumName);
		}

19 View Source File : Region.cs
License : GNU General Public License v3.0
Project Creator : aelariane

public static CloudRegionCode Parse(string codereplacedtring)
    {
        codereplacedtring = codereplacedtring.ToLower();
        CloudRegionCode result = CloudRegionCode.none;
        if (Enum.IsDefined(typeof(CloudRegionCode), codereplacedtring))
        {
            result = (CloudRegionCode)((int)Enum.Parse(typeof(CloudRegionCode), codereplacedtring));
        }
        return result;
    }

19 View Source File : PointDefinition.cs
License : MIT License
Project Creator : Aeroluna

public static PointDefinition ListToPointDefinition(List<object> list)
        {
            IEnumerable<List<object>> points;
            if (list.FirstOrDefault() is List<object>)
            {
                points = list.Cast<List<object>>();
            }
            else
            {
                points = new List<object>[] { list.Append(0).ToList() };
            }

            List<PointData> pointData = new List<PointData>();
            foreach (List<object> rawPoint in points)
            {
                int flagIndex = -1;
                int cachedCount = rawPoint.Count;
                for (int i = cachedCount - 1; i > 0; i--)
                {
                    if (rawPoint[i] is string)
                    {
                        flagIndex = i;
                    }
                    else
                    {
                        break;
                    }
                }

                Functions easing = Functions.easeLinear;
                bool spline = false;
                List<object> copiedList = rawPoint.ToList();
                if (flagIndex != -1)
                {
                    List<string> flags = rawPoint.GetRange(flagIndex, cachedCount - flagIndex).Cast<string>().ToList();
                    copiedList.RemoveRange(flagIndex, cachedCount - flagIndex);

                    string easingString = flags.Where(n => n.StartsWith("ease")).FirstOrDefault();
                    if (easingString != null)
                    {
                        easing = (Functions)Enum.Parse(typeof(Functions), easingString);
                    }

                    // TODO: add more spicy splines
                    string splineString = flags.Where(n => n.StartsWith("spline")).FirstOrDefault();
                    if (splineString == "splineCatmullRom")
                    {
                        spline = true;
                    }
                }

                if (copiedList.Count() == 2)
                {
                    Vector2 vector = new Vector2(Convert.ToSingle(copiedList[0]), Convert.ToSingle(copiedList[1]));
                    pointData.Add(new PointData(vector, easing));
                }
                else if (copiedList.Count() == 4)
                {
                    Vector4 vector = new Vector4(Convert.ToSingle(copiedList[0]), Convert.ToSingle(copiedList[1]), Convert.ToSingle(copiedList[2]), Convert.ToSingle(copiedList[3]));
                    pointData.Add(new PointData(vector, easing, spline));
                }
                else
                {
                    Vector5 vector = new Vector5(Convert.ToSingle(copiedList[0]), Convert.ToSingle(copiedList[1]), Convert.ToSingle(copiedList[2]), Convert.ToSingle(copiedList[3]), Convert.ToSingle(copiedList[4]));
                    pointData.Add(new PointData(vector, easing));
                }
            }

            return new PointDefinition(pointData);
        }

19 View Source File : SettingsSetterViewController.cs
License : MIT License
Project Creator : Aeroluna

internal void Init(StartStandardLevelParameters startParameters, MenuTransitionsHelper menuTransitionsHelper)
        {
            if (startParameters.DifficultyBeatmap.beatmapData is CustomBeatmapData customBeatmapData)
            {
                Dictionary<string, object?>? settings = customBeatmapData.beatmapCustomData.Get<Dictionary<string, object?>>("_settings");
                if (settings != null)
                {
                    _contents.Clear();
                    _modifiedParameters = startParameters;

                    Dictionary<string, object?>? jsonPlayerOptions = settings.Get<Dictionary<string, object?>>("_playerOptions");
                    if (jsonPlayerOptions != null)
                    {
                        PlayerSpecificSettings playerSettings = startParameters.PlayerSpecificSettings;
                        List<Dictionary<string, object>> settablePlayerSettings = SettingSetterSettableSettingsManager.SettingsTable["_playerOptions"];

                        PlayerSpecificSettings modifiedPlayerSettings = playerSettings.CopyWith();

                        foreach (Dictionary<string, object> settablePlayerSetting in settablePlayerSettings)
                        {
                            string name = (string)settablePlayerSetting["_name"];
                            string fieldName = (string)settablePlayerSetting["_fieldName"];

                            object? json = jsonPlayerOptions.Get<object>(fieldName);
                            if (json != null)
                            {
                                FieldInfo field = typeof(PlayerSpecificSettings).GetField(fieldName, BindingFlags.Instance | BindingFlags.NonPublic);
                                object activeValue = field.GetValue(playerSettings);
                                if (json is string jsonString)
                                {
                                    json = Enum.Parse(typeof(EnvironmentEffectsFilterPreset), jsonString);
                                }
                                else if (json is IConvertible)
                                {
                                    json = Convert.ChangeType(json, activeValue.GetType());
                                }

                                if (!json.Equals(activeValue))
                                {
                                    _contents.Add(new ListObject($"[Player Options] {name}", $"{activeValue} > {json}"));
                                    field.SetValue(modifiedPlayerSettings, json);
                                }
                            }
                        }

                        _modifiedParameters.PlayerSpecificSettings = modifiedPlayerSettings;
                    }

                    Dictionary<string, object?>? jsonModifiers = settings.Get<Dictionary<string, object?>>("_modifiers");
                    if (jsonModifiers != null)
                    {
                        GameplayModifiers gameplayModifiers = startParameters.GameplayModifiers;
                        List<Dictionary<string, object>> settableGameplayModifiers = SettingSetterSettableSettingsManager.SettingsTable["_modifiers"];

                        GameplayModifiers modifiedGameplayModifiers = gameplayModifiers.CopyWith();

                        foreach (Dictionary<string, object> settableGameplayModifier in settableGameplayModifiers)
                        {
                            string name = (string)settableGameplayModifier["_name"];
                            string fieldName = (string)settableGameplayModifier["_fieldName"];

                            object? json = jsonModifiers.Get<object>(fieldName);
                            if (json != null)
                            {
                                FieldInfo field = typeof(GameplayModifiers).GetField(fieldName, BindingFlags.Instance | BindingFlags.NonPublic);
                                object activeValue = field.GetValue(gameplayModifiers);
                                if (json is string jsonString)
                                {
                                    switch (fieldName)
                                    {
                                        case "_energyType":
                                            json = Enum.Parse(typeof(GameplayModifiers.EnergyType), jsonString);
                                            break;

                                        case "_enabledObstacleType":
                                            json = Enum.Parse(typeof(GameplayModifiers.EnabledObstacleType), jsonString);
                                            break;

                                        case "_songSpeed":
                                            json = Enum.Parse(typeof(GameplayModifiers.SongSpeed), jsonString);
                                            break;
                                    }
                                }
                                else if (json is IConvertible)
                                {
                                    json = Convert.ChangeType(json, activeValue.GetType());
                                }

                                if (!json.Equals(activeValue))
                                {
                                    _contents.Add(new ListObject($"[Modifiers] {name}", $"{activeValue} > {json}"));
                                    field.SetValue(modifiedGameplayModifiers, json);
                                }
                            }
                        }

                        _modifiedParameters.GameplayModifiers = modifiedGameplayModifiers;
                    }

                    Dictionary<string, object?>? jsonEnvironments = settings.Get<Dictionary<string, object?>>("_environments");
                    if (jsonEnvironments != null)
                    {
                        OverrideEnvironmentSettings? environmentOverrideSettings = startParameters.OverrideEnvironmentSettings;

                        if (environmentOverrideSettings != null)
                        {
                            Dictionary<string, object> settableEnvironmentSetting = SettingSetterSettableSettingsManager.SettingsTable["_environments"].First();
                            string name = (string)settableEnvironmentSetting["_name"];
                            string fieldName = (string)settableEnvironmentSetting["_fieldName"];
                            bool activeValue = environmentOverrideSettings.overrideEnvironments;
                            bool? json = jsonEnvironments.Get<bool>(fieldName);

                            if (json != null && json != activeValue)
                            {
                                _contents.Add(new ListObject($"[Environments] {name}", $"{activeValue} > {json}"));

                                // copy fields from original overrideenvironmentsettings to our new copy
                                OverrideEnvironmentSettings modifiedOverrideEnvironmentSettings = new OverrideEnvironmentSettings();
                                modifiedOverrideEnvironmentSettings.SetField("_data", environmentOverrideSettings.GetField<Dictionary<EnvironmentTypeSO, EnvironmentInfoSO>, OverrideEnvironmentSettings>("_data"));

                                modifiedOverrideEnvironmentSettings.overrideEnvironments = json.Value;

                                _modifiedParameters.OverrideEnvironmentSettings = modifiedOverrideEnvironmentSettings;
                            }
                        }
                    }

                    Dictionary<string, object?>? jsonColors = settings.Get<Dictionary<string, object?>>("_colors");
                    if (jsonColors != null)
                    {
                        ColorSchemesSettings? colorSchemesSettings = OverrideColorScheme;

                        if (colorSchemesSettings != null)
                        {
                            Dictionary<string, object> settableColorSetting = SettingSetterSettableSettingsManager.SettingsTable["_colors"].First();
                            string name = (string)settableColorSetting["_name"];
                            string fieldName = (string)settableColorSetting["_fieldName"];
                            bool activeValue = colorSchemesSettings.overrideDefaultColors;
                            bool? json = jsonColors.Get<bool>(fieldName);

                            if (json != null && json != activeValue)
                            {
                                _contents.Add(new ListObject($"[Colors] {name}", $"{activeValue} > {json}"));

                                _modifiedParameters.OverrideColorScheme = json.Value ? colorSchemesSettings.GetOverrideColorScheme() : null;
                            }
                        }
                    }

                    _modifiedMainSettings = null;
                    _cachedMainSettings = null;
                    Dictionary<string, object?>? jsonGraphics = settings.Get<Dictionary<string, object?>>("_graphics");
                    if (jsonGraphics != null)
                    {
                        MainSettingsModelSO mainSettingsModel = MainSettings;
                        List<Dictionary<string, object>> settableGraphicsSettings = SettingSetterSettableSettingsManager.SettingsTable["_graphics"];

                        _cachedMainSettings = new SettableMainSettings(
                            mainSettingsModel.mirrorGraphicsSettings,
                            mainSettingsModel.mainEffectGraphicsSettings,
                            mainSettingsModel.smokeGraphicsSettings,
                            mainSettingsModel.burnMarkTrailsEnabled,
                            mainSettingsModel.screenDisplacementEffectsEnabled,
                            mainSettingsModel.maxShockwaveParticles);
                        _modifiedMainSettings = _cachedMainSettings with { };

                        foreach (Dictionary<string, object> settableGraphicSetting in settableGraphicsSettings)
                        {
                            string name = (string)settableGraphicSetting["_name"];
                            string fieldName = (string)settableGraphicSetting["_fieldName"];

                            object? json = jsonGraphics.Get<object>(fieldName);
                            if (json != null)
                            {
                                // substring is to remove underscore
                                object valueSO = typeof(MainSettingsModelSO).GetField(fieldName.Substring(1), BindingFlags.Instance | BindingFlags.Public).GetValue(mainSettingsModel);
                                object activeValue = valueSO switch
                                {
                                    BoolSO boolSO => boolSO.value,
                                    IntSO intSO => intSO.value,
                                    _ => throw new InvalidOperationException($"How the hell did you reach this? [{valueSO.GetType()}]"),
                                };
                                if (json is IConvertible)
                                {
                                    json = Convert.ChangeType(json, activeValue.GetType());
                                }

                                if (!json.Equals(activeValue))
                                {
                                    _contents.Add(new ListObject($"[Graphics] {name}", $"{activeValue} > {json}"));
                                    typeof(SettableMainSettings).GetField(fieldName, BindingFlags.Instance | BindingFlags.NonPublic).SetValue(_modifiedMainSettings, json);
                                }
                            }
                        }
                    }

                    _settableSettingsToSet = null;
                    foreach (KeyValuePair<string, Dictionary<string, ISettableSetting>> groupSettingPair in SettingSetterSettableSettingsManager.SettableSettings)
                    {
                        Dictionary<string, object?>? jsonGroup = settings.Get<Dictionary<string, object?>>(groupSettingPair.Key);
                        if (jsonGroup != null)
                        {
                            _settableSettingsToSet = new List<Tuple<ISettableSetting, object>>();

                            foreach (KeyValuePair<string, ISettableSetting> settableSettingPair in groupSettingPair.Value)
                            {
                                object? json = jsonGroup.Get<object>(settableSettingPair.Key);
                                ISettableSetting settableSetting = settableSettingPair.Value;
                                object activeValue = settableSetting.TrueValue;
                                if (json != null && !json.Equals(activeValue))
                                {
                                    _contents.Add(new ListObject($"[{settableSetting.GroupName}] {settableSetting.FieldName}", $"{activeValue} > {json}"));
                                    _settableSettingsToSet.Add(new Tuple<ISettableSetting, object>(settableSetting, json));
                                }
                            }
                        }
                    }

                    if (_contents.Any())
                    {
                        if (_contentObject != null)
                        {
                            Destroy(_contentObject);
                        }

                        DoPresent = true;
                        _defaultParameters = startParameters;
                        _menuTransitionsHelper = menuTransitionsHelper;
                        _presentViewController(ActiveFlowCoordinator, this, null, AnimationDirection.Horizontal, false);
                        BeatSaberMarkupLanguage.BSMLParser.instance.Parse(ContentBSML, gameObject, this);
                        return;
                    }
                }
            }

19 View Source File : MissionParameterParser.cs
License : MIT License
Project Creator : ahydrax

public static (object value, ErrorType error, bool ok) ParseParameter(Type parameterType, string parameterValue)
        {
            switch (parameterType)
            {
                case var t when t == typeof(string):
                    return (parameterValue, ErrorType.No, true);

                case var t when t == typeof(bool):
                    return TryParse(JsonConvert.DeserializeObject<bool>, parameterValue);

                case var t when t == typeof(byte):
                    return TryParse(x => byte.Parse(x, NumberStyles.Any, CultureInfo.InvariantCulture), parameterValue);

                case var t when t == typeof(sbyte):
                    return TryParse(x => sbyte.Parse(x, NumberStyles.Any, CultureInfo.InvariantCulture),
                        parameterValue);

                case var t when t == typeof(char):
                    return TryParse(x => x[0], parameterValue);

                case var t when t == typeof(decimal):
                    return TryParse(x => decimal.Parse(x, NumberStyles.Any, CultureInfo.InvariantCulture),
                        parameterValue);

                case var t when t == typeof(double):
                    return TryParse(x => double.Parse(x, NumberStyles.Any, CultureInfo.InvariantCulture),
                        parameterValue);

                case var t when t == typeof(float):
                    return TryParse(x => float.Parse(x, NumberStyles.Any, CultureInfo.InvariantCulture),
                        parameterValue);

                case var t when t == typeof(int):
                    return TryParse(x => int.Parse(x, NumberStyles.Any, CultureInfo.InvariantCulture), parameterValue);

                case var t when t == typeof(uint):
                    return TryParse(x => uint.Parse(x, NumberStyles.Any, CultureInfo.InvariantCulture), parameterValue);

                case var t when t == typeof(long):
                    return TryParse(x => long.Parse(x, NumberStyles.Any, CultureInfo.InvariantCulture), parameterValue);

                case var t when t == typeof(ulong):
                    return TryParse(x => ulong.Parse(x, NumberStyles.Any, CultureInfo.InvariantCulture),
                        parameterValue);

                case var t when t == typeof(short):
                    return TryParse(x => short.Parse(x, NumberStyles.Any, CultureInfo.InvariantCulture),
                        parameterValue);

                case var t when t == typeof(ushort):
                    return TryParse(x => ushort.Parse(x, NumberStyles.Any, CultureInfo.InvariantCulture),
                        parameterValue);

                case var t when t == typeof(DateTime):
                    return TryParse(
                        x => DateTimeOffset.ParseExact(x, "yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture, DateTimeStyles.None)
                            .UtcDateTime,
                        parameterValue);

                case var t when t == typeof(DateTimeOffset):
                    return TryParse(
                        x => DateTimeOffset.ParseExact(x, "yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture, DateTimeStyles.None),
                        parameterValue);

                case var t when t == typeof(Guid):
                    return TryParse(Guid.Parse, parameterValue);
                
                case var t when t.IsEnum:
                    return TryParse(x => Enum.Parse(parameterType, x), parameterValue);

                case var pctx when pctx == typeof(PerformContext):
                case var jct when jct == typeof(IJobCancellationToken):
                case var ct when ct == typeof(CancellationToken):
                    return (null, ErrorType.No, true);

                case var t when t.CanBeInstantiated():
                    return TryParse(x => JsonConvert.DeserializeObject(parameterValue, t), parameterValue);

                default:
                    return (null, ErrorType.Unsupported, false);
            }
        }

19 View Source File : DataConverter.cs
License : GNU General Public License v3.0
Project Creator : aiportal

public static object ChangeType(object val, Type type)
		{
			object result = null;
			if (val != null && val != DBNull.Value)
			{
				Type srcType = val.GetType();
				if (srcType == type)
				{
					result = val;
				}
				else if (val is string)
				{
					string str = val as string;
					if (type.IsEnum)
						result = Enum.Parse(type, str);
					else if (type == typeof(string[]))
						result = string.IsNullOrEmpty(str) ? null : str.Split(',');
					else if (type == typeof(Guid))
						result = new Guid(val as string);
					else
						result = System.Convert.ChangeType(str, type);
				}
				else
				{
					if (type.IsEnum)
						result = Enum.ToObject(type, val);
					else if (srcType == typeof(Guid) && type == typeof(string))
						result = val.ToString();
					else
						result = System.Convert.ChangeType(val, type);
				}
			}
			return result;
		}

19 View Source File : DataConverter.cs
License : GNU General Public License v3.0
Project Creator : aiportal

public static object ChangeType(object obj, Type type)
		{
			if (obj == null || obj == DBNull.Value)
				return null;
			if (obj.GetType() == type)
				return obj;
			if (type == typeof(object))
				return obj;

			object result = null;
			try
			{
				if (obj is string)
				{
					if (_deserializeMethods.ContainsKey(type))
					{
						var method = _deserializeMethods[type];
						result = method.Invoke(_single, new object[] { obj as string });
					}
					else
					{
						if (type.IsEnum)
							result = Enum.Parse(type, obj as string);
						else
							result = System.Convert.ChangeType(obj, type);
					}
				}
				else if (type == typeof(string))
				{
					if (_serializeMethods.ContainsKey(obj.GetType()))
					{
						var method = _serializeMethods[obj.GetType()];
						result = method.Invoke(_single, new object[] { obj }) as string;
					}
					else
						result = obj.ToString();
				}
				else
				{
					if (type.IsEnum)
						result = Enum.ToObject(type, obj);
					else
						result = System.Convert.ChangeType(obj, type);
				}
			}
			catch (Exception ex) { TraceLogger.Instance.WriteException(ex); throw; }
			return result;
		}

19 View Source File : DataConverter.cs
License : GNU General Public License v3.0
Project Creator : aiportal

private static object ObjectFromString(string str, Type type)
		{
			object result = null;
			if (string.IsNullOrEmpty(str))
				result = type.IsValueType ? Activator.CreateInstance(type) : null;
			else if (type == typeof(Guid))
				result = new Guid(str);
			else if (type == typeof(DateTime))
				result = DateTime.Parse(str);
			else if (type == typeof(Decimal))
				result = Decimal.Parse(str);
			else if (type.IsEnum)
				result = Enum.Parse(type, str);
			else if (type.IsArray)
				result = ArrayFromString(str, type);
			else
			{
				var parse = type.GetParseMethod();
				if (parse != null)
					result = parse.Invoke(null, new object[] { str });
				else
				{
					if (type.IsValueType && !type.IsPrimitive)
						result = StructFromString(str, type);
					else
						result = System.Convert.ChangeType(str, type);
				}
			}
			return result;
		}

19 View Source File : ProviderGuid.cs
License : Apache License 2.0
Project Creator : airbus-cert

public static ProviderGuid Parse(string name)
        {
            var providerGuid = TraceEventProviders.GetProviderGuidByName(name);
            if (providerGuid != Guid.Empty)
            {
                return new ProviderGuid
                {
                    Type = ProviderType.Manifest,
                    Guid = providerGuid
                };
            }
            
            var matches = PATTERN.Matches(name);

            if (matches.Count != 1)
            {
                throw new Exception("Invalid Provider Format");
            }

            GroupCollection matchGroup = matches[0].Groups;

            return new ProviderGuid
            {
                Type = (ProviderType)Enum.Parse(typeof(ProviderType), matchGroup["type"].Value),
                Guid = Guid.Parse(matchGroup["guid"].Value)
            };
        }

19 View Source File : XMLStuff.cs
License : GNU General Public License v3.0
Project Creator : Albo1125

public static List<TransportWorldDistrict> LoadTransportWorldDistrictsFromXMLFile(string file)
        {
            TransportWorldDistrict DefaultCityDistrict = new TransportWorldDistrict()
            {
                WorldDistrict = Zones.WorldDistricts.City,
                DriverModels = new Model[] { "S_M_Y_COP_01" },
                PreplacedengerModels = new Model[] { "S_F_Y_COP_01" },
                VehSettings = new VehicleSettings[] { new VehicleSettings("POLICET", -1, new int[] { }) }
            };
            TransportWorldDistrict DefaultCountrysideDistrict = new TransportWorldDistrict()
            {
                WorldDistrict = Zones.WorldDistricts.LosSantosCountryside,
                DriverModels = new Model[] { "S_M_Y_SHERIFF_01" },
                PreplacedengerModels = new Model[] { "S_F_Y_SHERIFF_01" },
                VehSettings = new VehicleSettings[] { new VehicleSettings("SHERIFF2", -1, new int[] { }) }
            };
            TransportWorldDistrict DefaultBlaineDistrict = new TransportWorldDistrict()
            {
                WorldDistrict = Zones.WorldDistricts.BlaineCounty,
                DriverModels = new Model[] { "S_M_Y_SHERIFF_01" },
                PreplacedengerModels = new Model[] { "S_F_Y_SHERIFF_01" },
                VehSettings = new VehicleSettings[] { new VehicleSettings("SHERIFF2", -1, new int[] { }) }
            };

            TransportWorldDistrict DefaulreplacederDistrict = new TransportWorldDistrict()
            {
                WorldDistrict = Zones.WorldDistricts.Water,
                DriverModels = new Model[] { "s_m_y_uscg_01" },
                PreplacedengerModels = new Model[] { "s_m_y_uscg_01" },
                VehSettings = new VehicleSettings[] { new VehicleSettings("PREDATOR", -1, new int[] { }) }
            };

            try
            {

                #region defaultdoreplacedent
                if (!File.Exists(file))
                {
                    Directory.CreateDirectory(Directory.GetParent(file).FullName);
                    new XDoreplacedent(
                    new XElement("ArrestManager",
                        new XComment(@"These Transport World Districts are used if you call for transport within a certain world district and you don't have a transport region set up for that district.

    Multiple Transport World Districts can be set up for more than one zone.

    In that case, Arrest Manager will select a random one from the ones that you've specified for that zone.
    There must be at least one Transport World District for each of the following:

    Valid district names are: City, LosSantosCountryside, BlaineCounty, Water.

    Certain restrictions & conditions apply: Driver & Preplacedenger & Vehicle models must be valid.
    A vehicle must have at least 4 free seats and must be a Police vehicle(with the exception of the RIOT van).This means a FLAG_LAW_ENFORCEMENT in vehicles.meta must be present.
    Water districts must have boats as vehicles.

    LiveryNumber and ExtraNumbers are optional.
    For LiveryNumber & ExtraNumbers: Keep in mind the code starts counting at 0.If a LiveryNumber is 1 in OpenIV, it will be 0 in code so you must enter 0.
    If the LiveryNumber is 2 in OpenIV it will be 1 in code so you must enter 1 etc.

    ExtraNumbers must be separated by commas, e.g. 2,3,4,5.

    Naturally, you can add as many TransportWorldDistricts as you like - just keep them between the <ArrestManager> and </ArrestManager> tags.
    The below ones are meant as examples of what you can do.
    The default XML file that comes with the Arrest Manager download (this one, if you haven't changed it) works ingame.

    There's no need to change anything if you don't want to.

    If you don't set anything at all for a certain district (not recommended) a very basic default will be set by Arrest Manager itself.


    Here you can change the ped that's driving the transport vehicle. You can find all valid values here: http://ragepluginhook.net/PedModels.aspx

    Police unit uniforms
    Male City Police: s_m_y_cop_01
    Female City Police: s_f_y_cop_01
    Female Sheriff: s_f_y_sheriff_01
    Male Sheriff: s_m_y_sheriff_01
    Male Highway: s_m_y_hwaycop_01
    Prison Guard: s_m_m_prisguard_01

    Police Vehicle Examples: POLICE, POLICE2, POLICE3, POLICE4, POLICET, SHERIFF, SHERIFF2"


                        ), new XElement("TransportWorldDistrict",
                            new XAttribute("DistrictName", "City"),
                            new XElement("Driver", new XAttribute("Model", "S_M_Y_COP_01")),
                            new XElement("Driver", new XAttribute("Model", "S_F_Y_COP_01")),
                            new XElement("Preplacedenger", new XAttribute("Model", "S_M_Y_COP_01")),
                            new XElement("Preplacedenger", new XAttribute("Model", "S_F_Y_COP_01")),
                            new XElement("Vehicle", new XAttribute("Model", "POLICET"), new XAttribute("LiveryNumber", "0")),
                            new XElement("Vehicle", new XAttribute("Model", "POLICE")),
                            new XElement("Vehicle", new XAttribute("Model", "POLICE2"), new XAttribute("ExtraNumbers", "1")),
                            new XElement("Vehicle", new XAttribute("Model", "POLICE3"), new XAttribute("LiveryNumber", "0"), new XAttribute("ExtraNumbers", "1"))
                        ),

                          new XElement("TransportWorldDistrict",
                            new XAttribute("DistrictName", "City"),
                            new XElement("Driver", new XAttribute("Model", "S_M_Y_COP_01")),
                            new XElement("Driver", new XAttribute("Model", "S_F_Y_COP_01")),
                            new XElement("Preplacedenger", new XAttribute("Model", "S_F_Y_COP_01")),
                            new XElement("Preplacedenger", new XAttribute("Model", "S_M_Y_COP_01")),
                            new XElement("Vehicle", new XAttribute("Model", "POLICET")),
                            new XElement("Vehicle", new XAttribute("Model", "POLICE")),
                            new XElement("Vehicle", new XAttribute("Model", "POLICE2")),
                            new XElement("Vehicle", new XAttribute("Model", "POLICE3"))
                            ),

                          new XElement("TransportWorldDistrict",
                            new XAttribute("DistrictName", "LosSantosCountryside"),
                            new XElement("Driver", new XAttribute("Model", "S_M_Y_SHERIFF_01")),
                            new XElement("Driver", new XAttribute("Model", "S_F_Y_SHERIFF_01")),
                            new XElement("Preplacedenger", new XAttribute("Model", "S_M_Y_SHERIFF_01")),
                            new XElement("Preplacedenger", new XAttribute("Model", "S_F_Y_SHERIFF_01")),
                            new XElement("Vehicle", new XAttribute("Model", "SHERIFF2"))
                            ),

                          new XElement("TransportWorldDistrict",
                            new XAttribute("DistrictName", "BlaineCounty"),
                            new XElement("Driver", new XAttribute("Model", "S_M_Y_SHERIFF_01")),
                            new XElement("Driver", new XAttribute("Model", "S_F_Y_SHERIFF_01")),
                            new XElement("Preplacedenger", new XAttribute("Model", "S_M_Y_SHERIFF_01")),
                            new XElement("Preplacedenger", new XAttribute("Model", "S_F_Y_SHERIFF_01")),
                            new XElement("Vehicle", new XAttribute("Model", "SHERIFF2"), new XAttribute("LiveryNumber", "0"), new XAttribute("ExtraNumbers", "2,3,4"))
                            ),
                          new XElement("TransportWorldDistrict",
                            new XAttribute("DistrictName", "Water"),
                            new XElement("Driver", new XAttribute("Model", "S_M_Y_USCG_01")),
                            new XElement("Preplacedenger", new XAttribute("Model", "S_M_Y_USCG_01")),
                            new XElement("Vehicle", new XAttribute("Model", "PREDATOR"))
                            )
                        )

                    ).Save(file);
                    Game.LogTrivial("Transport world district file did not exist. Created default.");
                }
                #endregion
                XDoreplacedent xdoc = XDoreplacedent.Load(file);
                char[] trim = new char[] { '\'', '\"', ' ' };
                
                List<TransportWorldDistrict> trnswrlddistrs = xdoc.Descendants("TransportWorldDistrict").Select(x => new TransportWorldDistrict()
                {
                    WorldDistrict = (Zones.WorldDistricts)Enum.Parse(typeof(Zones.WorldDistricts), ((string)x.Attribute("DistrictName")).Trim(trim)),
                    DriverModels = (x.Elements("Driver").Select(y => new Model(((string)y.Attribute("Model")).Trim(trim))).ToArray()),
                    PreplacedengerModels = (x.Elements("Preplacedenger").Select(y => new Model(((string)y.Attribute("Model")).Trim(trim))).ToArray()),
                    VehSettings = (x.Elements("Vehicle").Select(y => new VehicleSettings(new Model((((string)y.Attribute("Model"))).Trim(trim)),
                    (string)y.Attribute("LiveryNumber") != null && !string.IsNullOrWhiteSpace((string)y.Attribute("LiveryNumber")) ? Int32.Parse(((string)y.Attribute("LiveryNumber")).Trim(trim)) : -1,
                    (string)y.Attribute("ExtraNumbers") != null && !string.IsNullOrWhiteSpace((string)y.Attribute("ExtraNumbers")) ? Array.ConvertAll(((string)y.Attribute("ExtraNumbers")).Trim(trim).Replace(" ", "").ToLower().Split(','), int.Parse) : new int[] { })).ToArray()),
                    
                }).ToList<TransportWorldDistrict>();
                
                foreach (Zones.WorldDistricts distr in Enum.GetValues(typeof(Zones.WorldDistricts)))
                {
                    if (!trnswrlddistrs.Select(x => x.WorldDistrict).Contains(distr))
                    {
                        Game.LogTrivial("Transport World Districts doesn't contain " + distr.ToString() + ". Adding default.");
                        if (distr == Zones.WorldDistricts.City)
                        {
                            
                            trnswrlddistrs.Add(DefaultCityDistrict);
                        }
                        else if (distr == Zones.WorldDistricts.LosSantosCountryside)
                        {
                            trnswrlddistrs.Add(DefaultCountrysideDistrict);
                        }
                        else if (distr == Zones.WorldDistricts.BlaineCounty)
                        {
                            trnswrlddistrs.Add(DefaultBlaineDistrict);
                        }
                        else if (distr == Zones.WorldDistricts.Water)
                        {
                            trnswrlddistrs.Add(DefaulreplacederDistrict);
                        }

                    }
                }

                return trnswrlddistrs;
            }
            catch (System.Threading.ThreadAbortException) { }
            catch (Exception e)
            {
                Game.LogTrivial("Arrest Manager encountered an exception reading \'" + file + "\'. It was: " + e.ToString());
                Game.DisplayNotification("~r~Error reading Transport World Districts.xml. Setting default values.");
            }

            return new List<TransportWorldDistrict>() { DefaultCityDistrict, DefaultBlaineDistrict, DefaultCountrysideDistrict };
        }

19 View Source File : LSPDFRPlusHandler.cs
License : GNU General Public License v3.0
Project Creator : Albo1125

public static void Initialise()
        {
            //ini stuff

            InitializationFile ini = new InitializationFile("Plugins/LSPDFR/LSPDFR+.ini");
            ini.Create();
            try
            {
                EnhancedTrafficStop.BringUpTrafficStopMenuControllerButton = ini.ReadEnum<ControllerButtons>("General", "BringUpTrafficStopMenuControllerButton", ControllerButtons.DPadRight);
                EnhancedTrafficStop.BringUpTrafficStopMenuKey = (Keys)kc.ConvertFromString(ini.ReadString("General", "BringUpTrafficStopMenuKey", "D7"));
              
                try
                {
                    stockLSPDFRIni = new InitializationFile(LSPDFRKeyIniPath);
                    string[] stockinicontents = File.ReadAllLines(LSPDFRKeyIniPath);
                    //Alternative INI reading implementation, RPH doesn't work with sectionless INIs.
                    foreach (string line in stockinicontents)
                    {
                        if (line.StartsWith("TRAFFICSTOP_INTERACT_Key="))
                        {
                            stockTrafficStopInteractKey = (Keys)kc.ConvertFromString(line.Substring(line.IndexOf('=') + 1));
                        }
                        else if (line.StartsWith("TRAFFICSTOP_INTERACT_ModifierKey"))
                        {
                            stockTrafficStopInteractModifierKey = (Keys)kc.ConvertFromString(line.Substring(line.IndexOf('=') + 1));
                        }
                        else if (line.StartsWith("TRAFFICSTOP_INTERACT_ControllerKey"))
                        {
                            stockTrafficStopInteractControllerButton = (ControllerButtons)Enum.Parse(typeof(ControllerButtons), line.Substring(line.IndexOf('=') + 1));
                        }
                        else if (line.StartsWith("TRAFFICSTOP_INTERACT_ControllerModifierKey"))
                        {
                            stockTrafficStopInteractModifierControllerButton = (ControllerButtons)Enum.Parse(typeof(ControllerButtons), line.Substring(line.IndexOf('=') + 1));
                        }
                    }
                    if ((EnhancedTrafficStop.BringUpTrafficStopMenuKey == stockTrafficStopInteractKey && stockTrafficStopInteractModifierKey == Keys.None) || (EnhancedTrafficStop.BringUpTrafficStopMenuControllerButton == stockTrafficStopInteractControllerButton && stockTrafficStopInteractModifierControllerButton == ControllerButtons.None))
                    {
                        TrafficStopMenuPopup = new Popup("LSPDFR+: Traffic Stop Menu Conflict", "Your LSPDFR+ traffic stop menu keys (plugins/lspdfr/lspdfr+.ini) are the same as the default LSPDFR traffic stop keys (lspdfr/keys.ini TRAFFICSTOP_INTERACT_Key and TRAFFICSTOP_INTERACT_ControllerKey). How would you like to solve this?",
                            new List<string>() { "Recommended: Automatically disable the default LSPDFR traffic stop menu keys (this will edit keys.ini TRAFFICSTOP_INTERACT_Key and TRAFFICSTOP_INTERACT_ControllerKey to None)", "I know what I'm doing, I will change the keys in the INIs myself!" }, false, true, TrafficStopMenuCb);
                        TrafficStopMenuPopup.Display();
                    }
                }
                catch (Exception e)
                {
                    Game.LogTrivial($"Failed to determine stock LSPDFR key bind/controller button for traffic stop keys: {e}");
                }
              
                CourtSystem.OpenCourtMenuKey = (Keys)kc.ConvertFromString(ini.ReadString("OnlyWithoutBritishPolicingScriptInstalled", "OpenCourtMenuKey", "F9"));
                CourtSystem.OpenCourtMenuModifierKey = (Keys)kc.ConvertFromString(ini.ReadString("OnlyWithoutBritishPolicingScriptInstalled", "OpenCourtMenuModifierKey", "None"));
                EnhancedTrafficStop.EnhancedTrafficStopsEnabled = ini.ReadBoolean("General", "EnhancedTrafficStopsEnabled", true);
                EnhancedPursuitAI.EnhancedPursuitAIEnabled = ini.ReadBoolean("General", "EnhancedPursuitAIEnabled", true);
                EnhancedPursuitAI.AutoPursuitBackupEnabled = ini.ReadBoolean("General", "AutoPursuitBackupEnabled", false);
                EnhancedPursuitAI.OpenPursuitTacticsMenuKey = (Keys)kc.ConvertFromString(ini.ReadString("General", "OpenPursuitTacticsMenuKey", "Q"));
                EnhancedPursuitAI.OpenPursuitTacticsMenuModifierKey = (Keys)kc.ConvertFromString(ini.ReadString("General", "OpenPursuitTacticsMenuModifierKey", "LShiftKey"));
                EnhancedPursuitAI.DefaultAutomaticAI = ini.ReadBoolean("General", "DefaultAutomaticAI", true);

                Offence.maxpoints = ini.ReadInt32("General", "MaxPoints", 12);
                Offence.pointincstep = ini.ReadInt32("General", "PointsIncrementalStep", 1);
                Offence.maxFine = ini.ReadInt32("General", "MaxFine", 5000);

                Offence.OpenTicketMenuKey = (Keys)kc.ConvertFromString(ini.ReadString("General", "OpenTicketMenuKey", "Q"));
                Offence.OpenTicketMenuModifierKey = (Keys)kc.ConvertFromString(ini.ReadString("General", "OpenTicketMenuModifierKey", "LShiftKey"));
                Offence.enablePoints = ini.ReadBoolean("General", "EnablePoints", true);

                CourtSystem.RealisticCourtDates = ini.ReadBoolean("OnlyWithoutBritishPolicingScriptInstalled", "RealisticCourtDates", true);
            }
            catch (Exception e)
            {
                Game.LogTrivial(e.ToString());
                Game.LogTrivial("Error loading LSPDFR+ INI file. Loading defaults");
                Game.DisplayNotification("~r~Error loading LSPDFR+ INI file. Loading defaults");
            }
            BetaCheck();
        }

19 View Source File : MapboxToken.cs
License : MIT License
Project Creator : alen-smajic

public static MapboxToken FromResponseData(byte[] data)
		{

			if (null == data || data.Length < 1)
			{
				return new MapboxToken()
				{
					HasError = true,
					ErrorMessage = "No data received from token endpoint."
				};
			}


			string jsonTxt = Encoding.UTF8.GetString(data);

			MapboxToken token = new MapboxToken();
			try
			{
				token = JsonConvert.DeserializeObject<MapboxToken>(jsonTxt);

				MapboxTokenStatus status = (MapboxTokenStatus)Enum.Parse(typeof(MapboxTokenStatus), token.Code);
				if (!Enum.IsDefined(typeof(MapboxTokenStatus), status))
				{
					throw new Exception(string.Format("could not convert token.code '{0}' to MapboxTokenStatus", token.Code));
				}

				token.Status = status;
			}
			catch (Exception ex)
			{
				token.HasError = true;
				token.ErrorMessage = ex.Message;
			}

			return token;
		}

19 View Source File : FeaturesSubLayerPropertiesDrawer.cs
License : MIT License
Project Creator : alen-smajic

void FetchPresetProperties(object name)
		{
			PresetFeatureType featureType = ((PresetFeatureType)Enum.Parse(typeof(PresetFeatureType), name.ToString()));
			subLayerProperties = PresetSubLayerPropertiesFetcher.GetSubLayerProperties(featureType);
		}

19 View Source File : IconControl.cs
License : GNU General Public License v3.0
Project Creator : alexdillon

private string GetPathData(string iconPath)
        {
            var iconNameParts = iconPath.Split(new char[] { '.' }, 2);
            var iconPackName = iconNameParts[0];
            var iconName = iconNameParts[1];

            var data = string.Empty;

            switch (iconPackName)
            {
                case nameof(PackIconEntypoKind):
                    PackIconEntypoDataFactory.DataIndex.Value?.TryGetValue((PackIconEntypoKind)Enum.Parse(typeof(PackIconEntypoKind), iconName), out data);
                    return data;
                case nameof(PackIconFeatherIconsKind):
                    PackIconFeatherIconsDataFactory.DataIndex.Value?.TryGetValue((PackIconFeatherIconsKind)Enum.Parse(typeof(PackIconFeatherIconsKind), iconName), out data);
                    return data;
                case nameof(PackIconFontAwesomeKind):
                    PackIconFontAwesomeDataFactory.DataIndex.Value?.TryGetValue((PackIconFontAwesomeKind)Enum.Parse(typeof(PackIconFontAwesomeKind), iconName), out data);
                    return data;
                case nameof(PackIconMaterialKind):
                    PackIconMaterialDataFactory.DataIndex.Value?.TryGetValue((PackIconMaterialKind)Enum.Parse(typeof(PackIconMaterialKind), iconName), out data);
                    return data;
                case nameof(PackIconOcticonsKind):
                    PackIconOcticonsDataFactory.DataIndex.Value?.TryGetValue((PackIconOcticonsKind)Enum.Parse(typeof(PackIconOcticonsKind), iconName), out data);
                    return data;
                default:
                    return null;
            }
        }

19 View Source File : PropertyNode.cs
License : MIT License
Project Creator : alexismorin

public override void ReadFromString( ref string[] nodeParams )
		{
			base.ReadFromString( ref nodeParams );
			if( UIUtils.CurrentShaderVersion() < 2505 )
			{
				string property = GetCurrentParam( ref nodeParams );
				m_currentParameterType = property.Equals( "Uniform" ) ? PropertyType.Global : (PropertyType)Enum.Parse( typeof( PropertyType ), property );
			}
			else
			{
				m_currentParameterType = (PropertyType)Enum.Parse( typeof( PropertyType ), GetCurrentParam( ref nodeParams ) );
			}

			if( m_currentParameterType == PropertyType.InstancedProperty )
			{
				UIUtils.CurrentWindow.OutsideGraph.AddInstancePropertyCount();
				UIUtils.RegisterPropertyNode( this );
			}

			if( m_currentParameterType == PropertyType.Property )
			{
				UIUtils.RegisterPropertyNode( this );
			}

			m_propertyName = GetCurrentParam( ref nodeParams );
			m_propertyInspectorName = GetCurrentParam( ref nodeParams );

			if( UIUtils.CurrentShaderVersion() > 13 )
			{
				m_orderIndex = Convert.ToInt32( GetCurrentParam( ref nodeParams ) );
			}

			if( UIUtils.CurrentShaderVersion() > 4102 )
			{
				int attribAmount = Convert.ToInt32( GetCurrentParam( ref nodeParams ) );
				if( attribAmount > 0 )
				{
					for( int i = 0; i < attribAmount; i++ )
					{
						m_selectedAttribs.Add( IdForAttrib( GetCurrentParam( ref nodeParams ) ) );
					}

					m_visibleAttribsFoldout = true;
				}
				InitializeAttribsArray();
			}


			if( UIUtils.CurrentShaderVersion() > 14003 )
			{
				m_variableMode = (VariableMode)Enum.Parse( typeof( VariableMode ), GetCurrentParam( ref nodeParams ) );
			}

			if( UIUtils.CurrentShaderVersion() > 14201 )
			{
				m_autoGlobalName = Convert.ToBoolean( GetCurrentParam( ref nodeParams ) );
			}
			if( UIUtils.CurrentShaderVersion() > 14403 )
			{
				m_enumCount = Convert.ToInt32( GetCurrentParam( ref nodeParams ) );
				for( int i = 0; i < m_enumCount; i++ )
				{
					m_enumNames.Add( GetCurrentParam( ref nodeParams ) );
					m_enumValues.Add( Convert.ToInt32( GetCurrentParam( ref nodeParams ) ) );
				}
			}

			if( UIUtils.CurrentShaderVersion() > 14501 )
			{
				m_enumModeInt = Convert.ToInt32( GetCurrentParam( ref nodeParams ) );
				if( m_enumModeInt == 1 )
					m_enumClreplacedName = GetCurrentParam( ref nodeParams );
				m_autoRegister = Convert.ToBoolean( GetCurrentParam( ref nodeParams ) );

				m_customAttrCount = Convert.ToInt32( GetCurrentParam( ref nodeParams ) );
				for( int i = 0; i < m_customAttrCount; i++ )
				{
					m_customAttr.Add( GetCurrentParam( ref nodeParams ) );
				}
				if( m_customAttrCount > 0 )
				{
					m_visibleCustomAttrFoldout = true;
					m_visibleAttribsFoldout = true;
				}
			}

			CheckEnumAttribute();
			if( m_enumCount > 0 )
				m_visibleEnumsFoldout = true;

			m_propertyNameIsDirty = true;
			m_reRegisterName = false;

			if( !m_isNodeBeingCopied )
			{
				if( m_variableMode != VariableMode.Fetch || m_currentParameterType == PropertyType.Constant )
				{
					UIUtils.ReleaseUniformName( UniqueId, m_oldName );
					UIUtils.RegisterUniformName( UniqueId, m_propertyName );
					m_oldName = m_propertyName;
				}
			}
			else
			{
				m_oldName = m_propertyName;
			}

		}

19 View Source File : BillboardOpHelper.cs
License : MIT License
Project Creator : alexismorin

public void ReadFromString( ref uint index, ref string[] nodeParams )
		{
			m_isBillboard = Convert.ToBoolean( nodeParams[ index++ ] );
			m_billboardType = (BillboardType)Enum.Parse( typeof( BillboardType ), nodeParams[ index++ ] );
			if( UIUtils.CurrentShaderVersion() > 11007 )
			{
				m_rotationIndependent = Convert.ToBoolean( nodeParams[ index++ ] );
			}
		}

19 View Source File : BlendOpsHelper.cs
License : MIT License
Project Creator : alexismorin

public void ReadFromString( ref uint index, ref string[] nodeParams )
		{
			m_currentIndex = Convert.ToInt32( nodeParams[ index++ ] );
			if( UIUtils.CurrentShaderVersion() > 15103 )
			{
				m_sourceFactorRGB.ReadFromString( ref index, ref nodeParams );
				m_destFactorRGB.ReadFromString( ref index, ref nodeParams );
			}
			else
			{
				m_sourceFactorRGB.IntValue = (int)(AvailableBlendFactor)Enum.Parse( typeof( AvailableBlendFactor ), nodeParams[ index++ ] );
				m_destFactorRGB.IntValue = (int)(AvailableBlendFactor)Enum.Parse( typeof( AvailableBlendFactor ), nodeParams[ index++ ] );
			}

			m_currentAlphaIndex = Convert.ToInt32( nodeParams[ index++ ] );
			if( UIUtils.CurrentShaderVersion() > 15103 )
			{
				m_sourceFactorAlpha.ReadFromString( ref index, ref nodeParams );
				m_destFactorAlpha.ReadFromString( ref index, ref nodeParams );

				m_blendOpRGB.ReadFromString( ref index, ref nodeParams );
				m_blendOpAlpha.ReadFromString( ref index, ref nodeParams );
				if( UIUtils.CurrentShaderVersion() < 15404 )
				{
					// Now BlendOps enum starts at 0 and not -1
					m_blendOpRGB.FloatValue += 1;
					m_blendOpAlpha.FloatValue += 1;
				}
			}
			else
			{
				m_sourceFactorAlpha.IntValue = (int)(AvailableBlendFactor)Enum.Parse( typeof( AvailableBlendFactor ), nodeParams[ index++ ] );
				m_destFactorAlpha.IntValue = (int)(AvailableBlendFactor)Enum.Parse( typeof( AvailableBlendFactor ), nodeParams[ index++ ] );
				m_blendOpRGB.IntValue = (int)(AvailableBlendOps)Enum.Parse( typeof( AvailableBlendOps ), nodeParams[ index++ ] );
				m_blendOpAlpha.IntValue = (int)(AvailableBlendOps)Enum.Parse( typeof( AvailableBlendOps ), nodeParams[ index++ ] );
			}

			m_enabled = ( m_currentIndex > 0 || m_currentAlphaIndex > 0 );
			m_blendOpEnabled = ( !m_blendOpRGB.Active && m_blendOpRGB.IntValue > -1 ) || ( m_blendOpRGB.Active && m_blendOpRGB.NodeId > -1 );
		}

19 View Source File : TransformVariables.cs
License : MIT License
Project Creator : alexismorin

public override void ReadFromString( ref string[] nodeParams )
		{
			base.ReadFromString( ref nodeParams );
			string selectedTypeStr = GetCurrentParam( ref nodeParams );
			try
			{
				BuiltInShaderTransformTypes selectedType = (BuiltInShaderTransformTypes)Enum.Parse( typeof( BuiltInShaderTransformTypes ), selectedTypeStr );
				m_selectedType = selectedType;
			}
			catch( Exception e )
			{
				switch( selectedTypeStr )
				{
					default: Debug.LogException( e );break;
					case "UNITY_MATRIX_TEXTURE0":UIUtils.ShowMessage("Texture 0 matrix is no longer supported",MessageSeverity.Warning);break;
					case "UNITY_MATRIX_TEXTURE1":UIUtils.ShowMessage("Texture 1 matrix is no longer supported",MessageSeverity.Warning);break;
					case "UNITY_MATRIX_TEXTURE2":UIUtils.ShowMessage("Texture 2 matrix is no longer supported",MessageSeverity.Warning);break;
					case "UNITY_MATRIX_TEXTURE3":UIUtils.ShowMessage("Texture 3 matrix is no longer supported",MessageSeverity.Warning); break;
					case "unity_Scale": UIUtils.ShowMessage( "Scale matrix is no longer supported", MessageSeverity.Warning ); break;
				}
			}

			ChangeOutputName( 0, ValuesStr[ ( int ) m_selectedType ] );
		}

19 View Source File : StaticSwitch.cs
License : MIT License
Project Creator : alexismorin

public override void ReadFromString( ref string[] nodeParams )
		{
			base.ReadFromString( ref nodeParams );
			m_multiCompile = Convert.ToInt32( GetCurrentParam( ref nodeParams ) );
			if( UIUtils.CurrentShaderVersion() > 14403 )
			{
				m_defaultValue = Convert.ToInt32( GetCurrentParam( ref nodeParams ) );
				if( UIUtils.CurrentShaderVersion() > 14101 )
				{
					m_materialValue = Convert.ToInt32( GetCurrentParam( ref nodeParams ) );
				}
			}
			else
			{
				m_defaultValue = Convert.ToBoolean( GetCurrentParam( ref nodeParams ) ) ? 1 : 0;
				if( UIUtils.CurrentShaderVersion() > 14101 )
				{
					m_materialValue = Convert.ToBoolean( GetCurrentParam( ref nodeParams ) ) ? 1 : 0;
				}
			}

			if( UIUtils.CurrentShaderVersion() > 13104 )
			{
				m_createToggle = Convert.ToBoolean( GetCurrentParam( ref nodeParams ) );
				m_currentKeyword = GetCurrentParam( ref nodeParams );
				m_currentKeywordId = UIUtils.GetKeywordId( m_currentKeyword );
			}
			if( UIUtils.CurrentShaderVersion() > 14001 )
			{
				m_keywordModeType = (KeywordModeType)Enum.Parse( typeof( KeywordModeType ), GetCurrentParam( ref nodeParams ) );
			}

			if( UIUtils.CurrentShaderVersion() > 14403 )
			{
				m_keywordEnumAmount = Convert.ToInt32( GetCurrentParam( ref nodeParams ) );
				for( int i = 0; i < m_keywordEnumAmount; i++ )
				{
					m_defaultKeywordNames[ i ] = GetCurrentParam( ref nodeParams );
				}

				UpdateLabels();
			}

			if( m_createToggle )
				UIUtils.RegisterPropertyNode( this );
			else
				UIUtils.UnregisterPropertyNode( this );

			if( UIUtils.CurrentShaderVersion() > 16304 )
			{
				string currentVarMode = GetCurrentParam( ref nodeParams );
				CurrentVarMode = (StaticSwitchVariableMode)Enum.Parse( typeof( StaticSwitchVariableMode ), currentVarMode );
				if( CurrentVarMode == StaticSwitchVariableMode.Reference )
				{
					m_referenceNodeId = Convert.ToInt32( GetCurrentParam( ref nodeParams ) );
				}
			}
			else
			{
				CurrentVarMode = (StaticSwitchVariableMode)m_variableMode;
			}

			if( UIUtils.CurrentShaderVersion() > 16700 )
			{
				m_isLocal = Convert.ToBoolean( GetCurrentParam( ref nodeParams ) );
			}
		}

19 View Source File : OutlineOpHelper.cs
License : MIT License
Project Creator : alexismorin

public void ReadFromString( ref uint index, ref string[] nodeParams )
		{
			m_enabled = Convert.ToBoolean( nodeParams[ index++ ] );
			m_outlineWidth = Convert.ToSingle( nodeParams[ index++ ] );
			m_outlineColor = IOUtils.StringToColor( nodeParams[ index++ ] );
			if( UIUtils.CurrentShaderVersion() > 5004 )
			{
				m_mode = (OutlineMode)Enum.Parse( typeof( OutlineMode ), nodeParams[ index++ ] );
			}

			if( UIUtils.CurrentShaderVersion() > 13902 )
			{
				m_noFog = Convert.ToBoolean( nodeParams[ index++ ] );
			}
		}

See More Examples