string.IndexOf(string, System.StringComparison)

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

2154 Examples 7

19 View Source File : RedisLiteHelper.cs
License : MIT License
Project Creator : AElfProject

public static string [] SplitOnFirst (this string strVal, string needle)
        {
            if (strVal == null) return EmptyStringArray;
            var pos = strVal.IndexOf (needle, StringComparison.OrdinalIgnoreCase);
            return pos == -1
                ? new [] { strVal }
                : new [] { strVal.Substring (0, pos), strVal.Substring (pos + needle.Length) };
        }

19 View Source File : IOHelper.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public static List<string> GetAllField(string path, string ext)
        {
            var fs = new List<string>();
            if (ext != null && ext.IndexOf("*", StringComparison.Ordinal) < 0 && ext.IndexOf("?", StringComparison.Ordinal) < 0)
            {
                ext = $"*.{ext}";
            }
            GetAllFiles(fs, path, ext);
            return fs.Distinct().ToList();
        }

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

public int IndexOf(string main, string pattern)
        {
            ArgumentUtility.CheckForNull(main, "main");
            ArgumentUtility.CheckForNull(pattern, "pattern");

            return main.IndexOf(pattern, m_stringComparison);
        }

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

public static string Replace(this string str, string oldValue, string newValue, StringComparison comparison)
		{
			StringBuilder sb = new StringBuilder();

			int previousIndex = 0;
			int index = str.IndexOf(oldValue, comparison);
			while (index != -1)
			{
				sb.Append(str.Substring(previousIndex, index - previousIndex));
				sb.Append(newValue);
				index += oldValue.Length;

				previousIndex = index;
				index = str.IndexOf(oldValue, index, comparison);
			}
			sb.Append(str.Substring(previousIndex));

			return sb.ToString();
		}

19 View Source File : BankIdSupportedDeviceDetector.cs
License : MIT License
Project Creator : ActiveLogin

private static BankIdSupportedDeviceOsVersion GetAndroidVersion(string userAgent)
        {
            if(string.IsNullOrWhiteSpace(userAgent))
            {
                return BankIdSupportedDeviceOsVersion.Empty;
            }

            try
            {
                //Example userAgent for Android "Mozilla/5.0 (Linux; Android 6.0.1; SM-G532G Build/MMB29T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.83 Mobile Safari/537.36";
                const string Android = "android";

                var versionNumber = userAgent.Substring(userAgent.IndexOf(Android, StringComparison.Ordinal) + Android.Length).Trim();
                versionNumber = versionNumber.Substring(0, versionNumber.IndexOf(";", StringComparison.Ordinal));
                var versionNumberList = versionNumber.Split('.').Select(v => int.TryParse(v, out var version) ? version : 0).ToArray();

                return versionNumberList.Length switch
                {
                    1 => new BankIdSupportedDeviceOsVersion(versionNumberList[0]),
                    2 => new BankIdSupportedDeviceOsVersion(versionNumberList[0], versionNumberList[1]),
                    3 => new BankIdSupportedDeviceOsVersion(versionNumberList[0], versionNumberList[1], versionNumberList[2]),
                    _ => BankIdSupportedDeviceOsVersion.Empty
                };
            }

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

public static string GetEnvironmentVariable(this Process process, IHostContext hostContext, string variable)
        {
            var trace = hostContext.GetTrace(nameof(LinuxProcessExtensions));
            Dictionary<string, string> env = new Dictionary<string, string>();

            if (Directory.Exists("/proc"))
            {
                string envFile = $"/proc/{process.Id}/environ";
                trace.Info($"Read env from {envFile}");
                string envContent = File.ReadAllText(envFile);
                if (!string.IsNullOrEmpty(envContent))
                {
                    // on linux, environment variables are seprated by '\0'
                    var envList = envContent.Split('\0', StringSplitOptions.RemoveEmptyEntries);
                    foreach (var envStr in envList)
                    {
                        // split on the first '='
                        var keyValuePair = envStr.Split('=', 2);
                        if (keyValuePair.Length == 2)
                        {
                            env[keyValuePair[0]] = keyValuePair[1];
                            trace.Verbose($"PID:{process.Id} ({keyValuePair[0]}={keyValuePair[1]})");
                        }
                    }
                }
            }
            else
            {
                // On OSX, there is no /proc folder for us to read environment for given process,
                // So we have call `ps e -p <pid> -o command` to print out env to STDOUT,
                // However, the output env are not format in a parseable way, it's just a string that concatenate all envs with space,
                // It doesn't escape '=' or ' ', so we can't parse the output into a dictionary of all envs.
                // So we only look for the env you request, in the format of variable=value. (it won't work if you variable contains = or space)
                trace.Info($"Read env from output of `ps e -p {process.Id} -o command`");
                List<string> psOut = new List<string>();
                object outputLock = new object();
                using (var p = hostContext.CreateService<IProcessInvoker>())
                {
                    p.OutputDataReceived += delegate (object sender, ProcessDataReceivedEventArgs stdout)
                    {
                        if (!string.IsNullOrEmpty(stdout.Data))
                        {
                            lock (outputLock)
                            {
                                psOut.Add(stdout.Data);
                            }
                        }
                    };

                    p.ErrorDataReceived += delegate (object sender, ProcessDataReceivedEventArgs stderr)
                    {
                        if (!string.IsNullOrEmpty(stderr.Data))
                        {
                            lock (outputLock)
                            {
                                trace.Error(stderr.Data);
                            }
                        }
                    };

                    int exitCode = p.ExecuteAsync(workingDirectory: hostContext.GetDirectory(WellKnownDirectory.Root),
                                                  fileName: "ps",
                                                  arguments: $"e -p {process.Id} -o command",
                                                  environment: null,
                                                  cancellationToken: CancellationToken.None).GetAwaiter().GetResult();
                    if (exitCode == 0)
                    {
                        trace.Info($"Successfully dump environment variables for {process.Id}");
                        if (psOut.Count > 0)
                        {
                            string psOutputString = string.Join(" ", psOut);
                            trace.Verbose($"ps output: '{psOutputString}'");

                            int varStartIndex = psOutputString.IndexOf(variable, StringComparison.Ordinal);
                            if (varStartIndex >= 0)
                            {
                                string rightPart = psOutputString.Substring(varStartIndex + variable.Length + 1);
                                if (rightPart.IndexOf(' ') > 0)
                                {
                                    string value = rightPart.Substring(0, rightPart.IndexOf(' '));
                                    env[variable] = value;
                                }
                                else
                                {
                                    env[variable] = rightPart;
                                }

                                trace.Verbose($"PID:{process.Id} ({variable}={env[variable]})");
                            }
                        }
                    }
                }
            }

            if (env.TryGetValue(variable, out string envVariable))
            {
                return envVariable;
            }
            else
            {
                return null;
            }
        }

19 View Source File : Renamer.cs
License : GNU General Public License v3.0
Project Creator : Agasper

bool CanRenameProperty(string realTypeName, PropertyDef prop)
        {
            if (!RenameProps)
                return false;
            if (prop.IsRuntimeSpecialName)
                return false;
            if (realTypeName.IndexOf("<>__AnonType", StringComparison.InvariantCulture) == 0) //Anonimous method make it hurt
                return false;
            if (prop.CustomAttributes.Any(a => a.TypeFullName.EndsWith("DoNotRename", StringComparison.InvariantCulture)))
                return false;
            return true;
        }

19 View Source File : CharRope.cs
License : MIT License
Project Creator : Abdesol

public static int IndexOf(this Rope<char> rope, string searchText, int startIndex, int length, StringComparison comparisonType)
		{
			if (rope == null)
				throw new ArgumentNullException("rope");
			if (searchText == null)
				throw new ArgumentNullException("searchText");
			rope.VerifyRange(startIndex, length);
			int pos = rope.ToString(startIndex, length).IndexOf(searchText, comparisonType);
			if (pos < 0)
				return -1;
			else
				return pos + startIndex;
		}

19 View Source File : MainViewModel.cs
License : MIT License
Project Creator : ahopper

public static bool Contains(this string source, string toCheck, StringComparison comp)
        {
            return source != null && toCheck != null && source.IndexOf(toCheck, comp) >= 0;
        }

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

private static void WriteIndexToFile()
        {
            var location = replacedembly.GetExecutingreplacedembly().Location;

            var index = location.IndexOf(@"\bin", StringComparison.InvariantCulture);

            var filePath = location.Substring(0, index) + InvertedIndexRelativePath;

            using (var outFile = new StreamWriter(filePath))
            {
                foreach (KeyValuePair<string, Posting> posting in _invertedIndex)
                {
                    var postingList = new List<string>();
                    foreach (var termInfo in posting.Value.TermInfos)
                    {
                        string indexes = string.Join(",", termInfo.TermEntryIndexes);
                        postingList.Add(string.Format("{0}:{1}", termInfo.ExamplePageId, indexes));
                    }

                    string postingData = string.Join(";", postingList);

                    var termFrequencies = posting.Value.TermInfos.Select(x => x.TermFrequency);
                    string termFrequency = string.Join(",", termFrequencies);

                    outFile.WriteLine("{0}|{1}|{2}|{3}", posting.Key, postingData, termFrequency,
                        posting.Value.InvertedDoreplacedentFrequency);
                }
            }
        }

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

private List<Dictionary<string, object>> ConvertRecordsToDictionary(OrganizationServiceContext serviceContext, IEnumerable<Enreplacedy> records, EnreplacedyMetadata enreplacedyMetadata)
		{
			var data = new List<Dictionary<string, object>>();
			var organizationMoneyFormatInfo = new OrganizationMoneyFormatInfo(serviceContext);

			foreach (var record in records)
			{
				var row = new Dictionary<string, object>
				{
					{ "RowId", record.Id.ToString("B", CultureInfo.InvariantCulture).ToUpper(CultureInfo.InvariantCulture) },
					{ "RowType", enreplacedyMetadata.ObjectTypeCode.GetValueOrDefault(0).ToString() }
				};

				// DateGrouping require us to also retrieve a datetime value so we can format series labels correctly. Grouping by day for example with a date like 9/23/2016 will result in the value 23 to be stored in the data. The DataDefinition is manually revised to add this aggregate attribute into the fetch so we get the actual date value 9/23/2016 displayed in the chart series.
				KeyValuePair<string, object> groupbyAttribute = new KeyValuePair<string, object>();
				object dategroupValue = null;
				var dategroupAttribute = record.Attributes.FirstOrDefault(a => a.Key.EndsWith("_dategroup_value"));
				if (!string.IsNullOrEmpty(dategroupAttribute.Key))
				{
					var aliasedDateGroupValue = dategroupAttribute.Value as AliasedValue;
					dategroupValue = aliasedDateGroupValue == null ? dategroupAttribute.Value : aliasedDateGroupValue.Value;
					groupbyAttribute = record.Attributes.FirstOrDefault(a =>
						a.Key != dategroupAttribute.Key
						&&
						a.Key.StartsWith(dategroupAttribute.Key.Substring(0, dategroupAttribute.Key.IndexOf("_dategroup_value", StringComparison.InvariantCulture))));
				}

				foreach (var attribute in record.Attributes)
				{
					var aliasedValue = attribute.Value as AliasedValue;
					var value = aliasedValue != null ? aliasedValue.Value : attribute.Value;
					var formattedValue = string.Empty;
					var attributeLogicalName = aliasedValue != null ? aliasedValue.AttributeLogicalName : attribute.Key;
					var attributeEnreplacedyLogicalName = aliasedValue != null ? aliasedValue.EnreplacedyLogicalName : enreplacedyMetadata.LogicalName;
					var attributeMetadata = this.GetAttributeMetadata(attributeLogicalName, attributeEnreplacedyLogicalName);
					
					if (record.FormattedValues.Contains(attribute.Key))
					{
						formattedValue = record.FormattedValues[attribute.Key];
					}

					if (attributeMetadata != null && value != null)
					{
						switch (attributeMetadata.AttributeType)
						{
							case AttributeTypeCode.Customer:
							case AttributeTypeCode.Lookup:
							case AttributeTypeCode.Owner:
								var enreplacedyReference = value as EnreplacedyReference;
								if (enreplacedyReference != null)
								{
									formattedValue = enreplacedyReference.Name;
								}
								break;
							case AttributeTypeCode.State:
							case AttributeTypeCode.Status:
							case AttributeTypeCode.Picklist:
								var optionSetValue = value as OptionSetValue;
								if (optionSetValue != null)
								{
									formattedValue =
										Adxstudio.Xrm.Core.OrganizationServiceContextExtensions.GetOptionSetValueLabel(attributeMetadata,
											optionSetValue.Value, this.contextLanguage.IsCrmMultiLanguageEnabled ? this.contextLanguage.ContextLanguage.CrmLcid : this.culture.LCID);
								}
								break;
							case AttributeTypeCode.Money:
								var money = value as Money;
								if (money != null)
								{
									value = money.Value;
									var moneyFormatter = new BaseCurrencyMoneyFormatter(organizationMoneyFormatInfo, CultureInfo.CurrentCulture);
									formattedValue = string.Format(moneyFormatter, "{0}", money);
								}
								break;
							case AttributeTypeCode.DateTime:
								if (!string.IsNullOrEmpty(dategroupAttribute.Key) && attribute.Key == groupbyAttribute.Key && dategroupValue != null)
								{
									value = dategroupValue;
								}
								if (value is DateTime)
								{
									formattedValue = ((DateTime)value).ToString(this.culture.DateTimeFormat.ShortDatePattern);
								}
								break;
							case AttributeTypeCode.BigInt:
							case AttributeTypeCode.Integer:
								if (value is int)
								{
									formattedValue = ((int)value).ToString("N", this.culture);
								}
								break;
							case AttributeTypeCode.Decimal:
								var decimalAttributeMetadata = attributeMetadata as DecimalAttributeMetadata;
								if (decimalAttributeMetadata != null && value is decimal)
								{
									formattedValue =
										((decimal)value).ToString(string.Format("N{0}", decimalAttributeMetadata.Precision.GetValueOrDefault(2)),
											this.culture);
								}
								break;
							case AttributeTypeCode.Double:
								var doubleAttributeMetadata = attributeMetadata as DoubleAttributeMetadata;
								if (doubleAttributeMetadata != null && value is double)
								{
									formattedValue =
										((double)value).ToString(string.Format("N{0}", doubleAttributeMetadata.Precision.GetValueOrDefault(2)),
											this.culture);
								}
								break;
						}
					}

					if (string.IsNullOrWhiteSpace(formattedValue))
					{
						try
						{
							formattedValue = value.ToString();
						}
						catch
						{
							// ignored
						}
					}

					if (!string.IsNullOrEmpty(formattedValue))
					{
						formattedValue = formattedValue.Replace("<", "<").Replace(">", ">");
					}

					row.Add(attribute.Key, formattedValue);
					row.Add(string.Format("{0}_Value", attribute.Key), value);
				}

				data.Add(row);
			}

			return data;
		}

19 View Source File : TypeExtensions.cs
License : MIT License
Project Creator : adamant

public static string GetFriendlyName(this Type type)
        {
            if (type.IsGenericParameter || !type.IsGenericType)
                return type.Name;

            var name = type.Name;
            var index = name.IndexOf("`", StringComparison.Ordinal);
            name = name.Substring(0, index);
            var genericArguments = string.Join(',', type.GetGenericArguments().Select(GetFriendlyName));
            return $"{name}<{genericArguments}>";
        }

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

public bool IsMatch(string searchString, ViewType viewType)
        {
            if (searchString == null) {
                return false;
            } else {
                if (viewType != Autodesk.Revit.DB.ViewType.Undefined) {
                    return ShortDescription.IndexOf(searchString, StringComparison.OrdinalIgnoreCase) > -1 && RevitViewType == viewType;
                } else {
                    return ShortDescription.IndexOf(searchString, StringComparison.OrdinalIgnoreCase) > -1;
                }
            }
        }

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

private static object Get(object input, string key)
		{
			if (input == null || key == null)
			{
				return null;
			}

			var hash = input as Hash;

			if (hash != null)
			{
				return hash[key];
			}

			var dictionary = input as IDictionary<string, object>;

			if (dictionary != null)
			{
				object value;

				return dictionary.TryGetValue(key, out value) ? value : null;
			}

			var drop = input as Drop;

			if (drop != null)
			{
				var dotIndex = key.IndexOf(".", StringComparison.InvariantCultureIgnoreCase);

				if (dotIndex > 0 && dotIndex < (key.Length - 1))
				{
					return Get(drop.InvokeDrop(key.Substring(0, dotIndex)), key.Substring(dotIndex + 1));
				}

				return drop.InvokeDrop(key);
			}

			var liquidizable = input as ILiquidizable;

			if (liquidizable != null)
			{
				return Get(liquidizable.ToLiquid(), key);
			}

			return null;
		}

19 View Source File : CompletionList.cs
License : MIT License
Project Creator : Abdesol

int GetMatchQuality(string itemText, string query)
		{
			if (itemText == null)
				throw new ArgumentNullException("itemText", "ICompletionData.Text returned null");

			// Qualities:
			//  	8 = full match case sensitive
			// 		7 = full match
			// 		6 = match start case sensitive
			//		5 = match start
			//		4 = match CamelCase when length of query is 1 or 2 characters
			// 		3 = match substring case sensitive
			//		2 = match substring
			//		1 = match CamelCase
			//		-1 = no match
			if (query == itemText)
				return 8;
			if (string.Equals(itemText, query, StringComparison.InvariantCultureIgnoreCase))
				return 7;

			if (itemText.StartsWith(query, StringComparison.InvariantCulture))
				return 6;
			if (itemText.StartsWith(query, StringComparison.InvariantCultureIgnoreCase))
				return 5;

			bool? camelCaseMatch = null;
			if (query.Length <= 2) {
				camelCaseMatch = CamelCaseMatch(itemText, query);
				if (camelCaseMatch == true) return 4;
			}

			// search by substring, if filtering (i.e. new behavior) turned on
			if (IsFiltering) {
				if (itemText.IndexOf(query, StringComparison.InvariantCulture) >= 0)
					return 3;
				if (itemText.IndexOf(query, StringComparison.InvariantCultureIgnoreCase) >= 0)
					return 2;
			}

			if (!camelCaseMatch.HasValue)
				camelCaseMatch = CamelCaseMatch(itemText, query);
			if (camelCaseMatch == true)
				return 1;

			return -1;
		}

19 View Source File : Renamer.cs
License : GNU General Public License v3.0
Project Creator : Agasper

bool CanRenameMethod(string realTypeName, MethodDef method)
        {
            if (!RenameMethods)
                return false;
            if (IsTypeFromUnity(method.DeclaringType))
                return false;
            if (method.IsRuntimeSpecialName || method.IsRuntime)
                return false;
            if (method.IsConstructor)
                return false;
            if (method.IsVirtual || method.IsAbstract || method.HasOverrides) //Not sure if both ruins
                return false;
            if (realTypeName.IndexOf("<>__AnonType", StringComparison.InvariantCulture) == 0) //Anonimous method make it hurt
                return false;
            if (method.DeclaringType.HasGenericParameters) //Generics too
                return false;
            if (method.DeclaringType.IsForwarder)
                return false;
            if (lockedMethods.Any(m => m == method.Name))
                return false;
            if (method.CustomAttributes.Any(a => a.TypeFullName.EndsWith("DoNotRename", StringComparison.InvariantCulture)))
                return false;
            //if (IsMethodContainsReflection(method))
            //    return false;
            return true;
        }

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

private static string ScrubSecret(string message, string token, string mask, bool replacedertOnDetection, bool maskToken=false)
        {
            int startIndex = -1;

            do
            {
                startIndex = message.IndexOf(token, (startIndex < 0) ? 0 : startIndex, StringComparison.OrdinalIgnoreCase);
                if (startIndex < 0)
                {
                    // Common case, there is not a preplacedword.
                    break;
                }

                //Explicitly check for original preplacedword mask so code that uses the orignal doesn't replacedert
                if (!maskToken && (
                    message.IndexOf(token + mask, StringComparison.OrdinalIgnoreCase) == startIndex
                    || (message.IndexOf(token + PreplacedwordMask, StringComparison.OrdinalIgnoreCase) == startIndex)))
                {
                    // The preplacedword is already masked, move past this string.
                    startIndex += token.Length + mask.Length;
                    continue;
                }

                // At this point we detected a preplacedword that is not masked, remove it!
                try
                {
                    if (!maskToken)
                    {
                        startIndex += token.Length;
                    }
                    // Find the end of the preplacedword.
                    int endIndex = message.Length - 1;

                    if (message[startIndex] == '"' || message[startIndex] == '\'')
                    {
                        // The preplacedword is wrapped in quotes.  The end of the string will be the next unpaired quote. 
                        // Unless the message itself wrapped the connection string in quotes, in which case we may mask out the rest of the message.  Better to be safe than leak the connection string.
                        // Intentionally going to "i < message.Length - 1".  If the quote isn't the second to last character, it is the last character, and we delete to the end of the string anyway.
                        for (int i = startIndex + 1; i < message.Length - 1; i++)
                        {
                            if (message[startIndex] == message[i])
                            {
                                if (message[startIndex] == message[i + 1])
                                {
                                    // we found a pair of quotes. Skip over the pair and continue.
                                    i++;
                                    continue;
                                }
                                else
                                {
                                    // this is a single quote, and the end of the preplacedword.
                                    endIndex = i;
                                    break;
                                }
                            }
                        }
                    }
                    else
                    {
                        // The preplacedword is not wrapped in quotes.
                        // The end is any whitespace, semi-colon, single, or double quote character.
                        for (int i = startIndex + 1; i < message.Length; i++)
                        {
                            if (Char.IsWhiteSpace(message[i]) || ((IList<Char>)s_validPreplacedwordEnding).Contains(message[i]))
                            {
                                endIndex = i - 1;
                                break;
                            }
                        }
                    }

                    message = message.Substring(0, startIndex) + mask + message.Substring(endIndex + 1);

                    // Bug 94478: We need to scrub the message before replacedert, otherwise we will fall into
                    // a recursive replacedert where the TeamFoundationServerException contains same message
                    if (replacedertOnDetection)
                    {
                        Debug.replacedert(false, String.Format(CultureInfo.InvariantCulture, "Message contains an unmasked secret. Message: {0}", message));
                    }

                    // Trace raw that we have scrubbed a message.
                    //FUTURE: We need a work item to add Tracing to the VSS Client replacedembly.
                    //TraceLevel traceLevel = replacedertOnDetection ? TraceLevel.Error : TraceLevel.Info;
                    //TeamFoundationTracingService.TraceRaw(99230, traceLevel, s_area, s_layer, "An unmasked preplacedword was detected in a message. MESSAGE: {0}. STACK TRACE: {1}", message, Environment.StackTrace);
                }
                catch (Exception /*exception*/)
                {
                    // With an exception here the message may still contain an unmasked preplacedword.
                    // We also do not want to interupt the current thread with this exception, because it may be constucting a message 
                    // for a different exception. Trace this exception and continue on using a generic exception message.
                    //TeamFoundationTracingService.TraceExceptionRaw(99231, s_area, s_layer, exception);
                }
                finally
                {
                    // Iterate to the next preplacedword (if it exists)
                    startIndex += mask.Length;
                }
            } while (startIndex < message.Length);

            return message;
        }

19 View Source File : SnowFlake.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

private static void GetMachineId()
        {
            // ReSharper disable once ConstantNullCoalescingCondition
            string hostName = Dns.GetHostName() ?? "XJXX-001";
            var idx = hostName.IndexOf("-", StringComparison.Ordinal) + 1;
            string machineId = hostName.Substring(idx, hostName.Length - idx);
            //_machineId = int.Parse(machineId);
            _machineId = int.TryParse(machineId, out var id) ? id : 1;
        }

19 View Source File : TemplateGenerator.cs
License : MIT License
Project Creator : 2881099

public void Build(IDbFirst dbfirst, string templateDirectory, string outputDirectory, params string[] database) {
			if (dbfirst == null) throw new ArgumentException("dbfirst 参数不能为 null");
			if (string.IsNullOrEmpty(templateDirectory) || Directory.Exists(templateDirectory) == false) throw new ArgumentException("templateDirectory 目录不存在");
			if (string.IsNullOrEmpty(templateDirectory)) throw new ArgumentException("outputDirectory 不能为 null");
			if (database == null || database.Any() == false) throw new ArgumentException("database 参数不能为空");
			if (Directory.Exists(outputDirectory) == false) Directory.CreateDirectory(outputDirectory);
			templateDirectory = new DirectoryInfo(templateDirectory).FullName;
			outputDirectory = new DirectoryInfo(outputDirectory).FullName;
			if (templateDirectory.IndexOf(outputDirectory, StringComparison.CurrentCultureIgnoreCase) != -1) throw new ArgumentException("outputDirectory 目录不能设置在 templateDirectory 目录内");
			var tables = dbfirst.GetTablesByDatabase(database);
			var tpl = new TemplateEngin(templateDirectory, "FreeSql", "FreeSql.DatabaseModel");
			BuildEachDirectory(templateDirectory, outputDirectory, tpl, dbfirst, tables);
			tpl.Dispose();
		}

19 View Source File : StringHelper.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public static void AppendUsing(this StringBuilder code, IEnumerable<string> nameSpaces)
        {
            if (nameSpaces == null)
                return;
            var spaces = nameSpaces as string[] ?? nameSpaces.ToArray();
            foreach (var nameSpace in spaces.Where(p => p != null && p.IndexOf("System", StringComparison.Ordinal) == 0).Distinct().OrderBy(p => p))
            {
                code.AppendFormat(@"using {0};", nameSpace);
                code.AppendLine();
            }
            foreach (var nameSpace in spaces.Where(p => p != null && p.IndexOf("System", StringComparison.Ordinal) != 0).Distinct().OrderBy(p => p))
            {
                code.AppendFormat(@"using {0};", nameSpace);
                code.AppendLine();
            }
        }

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

public async Task StartContainersAsync(IExecutionContext executionContext, object data)
        {
            Trace.Entering();
            if (!Constants.Runner.Platform.Equals(Constants.OSPlatform.Linux))
            {
                throw new NotSupportedException("Container operations are only supported on Linux runners");
            }
            ArgUtil.NotNull(executionContext, nameof(executionContext));
            List<ContainerInfo> containers = data as List<ContainerInfo>;
            ArgUtil.NotNull(containers, nameof(containers));

            var postJobStep = new JobExtensionRunner(runAsync: this.StopContainersAsync,
                                                condition: $"{PipelineTemplateConstants.Always}()",
                                                displayName: "Stop containers",
                                                data: data);

            executionContext.Debug($"Register post job cleanup for stopping/deleting containers.");
            executionContext.RegisterPostJobStep(postJobStep);

            // Check whether we are inside a container.
            // Our container feature requires to map working directory from host to the container.
            // If we are already inside a container, we will not able to find out the real working direcotry path on the host.
#if OS_WINDOWS
            // service CExecSvc is Container Execution Agent.
            ServiceController[] scServices = ServiceController.GetServices();
            if (scServices.Any(x => String.Equals(x.ServiceName, "cexecsvc", StringComparison.OrdinalIgnoreCase) && x.Status == ServiceControllerStatus.Running))
            {
                throw new NotSupportedException("Container feature is not supported when runner is already running inside container.");
            }
#else
            var initProcessCgroup = File.ReadLines("/proc/1/cgroup");
            if (initProcessCgroup.Any(x => x.IndexOf(":/docker/", StringComparison.OrdinalIgnoreCase) >= 0))
            {
                throw new NotSupportedException("Container feature is not supported when runner is already running inside container.");
            }
#endif

#if OS_WINDOWS
            // Check OS version (Windows server 1803 is required)
            object windowsInstallationType = Registry.GetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion", "InstallationType", defaultValue: null);
            ArgUtil.NotNull(windowsInstallationType, nameof(windowsInstallationType));
            object windowsReleaseId = Registry.GetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion", "ReleaseId", defaultValue: null);
            ArgUtil.NotNull(windowsReleaseId, nameof(windowsReleaseId));
            executionContext.Debug($"Current Windows version: '{windowsReleaseId} ({windowsInstallationType})'");

            if (int.TryParse(windowsReleaseId.ToString(), out int releaseId))
            {
                if (!windowsInstallationType.ToString().StartsWith("Server", StringComparison.OrdinalIgnoreCase) || releaseId < 1803)
                {
                    throw new NotSupportedException("Container feature requires Windows Server 1803 or higher.");
                }
            }
            else
            {
                throw new ArgumentOutOfRangeException(@"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ReleaseId");
            }
#endif

            // Check docker client/server version
            executionContext.Output("##[group]Checking docker version");
            DockerVersion dockerVersion = await _dockerManager.DockerVersion(executionContext);
            executionContext.Output("##[endgroup]");

            ArgUtil.NotNull(dockerVersion.ServerVersion, nameof(dockerVersion.ServerVersion));
            ArgUtil.NotNull(dockerVersion.ClientVersion, nameof(dockerVersion.ClientVersion));

#if OS_WINDOWS
            Version requiredDockerEngineAPIVersion = new Version(1, 30);  // Docker-EE version 17.6
#else
            Version requiredDockerEngineAPIVersion = new Version(1, 35); // Docker-CE version 17.12
#endif

            if (dockerVersion.ServerVersion < requiredDockerEngineAPIVersion)
            {
                throw new NotSupportedException($"Min required docker engine API server version is '{requiredDockerEngineAPIVersion}', your docker ('{_dockerManager.DockerPath}') server version is '{dockerVersion.ServerVersion}'");
            }
            if (dockerVersion.ClientVersion < requiredDockerEngineAPIVersion)
            {
                throw new NotSupportedException($"Min required docker engine API client version is '{requiredDockerEngineAPIVersion}', your docker ('{_dockerManager.DockerPath}') client version is '{dockerVersion.ClientVersion}'");
            }

            // Clean up containers left by previous runs
            executionContext.Output("##[group]Clean up resources from previous jobs");
            var staleContainers = await _dockerManager.DockerPS(executionContext, $"--all --quiet --no-trunc --filter \"label={_dockerManager.DockerInstanceLabel}\"");
            foreach (var staleContainer in staleContainers)
            {
                int containerRemoveExitCode = await _dockerManager.DockerRemove(executionContext, staleContainer);
                if (containerRemoveExitCode != 0)
                {
                    executionContext.Warning($"Delete stale containers failed, docker rm fail with exit code {containerRemoveExitCode} for container {staleContainer}");
                }
            }

            int networkPruneExitCode = await _dockerManager.DockerNetworkPrune(executionContext);
            if (networkPruneExitCode != 0)
            {
                executionContext.Warning($"Delete stale container networks failed, docker network prune fail with exit code {networkPruneExitCode}");
            }
            executionContext.Output("##[endgroup]");

            // Create local docker network for this job to avoid port conflict when multiple runners run on same machine.
            // All containers within a job join the same network
            executionContext.Output("##[group]Create local container network");
            var containerNetwork = $"github_network_{Guid.NewGuid().ToString("N")}";
            await CreateContainerNetworkAsync(executionContext, containerNetwork);
            executionContext.JobContext.Container["network"] = new StringContextData(containerNetwork);
            executionContext.Output("##[endgroup]");

            foreach (var container in containers)
            {
                container.ContainerNetwork = containerNetwork;
                await StartContainerAsync(executionContext, container);
            }

            executionContext.Output("##[group]Waiting for all services to be ready");
            foreach (var container in containers.Where(c => !c.IsJobContainer))
            {
                await ContainerHealthcheck(executionContext, container);
            }
            executionContext.Output("##[endgroup]");
        }

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

private static bool IsTransientNetworkExceptionHelper(
            Exception ex,
            VssHttpRetryOptions options,
            out HttpStatusCode? httpStatusCode,
            out WebExceptionStatus? webExceptionStatus,
            out SocketError? socketErrorCode,
            out WinHttpErrorCode? winHttpErrorCode,
            out CurlErrorCode? curlErrorCode)
        {
            ArgumentUtility.CheckForNull(ex, "ex");

            httpStatusCode = null;
            webExceptionStatus = null;
            socketErrorCode = null;
            winHttpErrorCode = null;
            curlErrorCode = null;

            if (ex is WebException)
            {
                WebException webEx = (WebException)ex;

                if (webEx.Response != null && webEx.Response is HttpWebResponse)
                {
                    var httpResponse = (HttpWebResponse)webEx.Response;
                    httpStatusCode = httpResponse.StatusCode;

                    // If the options include this status code as a retryable error then we report the exception
                    // as transient to the caller
                    if (options.RetryableStatusCodes.Contains(httpResponse.StatusCode))
                    {
                        return true;
                    }
                }

                webExceptionStatus = webEx.Status;

                if (webEx.Status == WebExceptionStatus.ConnectFailure ||
                    webEx.Status == WebExceptionStatus.ConnectionClosed ||
                    webEx.Status == WebExceptionStatus.KeepAliveFailure ||
                    webEx.Status == WebExceptionStatus.NameResolutionFailure ||
                    webEx.Status == WebExceptionStatus.ReceiveFailure ||
                    webEx.Status == WebExceptionStatus.SendFailure ||
                    webEx.Status == WebExceptionStatus.Timeout)
                {
                    return true;
                }
            }
            else if (ex is SocketException)
            {
                SocketException sockEx = (SocketException)ex;

                socketErrorCode = sockEx.SocketErrorCode;

                if (sockEx.SocketErrorCode == SocketError.Interrupted ||
                    sockEx.SocketErrorCode == SocketError.NetworkDown ||
                    sockEx.SocketErrorCode == SocketError.NetworkUnreachable ||
                    sockEx.SocketErrorCode == SocketError.NetworkReset ||
                    sockEx.SocketErrorCode == SocketError.ConnectionAborted ||
                    sockEx.SocketErrorCode == SocketError.ConnectionReset ||
                    sockEx.SocketErrorCode == SocketError.TimedOut ||
                    sockEx.SocketErrorCode == SocketError.HostDown ||
                    sockEx.SocketErrorCode == SocketError.HostUnreachable ||
                    sockEx.SocketErrorCode == SocketError.TryAgain)
                {
                    return true;
                }
            }
            else if (ex is Win32Exception) // WinHttpException when use WinHttp (dotnet core)
            {
                Win32Exception winHttpEx = (Win32Exception)ex;

                Int32 errorCode = winHttpEx.NativeErrorCode;
                if (errorCode > (Int32)WinHttpErrorCode.WINHTTP_ERROR_BASE &&
                    errorCode <= (Int32)WinHttpErrorCode.WINHTTP_ERROR_LAST)
                {
                    winHttpErrorCode = (WinHttpErrorCode)errorCode;

                    if (winHttpErrorCode == WinHttpErrorCode.ERROR_WINHTTP_CANNOT_CONNECT ||
                        winHttpErrorCode == WinHttpErrorCode.ERROR_WINHTTP_CONNECTION_ERROR ||
                        winHttpErrorCode == WinHttpErrorCode.ERROR_WINHTTP_INTERNAL_ERROR ||
                        winHttpErrorCode == WinHttpErrorCode.ERROR_WINHTTP_NAME_NOT_RESOLVED ||
                        winHttpErrorCode == WinHttpErrorCode.ERROR_WINHTTP_TIMEOUT)
                    {
                        return true;
                    }
                }
            }
            else if (ex is IOException)
            {
                if (null != ex.InnerException &&
                    ex.InnerException is Win32Exception)
                {
                    String stackTrace = ex.StackTrace;

                    if (null != stackTrace &&
                        stackTrace.IndexOf("System.Net.Security._SslStream.StartWriting(", StringComparison.Ordinal) >= 0)
                    {
                        // HACK: There is an underlying HRESULT code for this error which is not set on the exception which 
                        //       bubbles from the underlying stack. The top of the stack trace will be in the _SslStream clreplaced
                        //       and will have an exception chain of HttpRequestException -> IOException -> Win32Exception.

                        // Check for SEC_E_CONTEXT_EXPIRED as this occurs at random in the underlying stack. Retrying the
                        // request should get a new connection and work correctly, so we ignore this particular error.

                        return true;
                    }
                }
            }
            else if (ex.GetType().Name == "CurlException") // CurlException when use libcurl (dotnet core)
            {
                // Valid curl error code should in range (0, 93]
                if (ex.HResult > 0 && ex.HResult < 94)
                {
                    curlErrorCode = (CurlErrorCode)ex.HResult;
                    if (curlErrorCode == CurlErrorCode.CURLE_COULDNT_RESOLVE_PROXY ||
                        curlErrorCode == CurlErrorCode.CURLE_COULDNT_RESOLVE_HOST ||
                        curlErrorCode == CurlErrorCode.CURLE_COULDNT_CONNECT ||
                        curlErrorCode == CurlErrorCode.CURLE_HTTP2 ||
                        curlErrorCode == CurlErrorCode.CURLE_PARTIAL_FILE ||
                        curlErrorCode == CurlErrorCode.CURLE_WRITE_ERROR ||
                        curlErrorCode == CurlErrorCode.CURLE_UPLOAD_FAILED ||
                        curlErrorCode == CurlErrorCode.CURLE_READ_ERROR ||
                        curlErrorCode == CurlErrorCode.CURLE_OPERATION_TIMEDOUT ||
                        curlErrorCode == CurlErrorCode.CURLE_INTERFACE_FAILED ||
                        curlErrorCode == CurlErrorCode.CURLE_GOT_NOTHING ||
                        curlErrorCode == CurlErrorCode.CURLE_SEND_ERROR ||
                        curlErrorCode == CurlErrorCode.CURLE_RECV_ERROR)
                    {
                        return true;
                    }
                }
            }

            return false;
        }

19 View Source File : Program.cs
License : GNU Affero General Public License v3.0
Project Creator : 3CORESec

public static Dictionary<string, dynamic> DeserializeYamlFile(string ruleFilePath, Options o)
        {
            var contents = File.ReadAllText(ruleFilePath);
            if (!contents.Contains("tags"))
            {
                Console.WriteLine($"Ignoring rule {ruleFilePath} (no tags)");
                return null;
            }
            if (o.Warning)
                contents = contents.Replace(Environment.NewLine + Environment.NewLine,
                        Environment.NewLine)
                    .Remove(0, contents.IndexOf("tags", StringComparison.Ordinal));
            if (contents.Contains("---"))
                contents = contents.Remove(contents.IndexOf("---", StringComparison.Ordinal));
            var deserializer = new YamlDotNet.Serialization.Deserializer();
            var dict = deserializer.Deserialize<Dictionary<string, dynamic>>(contents);
            return dict;
        }

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

private static string GetPrefixFromTestFilePath(string testFilePath)
		{
			string folderFullPath = testFilePath.IsNullOrWhiteSpace()
				? null
				: Path.GetDirectoryName(testFilePath);

			if (folderFullPath.IsNullOrWhiteSpace())
				return DefaultPrefix;

			// ReSharper disable once PossibleNullReferenceException
			int startingIndex = folderFullPath.IndexOf(TestsRoot, StringComparison.OrdinalIgnoreCase);

			if (startingIndex < 0)
				return DefaultPrefix;

			string prefix = folderFullPath.Substring(startingIndex);
			string preparedPrefix = TransformFileNameToreplacedemblyResourceID(prefix);
			return !preparedPrefix.IsNullOrWhiteSpace()
					? $"{preparedPrefix}.{SourcesPrefix}"
					: DefaultPrefix;
		}

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

public static void ReadIndexFromFile()
        {
            var location = replacedembly.GetExecutingreplacedembly().Location;

            var index = location.IndexOf(@"\bin", StringComparison.InvariantCulture);

            var filePath = location.Substring(0, index) + InvertedIndexRelativePath;

            string[] lines = File.ReadAllLines(filePath);

            _invertedIndex.Clear();
            foreach (var line in lines)
            {
                var splittedLine = line.Split('|');

                string term = splittedLine[0];
                var postings = splittedLine[1].Split(';');
                var termFrequencies = splittedLine[2].Split(',');
                var invertedDocFrequency = double.Parse(splittedLine[3]);

                var termInfos = new List<TermInfo>();

                for (int i = 0; i < postings.Length; i++)
                {
                    var posting = postings[i];
                    var tf = double.Parse(termFrequencies[i]);

                    var post = posting.Split(':');
                    var termEntries = post[1].Split(',').Select(ushort.Parse).ToArray();
                    
                    termInfos.Add(new TermInfo(new Guid(post[0]), termEntries, (float) tf));
                }

                _invertedIndex[term] = new Posting(termInfos) {InvertedDoreplacedentFrequency = invertedDocFrequency};
            }
        }

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

private string RemoveDuplicates(string input)
		{
			if (string.IsNullOrEmpty(input))
			{
				return input;
			}

			var uniqueWords = new List<string>();
			var duplicateWords = new List<string>();

			foreach (var word in input.Split(';', ','))
			{
				var trimmedWord = word.Trim();

				if (string.IsNullOrEmpty(trimmedWord))
				{
					continue;
				}

				if (uniqueWords.Contains(trimmedWord))
				{
					duplicateWords.Add(trimmedWord);
					continue;
				}

				uniqueWords.Add(trimmedWord);
			}

			foreach (var duplicateWord in duplicateWords)
			{
				var startIndex = input.IndexOf(duplicateWord, StringComparison.InvariantCulture) + duplicateWord.Length;
				var secondDuplicateIndex = input.IndexOf(duplicateWord, startIndex, StringComparison.InvariantCulture);
				input = input.Remove(secondDuplicateIndex, duplicateWord.Length);
			}

			return input;
		}

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

private static string EnsureValidFileName(string fileName)
		{
			return fileName.IndexOf("\\", StringComparison.Ordinal) >= 0 ? fileName.Substring(fileName.LastIndexOf("\\", StringComparison.Ordinal) + 1) : fileName;
		}

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

public static HouseType GetHouseType(string clreplacedname)
        {
            if (clreplacedname.IndexOf("apartment", StringComparison.OrdinalIgnoreCase) != -1)
                return HouseType.Apartment;
            else if (clreplacedname.IndexOf("cottage", StringComparison.OrdinalIgnoreCase) != -1)
                return HouseType.Cottage;
            else if (clreplacedname.IndexOf("villa", StringComparison.OrdinalIgnoreCase) != -1)
                return HouseType.Villa;
            else if (clreplacedname.IndexOf("mansion", StringComparison.OrdinalIgnoreCase) != -1)
                return HouseType.Mansion;
            else
                return HouseType.Undef;
        }

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

public static EnreplacedyReference GetNoteContact(string subject)
		{
			if (string.IsNullOrWhiteSpace(subject))
			{
				return null;
			}

			// String format is "Note created on {0} by {1} [{2}:{3}]"

			var startIndex = subject.IndexOf("by ", StringComparison.InvariantCulture);

			if (startIndex == -1)
			{
				return null;
			}

			try
			{
				var contactString = subject.Substring(startIndex);

				var name = contactString.Substring(3, contactString.IndexOf("[", StringComparison.InvariantCulture) - 4);

				var pos1 = contactString.IndexOf(":", StringComparison.InvariantCulture) + 1;
				var pos2 = contactString.IndexOf("]", StringComparison.InvariantCulture);

				var contactid = contactString.Substring(pos1, pos2 - pos1);

				Guid contactGuid;

				if (Guid.TryParse(contactid, out contactGuid))
				{
					return new EnreplacedyReference("contact", contactGuid) { Name = name };
				}
			}
			catch (Exception)
			{
                ADXTrace.Instance.TraceError(TraceCategory.Application, string.Format("Failed to extract contact EnreplacedyReference from note subject. {0}", subject));
            }

			return null;
		}

19 View Source File : BTCChinaAPI.cs
License : MIT License
Project Creator : aabiryukov

private string DoMethod(NameValueCollection jParams)
	    {
		    const int RequestTimeoutMilliseconds = 2*1000; // 2 sec 

		    string tempResult = "";

		    try
		    {
			    lock (m_tonceLock)
			    {
				    //get tonce
				    TimeSpan timeSpan = DateTime.UtcNow - genesis;
				    long milliSeconds = Convert.ToInt64(timeSpan.TotalMilliseconds*1000);
				    jParams[pTonce] = Convert.ToString(milliSeconds, CultureInfo.InvariantCulture);
				    //mock json request id
				    jParams[pId] = jsonRequestID.Next().ToString(CultureInfo.InvariantCulture);
				    //build http head
				    string paramsHash = GetHMACSHA1Hash(jParams);
				    string base64String = Convert.ToBase64String(Encoding.ASCII.GetBytes(accessKey + ':' + paramsHash));
				    string postData = "{\"method\": \"" + jParams[pMethod] + "\", \"params\": [" + jParams[pParams] + "], \"id\": " +
				                      jParams[pId] + "}";

				    //get webrequest,respawn new object per call for multiple connections
				    var webRequest = (HttpWebRequest) WebRequest.Create(url);
				    webRequest.Timeout = RequestTimeoutMilliseconds;

				    var bytes = Encoding.ASCII.GetBytes(postData);

				    webRequest.Method = jParams[pRequestMethod];
				    webRequest.ContentType = "application/json-rpc";
				    webRequest.ContentLength = bytes.Length;
				    webRequest.Headers["Authorization"] = "Basic " + base64String;
				    webRequest.Headers["Json-Rpc-Tonce"] = jParams[pTonce];

				    // Send the json authentication post request
				    using (var dataStream = webRequest.GetRequestStream())
				    {
					    dataStream.Write(bytes, 0, bytes.Length);
				    }

				    // Get authentication response
				    using (var response = webRequest.GetResponse())
				    {
					    using (var stream = response.GetResponseStream())
					    {
// ReSharper disable once replacedignNullToNotNullAttribute
						    using (var reader = new StreamReader(stream))
						    {
							    tempResult = reader.ReadToEnd();
						    }
					    }
				    }
			    }
		    }
		    catch (WebException ex)
		    {
			    throw new BTCChinaException(jParams[pMethod], jParams[pId], ex.Message, ex);
		    }

		    //there are two kinds of API response, result or error.
		    if (tempResult.IndexOf("result", StringComparison.Ordinal) < 0)
		    {
			    throw new BTCChinaException(jParams[pMethod], jParams[pId], "API error:\n" + tempResult);
		    }

		    //compare response id with request id and remove it from result
		    try
		    {
			    int cutoff = tempResult.LastIndexOf(':') + 2;//"id":"1"} so (last index of ':')+2=length of cutoff=start of id-string
			    string idString = tempResult.Substring(cutoff, tempResult.Length - cutoff - 2);//2=last "}
			    if (idString != jParams[pId])
			    {
				    throw new BTCChinaException(jParams[pMethod], jParams[pId], "JSON-request id is not equal with JSON-response id.");
			    }
			    else
			    {
				    //remove json request id from response json string
				    int fromComma = tempResult.LastIndexOf(',');
				    int toLastBrace = tempResult.Length - 1;
				    tempResult = tempResult.Remove(fromComma, toLastBrace - fromComma);
			    }
		    }
		    catch (ArgumentOutOfRangeException ex)
		    {
			    throw new BTCChinaException(jParams[pMethod], jParams[pId], "Argument out of range in parsing JSON response id:" + ex.Message, ex);
		    }

		    return tempResult;
	    }

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

private static string GetOrganizationName(AuthenticationProviderType authType, Uri uri)
		{
			if (authType == AuthenticationProviderType.LiveId)
			{
				// take the first sub-domain of the host

				return GetOrganizationNameFromHost(uri);
			}

			if ((authType == AuthenticationProviderType.Federation || authType == AuthenticationProviderType.OnlineFederation)
				&& uri.AbsolutePath.IndexOf("/xrmservices/2011/organization.svc", StringComparison.OrdinalIgnoreCase) == 0)
			{
				return GetOrganizationNameFromHost(uri);
			}

			if (uri.Segments.Length < 2) return null;

			var orgName = uri.Segments[1];

			return orgName.TrimEnd('/');
		}

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

public static String ClreplacedifyScript(string s)
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder(s);
            sb.Insert(s.IndexOf(@"public static", StringComparison.InvariantCulture), @"public clreplaced A{");
            sb.Append(@"}");
            return sb.ToString();
        }

19 View Source File : InternalServerErrorProcessor.cs
License : Apache License 2.0
Project Creator : adrianiftode

private static void AspNetCore30(StringBuilder contentBuilder, string content)
        {
            const string headersText = "HEADERS";
            var headersIndex = content.IndexOf(headersText, StringComparison.Ordinal);
            if (headersIndex >= 0)
            {
                var exceptionDetails = content.Substring(0, headersIndex).Trim();
                contentBuilder.Append(exceptionDetails);
            }
        }

19 View Source File : Dumper.cs
License : MIT License
Project Creator : 13xforever

private List<string> EnumeratePhysicalDrivesWindows()
        {
            var physicalDrives = new List<string>();
#if !NATIVE
            try
            {
                using var mgmtObjSearcher = new ManagementObjectSearcher("SELECT * FROM Win32_PhysicalMedia");
                var drives = mgmtObjSearcher.Get();
                foreach (var drive in drives)
                {
                    var tag = drive.Properties["Tag"].Value as string;
                    if (tag?.IndexOf("CDROM", StringComparison.InvariantCultureIgnoreCase) > -1)
                        physicalDrives.Add(tag);
                }
            }
            catch (Exception e)
            {
                Log.Error(e, "Failed to enumerate physical media drives using WMI");
                for (var i = 0; i < 32; i++)
                    physicalDrives.Add([email protected]"\\.\CDROM{i}");
            }
#else
            for (var i = 0; i < 32; i++)
                physicalDrives.Add([email protected]"\\.\CDROM{i}");
#endif
            return physicalDrives;
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : AElfProject

private static replacedembly OnreplacedemblyResolve(object sender, ResolveEventArgs args)
        {
            var folderPath = Path.GetDirectoryName(replacedembly.GetExecutingreplacedembly().Location);
            var replacedemblyPath = Path.Combine(folderPath, new replacedemblyName(args.Name).Name + ".dll");
            if (!File.Exists(replacedemblyPath))
            {
                if (replacedemblyPath.Contains("Contract"))
                {
                    replacedemblyPath = replacedemblyPath.Substring(0,
                        replacedemblyPath.IndexOf("bin", StringComparison.Ordinal) - 1);
                    replacedemblyPath = Path.Combine(replacedemblyPath, "contracts", new replacedemblyName(args.Name).Name + ".dll");
                }
                else
                    return null;
            }

            var replacedembly = replacedembly.LoadFrom(replacedemblyPath);
            return replacedembly;
        }

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

public void ProcessCommand(IExecutionContext context, string filePath, ContainerInfo container)
        {
            try
            {
                var text = File.ReadAllText(filePath) ?? string.Empty;
                var index = 0;
                var line = ReadLine(text, ref index);
                while (line != null)
                {
                    if (!string.IsNullOrEmpty(line))
                    {
                        var equalsIndex = line.IndexOf("=", StringComparison.Ordinal);
                        var heredocIndex = line.IndexOf("<<", StringComparison.Ordinal);

                        // Normal style NAME=VALUE
                        if (equalsIndex >= 0 && (heredocIndex < 0 || equalsIndex < heredocIndex))
                        {
                            var split = line.Split(new[] { '=' }, 2, StringSplitOptions.None);
                            if (string.IsNullOrEmpty(line))
                            {
                                throw new Exception($"Invalid environment variable format '{line}'. Environment variable name must not be empty");
                            }
                            SetEnvironmentVariable(context, split[0], split[1]);
                        }
                        // Heredoc style NAME<<EOF
                        else if (heredocIndex >= 0 && (equalsIndex < 0 || heredocIndex < equalsIndex))
                        {
                            var split = line.Split(new[] { "<<" }, 2, StringSplitOptions.None);
                            if (string.IsNullOrEmpty(split[0]) || string.IsNullOrEmpty(split[1]))
                            {
                                throw new Exception($"Invalid environment variable format '{line}'. Environment variable name must not be empty and delimiter must not be empty");
                            }
                            var name = split[0];
                            var delimiter = split[1];
                            var startIndex = index; // Start index of the value (inclusive)
                            var endIndex = index;   // End index of the value (exclusive)
                            var tempLine = ReadLine(text, ref index, out var newline);
                            while (!string.Equals(tempLine, delimiter, StringComparison.Ordinal))
                            {
                                if (tempLine == null)
                                {
                                    throw new Exception($"Invalid environment variable value. Matching delimiter not found '{delimiter}'");
                                }
                                endIndex = index - newline.Length;
                                tempLine = ReadLine(text, ref index, out newline);
                            }

                            var value = endIndex > startIndex ? text.Substring(startIndex, endIndex - startIndex) : string.Empty;
                            SetEnvironmentVariable(context, name, value);
                        }
                        else
                        {
                            throw new Exception($"Invalid environment variable format '{line}'");
                        }
                    }

                    line = ReadLine(text, ref index);
                }
            }
            catch (DirectoryNotFoundException)
            {
                context.Debug($"Environment variables file does not exist '{filePath}'");
            }
            catch (FileNotFoundException)
            {
                context.Debug($"Environment variables file does not exist '{filePath}'");
            }
        }

19 View Source File : Renamer.cs
License : GNU General Public License v3.0
Project Creator : Agasper

bool CanRenameField(string realTypeName, FieldDef field)
        {
            if (!RenameFields)
                return false;
            if (realTypeName.IndexOf("<>__AnonType", StringComparison.InvariantCulture) == 0) //Anonimous method make it hurt
                return false;
            if (field.IsRuntimeSpecialName || field.IsSpecialName)
                return false;
            if (field.DeclaringType.HasGenericParameters)
                return false;
            if (field.DeclaringType.IsSerializable && !field.IsNotSerialized)
                return false;
            if (field.IsPinvokeImpl)
                return false;
            if (field.IsLiteral && field.DeclaringType.IsEnum)
                return false;
            if (field.CustomAttributes.Any(a => a.TypeFullName.EndsWith("DoNotRename", StringComparison.InvariantCulture)))
                return false;
            return true;
        }

19 View Source File : TextRangeProvider.cs
License : MIT License
Project Creator : Abdesol

public ITextRangeProvider FindText(string text, bool backward, bool ignoreCase)
		{
			Log("{0}.FindText({1}, {2}, {3})", ID, text, backward, ignoreCase);
			string segmentText = doc.GetText(segment);
			var comparison = ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal;
			int pos = backward ? segmentText.LastIndexOf(text, comparison) : segmentText.IndexOf(text, comparison);
			if (pos >= 0) {
				return new TextRangeProvider(textArea, doc, segment.Offset + pos, text.Length);
			}
			return null;
		}

19 View Source File : IOHelper.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

private static DiskInfo WindowsFolderDiskInfo(string path)
        {
            var info = new DiskInfo();

            var str_HardDiskName = path[0] + ":\\";

            var drive = System.IO.DriveInfo.GetDrives().FirstOrDefault(p=> path.IndexOf(p.Name,StringComparison.OrdinalIgnoreCase)==0);
            if(drive != null)
            {
                info.TotalSize = drive.TotalSize / (1024 * 1024);
                info.AvailableSize = drive.AvailableFreeSpace / (1024 * 1024);
                info.UsedSize = info.TotalSize - info.AvailableSize;
                info.Use = info.UsedSize / info.TotalSize;
            }
            return info;
        }

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

public bool Contains(string main, string pattern)
        {
            ArgumentUtility.CheckForNull(main, "main");
            ArgumentUtility.CheckForNull(pattern, "pattern");

            return main.IndexOf(pattern, m_stringComparison) >= 0;
        }

19 View Source File : XmlMember.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public static XmlMember Find(Type type, string sub, string subType = "P")
        {
            if (type == typeof(object) || type.Namespace.IndexOf("System", StringComparison.Ordinal) == 0)
                return null;
            if (!replacedemblies.Contains(type.replacedembly))
                Load(type.replacedembly);
            var fn = type.FullName.Split('[')[0];
            var name = $"{fn}.{sub}";
            var re = HelpXml.FirstOrDefault(p => /*p.Type == subType &&*/ p.Name == name);
            if (re == null && replacedemblies.Contains(type.replacedembly))
            {
                return Find(type.BaseType, sub, subType);
            }
            return re;
        }

19 View Source File : CICPSerializer.cs
License : MIT License
Project Creator : 0xC0000054

private static ushort GetPropertyValue(string haystack, string propertyName)
        {
            string needle = propertyName + "=\"";

            int valueStartIndex = haystack.IndexOf(needle, StringComparison.Ordinal) + needle.Length;
            int valueEndIndex = haystack.IndexOf('"', valueStartIndex);

            string propertyValue = haystack.Substring(valueStartIndex, valueEndIndex - valueStartIndex);

            return ushort.Parse(propertyValue, CultureInfo.InvariantCulture);
        }

19 View Source File : IOHelper.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public static List<string> GetAllFiles(string path, string ext)
        {
            var fs = new List<string>();
            if (ext != null && ext.IndexOf("*", StringComparison.Ordinal) < 0 && ext.IndexOf("?", StringComparison.Ordinal) < 0)
            {
                ext = $"*.{ext}";
            }
            GetAllFiles(fs, path, ext);
            return fs.Distinct().ToList();
        }

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

protected string NormalizePath(string path, bool allowRootPath = false)
            {
                if (string.IsNullOrEmpty(path) || path[0] != PathSeparator || path.IndexOf(m_emptyPathSegment, StringComparison.Ordinal) >= 0 || (!allowRootPath && path.Length == 1))
                {
                    throw new ArgumentException(CommonResources.InvalidClientStoragePath(path, PathSeparator), "path");
                }
                if (path[path.Length - 1] == PathSeparator)
                {
                    path = path.Substring(0, path.Length - 1);
                }
                return path;
            }

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

private static string GetGltfNodeName(string jsonString)
        {
            jsonString = jsonString.Replace("\"name\"", string.Empty);
            jsonString = jsonString.Replace(": \"", string.Empty);
            jsonString = jsonString.Replace(":\"", string.Empty);
            jsonString = jsonString.Substring(0, jsonString.IndexOf("\"", StringComparison.Ordinal));
            return jsonString;
        }

19 View Source File : ImageGridMetadata.cs
License : MIT License
Project Creator : 0xC0000054

private static uint GetPropertyValue(string haystack, string propertyName)
        {
            string needle = propertyName + "=\"";

            int valueStartIndex = haystack.IndexOf(needle, StringComparison.Ordinal) + needle.Length;
            int valueEndIndex = haystack.IndexOf('"', valueStartIndex);

            string propertyValue = haystack.Substring(valueStartIndex, valueEndIndex - valueStartIndex);

            return uint.Parse(propertyValue, CultureInfo.InvariantCulture);
        }

19 View Source File : RawFileType.cs
License : MIT License
Project Creator : 0xC0000054

private static string RemoveCommentsAndWhiteSpace(string line)
        {
            int commentIndex = line.IndexOf(";", StringComparison.Ordinal);
            if (commentIndex >= 0)
            {
                return line.Substring(0, commentIndex).Trim();
            }
            else
            {
                return line.Trim();
            }
        }

19 View Source File : DynamicDNAConverterBehaviourEditor.cs
License : Apache License 2.0
Project Creator : A7ocin

public override void OnInspectorGUI()
		{
			serializedObject.Update();
			if (!initialized)
				this.Init();

			//Style for Tips
			var foldoutTipStyle = new GUIStyle(EditorStyles.foldout);
			foldoutTipStyle.fontStyle = FontStyle.Bold;
			//DISPLAY VALUE
			EditorGUILayout.PropertyField(serializedObject.FindProperty("DisplayValue"));
			//
			//=============DNA replacedET AND EDITOR============//
			SerializedProperty dnareplacedet = serializedObject.FindProperty("dnareplacedet");
			dnareplacedet.isExpanded = EditorGUILayout.Foldout(dnareplacedet.isExpanded, "Dynamic DNA", foldoutTipStyle);
			if (dnareplacedet.isExpanded)
			{
				GUIHelper.BeginVerticalPadded(3, new Color(0.75f, 0.875f, 1f, 0.3f));
				EditorGUI.indentLevel++;
				dnareplacedetInfoExpanded = EditorGUILayout.Foldout(dnareplacedetInfoExpanded, "INFO");
				if (dnareplacedetInfoExpanded)
					EditorGUILayout.HelpBox("The DynmicDNAreplacedet is the DNA this converter will apply to the skeleton. The DNA consists of names and replacedociated values. Often you display these names as 'sliders'. The values set by these sliders change an Avatar's body proportions by modifying its skeleton bones by the dna value, according to the 'DNA Converter Settings' you set in the 'DNA Converter Settings' section.", MessageType.Info);
				
				if(dnareplacedet.objectReferenceValue == null)
				{
					//show a tip that people need to create or replacedign a dna replacedet
					EditorGUILayout.HelpBox("Create or replacedign a DNA replacedet this converter will use", MessageType.Info);
				}
				EditorGUI.BeginChangeCheck();
				EditorGUILayout.PropertyField(dnareplacedet, new GUIContent("DNA replacedet", "A DynamireplacedADnareplacedet contains a list of names that define the 'DNA' that will be used to modify the Avatars Skeleton. Often displayed in the UI as 'sliders'"));
				if (EditorGUI.EndChangeCheck())
				{
					UpdateDnaNames();
					serializedObject.ApplyModifiedProperties();
					serializedObject.Update();//?
					if (minimalMode)
					{
						//force the Avatar to update its dna and dnaconverter dictionaries
						umaData.umaRecipe.ClearDna();
						umaData.umaRecipe.ClearDNAConverters();
					}
				}
				//If there is no dna replacedet replacedigned show a button to make one
				if (dnareplacedet.objectReferenceValue == null)
				{
					GUILayout.BeginHorizontal();
					GUILayout.Space(EditorGUI.indentLevel * 15);
					if (GUILayout.Button(new GUIContent("Create Dynamic DNA replacedet")))
					{
						var suggestedPath = replacedetDatabase.GetreplacedetPath(target);
						var suggestedName = target.name + "DNAreplacedet";
						var path = EditorUtility.SaveFilePanelInProject("Create a new Dynamic DNA replacedet", suggestedName, "replacedet", "some message", suggestedPath);
						if (path != "")
						{
							var newDnareplacedet = CustomreplacedetUtility.Createreplacedet<DynamireplacedADnareplacedet>(path, false);
							if (newDnareplacedet != null)
							{
								//set this replacedet as the used replacedet
								dnareplacedet.objectReferenceValue = newDnareplacedet;
								serializedObject.ApplyModifiedProperties();
								createDnareplacedetName = "";
							}
							UpdateDnaNames();
							if (minimalMode)
							{
								//force the Avatar to update its dna and dnaconverter dictionaries
								umaData.umaRecipe.ClearDna();
								umaData.umaRecipe.ClearDNAConverters();
							}
						}
					}
					GUILayout.EndHorizontal();
				}
				//Otherwise show the DNA replacedets Editor
				else
				{
					if (thisDUDA == null)
					{
						thisDUDA = Editor.CreateEditor((DynamireplacedADnareplacedet)dnareplacedet.objectReferenceValue, typeof(UMA.CharacterSystem.Editors.DynamireplacedADnareplacedetEditor));
					}
					else if (thisDUDA.target != (DynamireplacedADnareplacedet)dnareplacedet.objectReferenceValue)
					{
						thisDUDA = Editor.CreateEditor((DynamireplacedADnareplacedet)dnareplacedet.objectReferenceValue, typeof(UMA.CharacterSystem.Editors.DynamireplacedADnareplacedetEditor));
					}
					EditorGUI.BeginChangeCheck();
					thisDUDA.OnInspectorGUI();
					if (EditorGUI.EndChangeCheck())
					{
						UpdateDnaNames();
					}
				}
				EditorGUI.indentLevel--;
				GUIHelper.EndVerticalPadded(3);
			}
			serializedObject.ApplyModifiedProperties();
			//===========END DNA replacedET AND EDITOR============//
			//
			EditorGUILayout.Space();
			//
			//=============CONVERTER VALUES AND EDITOR=============//
			SerializedProperty hashList = serializedObject.FindProperty("hashList");
			SerializedProperty skeletonModifiers = serializedObject.FindProperty("skeletonModifiers");
			string converterTips = "";
			if (minimalMode)
			{
				converterTips = "Skeleton Modifiers control how the values of the DNA you set above are applied to the skeleton. So for example 'Upper Weight' affects the scale of the Spine, breast, belly and shoulder bones in different ways. The best way to edit these modifiers is to set the DNA slider you want to adjust in the game view, to either its minimum or maximum position. Then add or edit a skeleton modifier in the list below to use that value to modify the skeleton. The 'Value Modifiers' part of a Skeleton Modifier, takes the incoming value, modifies it by the settings and applies it to the bone. The Min and Max values are what that result will be 'clamped' to. Avoid changing the starting 'Value' as changes to this will persist even if the dna is not itself applied (if you want to do this use the starting pose below instead).";
			}
			else
			{
				converterTips = "Skeleton Modifiers control how the values of the DNA you set above are applied to the skeleton.  So for example 'Upper Weight' affects the scale of the Spine, breast, belly and shoulder bones in different ways. Add bones you wish to make available to modify in the 'BoneHashes' section. Then add or edit a skeleton modifier in the list below to use a given dna value to modify the skeleton. The 'Value Modifiers' part of a Skeleton Modifier, takes the incoming value, modifies it by the settings and applies it to the bone. The Min and Max values are what that result will be 'clamped' to. Avoid changing the starting 'Value' as changes to this will persist even if the dna is not itself applied (if you want to do this use the starting pose below instead).";
			}
			skeletonModifiersExpanded = EditorGUILayout.Foldout(skeletonModifiersExpanded, "DNA Converter Settings", foldoutTipStyle);
			if (skeletonModifiersExpanded)
			{
				GUIHelper.BeginVerticalPadded(3, new Color(0.75f, 0.875f, 1f, 0.3f));
				if (!minimalMode)
				{
					EditorGUILayout.HelpBox("TIP: Setting up your DNA Converter's Skeleton Modifiers is much easier if you use the 'DNA Converter Bahaviour Customizer' scene as it can automatically populate the list of available bones with the ones in the generated Avatar's skeleton.", MessageType.Info);
				}
				EditorGUI.indentLevel++;
				skeletonModifiersInfoExpanded = EditorGUILayout.Foldout(skeletonModifiersInfoExpanded, "INFO");
				if (skeletonModifiersInfoExpanded)
					EditorGUILayout.HelpBox(converterTips, MessageType.Info);
				if (!minimalMode)//in minimal mode we dont need to show these because we will have a skeleton that we can get the bonehash list from
				{
					int hashListCount = hashList.arraySize;
					hashList.isExpanded = EditorGUILayout.Foldout(hashList.isExpanded, new GUIContent("Bone Hashes", "These are the bones you have identified that the converter will work on. If you use the Dynamic DNA Customizer Scene these can be set automatically when you add Modifiers") );
					if (hashList.isExpanded)
					{
						EditorGUI.indentLevel++;
						extraBonesAddDelOptsExpanded = EditorGUILayout.Foldout(extraBonesAddDelOptsExpanded, "Add/Delete Bones Options");
						EditorGUI.indentLevel--;
						if (extraBonesAddDelOptsExpanded)
						{
							//make a drop area for importing bone hashes from another DynamicDnaConverter
							var dropArea = GUILayoutUtility.GetRect(0.0f, 60.0f, GUILayout.ExpandWidth(true));
							dropArea.xMin = dropArea.xMin + (EditorGUI.indentLevel * 15);
							GUI.Box(dropArea, "Drag DynamicDNAConverterBahaviours here to import their names");//cant click to pick unfortunately because this is a prefab
							var AddMethods = new GUIContent[dnaNamesAddOpts.Count];
							for (int i = 0; i < dnaNamesAddOpts.Count; i++)
								AddMethods[i] = new GUIContent(dnaNamesAddOpts[i]);
							Rect selectedAddMethodRect = dropArea;
							selectedAddMethodRect.yMin = dropArea.yMax - EditorGUIUtility.singleLineHeight - 5;
							selectedAddMethodRect.xMin = dropArea.xMin - ((EditorGUI.indentLevel * 10) - 10);
							selectedAddMethodRect.xMax = dropArea.xMax - ((EditorGUI.indentLevel * 10) + 10);
							selectedBonesAddMethod = EditorGUI.Popup(selectedAddMethodRect, new GUIContent("On Import", "Choose whether to 'Add' the bones to the current list, or 'Replace' them with the imported  ones"), selectedBonesAddMethod, AddMethods);

							ImportConverterDropArea(dropArea, selectedBonesAddMethod, AddDNAConverterHashes);

							EditorGUILayout.Space();

							//Clear all and Add Defaults Buttons
							Rect clearAndDefaultsRect = GUILayoutUtility.GetRect(0.0f, EditorGUIUtility.singleLineHeight, GUILayout.ExpandWidth(true));
							clearAndDefaultsRect.xMin = clearAndDefaultsRect.xMin + (EditorGUI.indentLevel * 15);
							var defaultsButRect = clearAndDefaultsRect;
							var clearButRect = clearAndDefaultsRect;
							defaultsButRect.width = clearAndDefaultsRect.width / 2;
							clearButRect.xMin = defaultsButRect.xMax;
							clearButRect.width = clearAndDefaultsRect.width / 2;
							if (GUI.Button(defaultsButRect, new GUIContent("Add Default Hashes", "Adds the default bone hashes as used by UMA Human Male DNA")))
							{
								AddDefaultBoneHashes();
								//once we add these we need to update the hashnames so the dropdown has the right stuff in
								hashList.serializedObject.ApplyModifiedProperties();
								serializedObject.Update();
								UpdateHashNames();
							}
							EditorGUI.BeginDisabledGroup(hashList.arraySize == 0);
							if (GUI.Button(clearButRect, new GUIContent("Clear All Bone Hashes", "Clears the current Bone Hashes. Cannot be undone.")))
							{
								bool proceed = true;
								//if there are any skeleton modifiers that are using these bone hashes warn the user that clearing this list will break them
								if (skeletonModifiers.arraySize > 0)
									proceed = EditorUtility.DisplayDialog("Really Clear All Bone Hashes?", "This will delete all the bone hashes in the list and make any skeleton modifiers you have added not work. Are you sure?", "Yes", "Cancel");
								if (proceed)
								{
									(target as DynamicDNAConverterBehaviour).hashList = new List<DynamicDNAConverterBehaviour.HashLisreplacedem>();
									hashList.serializedObject.ApplyModifiedProperties();
									serializedObject.Update();
									UpdateHashNames();
								}
							}
							EditorGUI.EndDisabledGroup();
							EditorGUILayout.Space();
						}
						//create an add field for adding new hashes
						EditorGUILayout.BeginHorizontal();
						//var buttonDisabled = newHashName == "";
						bool canAdd = true;
						bool notFoundInSkeleton = false;
						bool didAdd = false;
						EditorGUI.BeginChangeCheck();
						newHashName = EditorGUILayout.TextField(newHashName);
						if (EditorGUI.EndChangeCheck())
						{
							if (newHashName != "" && canAdd)
							{
								//buttonDisabled = false;
							}
						}
						if (newHashName != "")
						{
							for (int ni = 0; ni < hashList.arraySize; ni++)
							{
								if (hashList.GetArrayElementAtIndex(ni).FindPropertyRelative("hashName").stringValue == newHashName)
								{
									canAdd = false;
									//buttonDisabled = true;
								}
							}
							//if we have a skeleton available we can also check that the bone the user is trying to add exists
							if (umaData)
								if (umaData.skeleton != null)
								{
									if (umaData.skeleton.HasBone(UMAUtils.StringToHash(newHashName)) == false)
									{
										canAdd = false;
										//buttonDisabled = true;
										notFoundInSkeleton = true;
									}
								}
						}
						//Dont disable because it stops looking like what you want to do, just make it do nothing if nothing is entered
						/*if (buttonDisabled)
						{
							EditorGUI.BeginDisabledGroup(true);
						}*/

						if (GUILayout.Button("Add Bone Hash"))
						{
							if (canAdd)
							{
								var newHash = UMAUtils.StringToHash(newHashName);
								(target as DynamicDNAConverterBehaviour).hashList.Insert(0, new DynamicDNAConverterBehaviour.HashLisreplacedem(newHashName, newHash));
								hashList.serializedObject.ApplyModifiedProperties();
								serializedObject.Update();
								didAdd = true;
								UpdateHashNames();
								//reset the bloody text field!
								EditorGUIUtility.keyboardControl = 0;
							}
						}
						/*if (buttonDisabled)
						{
							EditorGUI.EndDisabledGroup();
						}*/
						EditorGUILayout.EndHorizontal();
						if (canAdd == false)
						{
							if (notFoundInSkeleton == true)
							{
								EditorGUILayout.HelpBox("That name was not found in the skeleton. (Standard Bone names start with a capital letter in CamelCase)", MessageType.Warning);
							}
							else
							{
								EditorGUILayout.HelpBox("That name is already in use.", MessageType.Warning);
							}
						}
						if (didAdd)
						{
							newHashName = "";
						}

						//THE ACTUAL BONE HASH LIST
						GUIHelper.BeginVerticalPadded(3, new Color(0.75f, 0.875f, 1f, 0.3f));
						EditorGUILayout.LabelField("Bone Hash List (" + hashListCount + ")", EditorStyles.helpBox);
						//Search Bone Hashes Controls
						if (hashList.arraySize > 0)
							boneHashFilter = EditorGUILayout.TextField("Search Bones", boneHashFilter);
						EditorGUI.indentLevel++;
						if (hashList.arraySize > 0)
						{
							for (int i = 0; i < hashList.arraySize; i++)
							{
								var thisHashEl = hashList.GetArrayElementAtIndex(i);
								//Search Bone Hashes Method
								if (boneHashFilter.Length >= 3)
								{
									if (thisHashEl.displayName.IndexOf(boneHashFilter, StringComparison.CurrentCultureIgnoreCase) == -1)
										continue;
								}
								EditorGUILayout.BeginHorizontal();
								thisHashEl.isExpanded = EditorGUILayout.Foldout(thisHashEl.isExpanded, thisHashEl.displayName);
								//DeleteButton
								Rect hDelButR = EditorGUILayout.GetControlRect(false);
								hDelButR.x = hDelButR.x + hDelButR.width - 100f;
								hDelButR.width = 100f;
								if (GUI.Button(hDelButR, "Delete"))
								{
									hashList.DeleteArrayElementAtIndex(i);
									continue;
								}
								EditorGUILayout.EndHorizontal();
								if (thisHashEl.isExpanded)
								{
									EditorGUI.indentLevel++;
									string origName = thisHashEl.FindPropertyRelative("hashName").stringValue;
									string newName = origName;
									EditorGUI.BeginChangeCheck();
									newName = EditorGUILayout.TextField("Hash Name", origName);
									if (EditorGUI.EndChangeCheck())
									{
										if (newName != origName && newName != "")
										{
											thisHashEl.FindPropertyRelative("hashName").stringValue = newName;
											int newHash = UMAUtils.StringToHash(newName);
											thisHashEl.FindPropertyRelative("hash").intValue = newHash;
											serializedObject.ApplyModifiedProperties();
										}
									}
									EditorGUI.BeginDisabledGroup(true);
									EditorGUILayout.IntField("Hash", thisHashEl.FindPropertyRelative("hash").intValue);
									EditorGUI.EndDisabledGroup();
									EditorGUI.indentLevel--;
								}
							}
							hashList.serializedObject.ApplyModifiedProperties();
							EditorGUILayout.Space();
						}	
						EditorGUI.indentLevel--;
						GUIHelper.EndVerticalPadded(3);
					}
				}
				//SKELETON MODIFIERS SECTION
				skeletonModifiers.isExpanded = EditorGUILayout.Foldout(skeletonModifiers.isExpanded, "Skeleton Modifiers");
				if (skeletonModifiers.isExpanded)
				{
					//If dnaNames is null or empty show a warning
					bool showDNANamesWarning = false;
					if (serializedObject.FindProperty("dnareplacedet").objectReferenceValue == null)
						showDNANamesWarning = true;
					else if((serializedObject.FindProperty("dnareplacedet").objectReferenceValue as DynamireplacedADnareplacedet).Names.Length == 0)
						showDNANamesWarning = true;
					if(showDNANamesWarning)
						EditorGUILayout.HelpBox("You need to have your DNA Names set up above in order for the Skeleton Modifiers to make any modifications", MessageType.Warning);
					//If bone hashes is empty show a warning
					if(hashList.arraySize == 0 && !minimalMode)
						EditorGUILayout.HelpBox("You need to add the bones you want the Skeleton Modifiers to be able to modify to the 'Bone Hashes' section above.", MessageType.Warning);

					EditorGUI.indentLevel++;
					extraSkelAddDelOptsExpanded = EditorGUILayout.Foldout(extraSkelAddDelOptsExpanded, "Add/Delete Modifier Options");
					EditorGUI.indentLevel--;
					if (extraSkelAddDelOptsExpanded)
					{
						//make a drop area for importing skeletonModifiers from another DynamicDnaConverter
						var dropArea = GUILayoutUtility.GetRect(0.0f, 60.0f, GUILayout.ExpandWidth(true));
						dropArea.xMin = dropArea.xMin + (EditorGUI.indentLevel * 15);
						GUI.Box(dropArea, "Drag DynamicDNAConverterBahaviours here to import their Skeleton Modifiers");//cant click to pick unfortunately because this is a prefab
						var AddMethods = new GUIContent[dnaNamesAddOpts.Count];
						for (int i = 0; i < dnaNamesAddOpts.Count; i++)
							AddMethods[i] = new GUIContent(dnaNamesAddOpts[i]);
						Rect selectedAddMethodRect = dropArea;
						selectedAddMethodRect.yMin = dropArea.yMax - EditorGUIUtility.singleLineHeight - 5;
						selectedAddMethodRect.xMin = dropArea.xMin - ((EditorGUI.indentLevel * 10) - 10);
						selectedAddMethodRect.xMax = dropArea.xMax - ((EditorGUI.indentLevel * 10) + 10);
						selectedModifiersAddMethod = EditorGUI.Popup(selectedAddMethodRect, new GUIContent("On Import", "Choose whether to 'Add' the modifiers to the current list, or 'Replace' the modifiers with the imported list"), selectedModifiersAddMethod, AddMethods);

						ImportConverterDropArea(dropArea, selectedModifiersAddMethod, AddDNAConverterModifiers);

						//Clear all button
						GUILayout.BeginHorizontal();
						GUILayout.Space(EditorGUI.indentLevel * 15);
						EditorGUI.BeginDisabledGroup(skeletonModifiers.arraySize == 0);
						if (GUILayout.Button("Clear All Modifiers"))
						{
							if (EditorUtility.DisplayDialog("Really Clear All Modifiers?", "This will delete all the skeleton modifiers in the list and cannot be undone. Are you sure?", "Yes", "Cancel"))
							{
								(target as DynamicDNAConverterBehaviour).skeletonModifiers = new List<DynamicDNAConverterBehaviour.SkeletonModifier>();
								skeletonModifiers.serializedObject.ApplyModifiedProperties();
								serializedObject.Update();
							}
						}
						EditorGUI.EndDisabledGroup();
						GUILayout.EndHorizontal();
						EditorGUILayout.Space();
					}


					//Add new Skeleton Modifier UI
					Rect addSkelButsR = EditorGUILayout.GetControlRect(false);
					var addSkelLabel = addSkelButsR;
					var addSkelBone = addSkelButsR;
					var addSkelProp = addSkelButsR;
					var addSkelAddBut = addSkelButsR;
					addSkelLabel.width = 100;
					addSkelAddBut.width = 70;
					addSkelBone.width = addSkelProp.width = (addSkelButsR.width - (addSkelLabel.width + (addSkelAddBut.width + 5))) / 2;
					addSkelBone.x = addSkelLabel.xMax;
					addSkelProp.x = addSkelBone.xMax;
					addSkelAddBut.x = addSkelProp.xMax + 5;
					EditorGUI.LabelField(addSkelLabel, new GUIContent("Add Modifier", "Add a modifier for the selected bone in the skeleton, that will modify its 'Position', 'Rotation' or 'Scale'"));
					EditorGUI.indentLevel--;
					List<string> thisBoneNames = new List<string>(0);
					//string[] boneNames = new string[0];
					/*if(minimalMode == false)
					{
						bonesInSkeleton = new List<string>( hashNames.ToArray());
					}
					else
					{
						bonesInSkeleton = new List<string>(umaData.skeleton.BoneNames);
					}
					bonesInSkeleton.Sort();*/
					//Array.Sort(boneNames);
					thisBoneNames = new List<string>(bonesInSkeleton);
					thisBoneNames.Insert(0, "Choose Bone");

					EditorGUI.BeginChangeCheck();
					selectedAddHash = EditorGUI.Popup(addSkelBone, selectedAddHash, thisBoneNames.ToArray());
					string[] propertyArray = new string[] { "Position", "Rotation", "Scale" };
					selectedAddProp = EditorGUI.Popup(addSkelProp, selectedAddProp, propertyArray);
					if (EditorGUI.EndChangeCheck())
					{
						if (selectedAddHash > 0)
						{
							addSkelBoneName = thisBoneNames[selectedAddHash];
							addSkelBoneHash = UMAUtils.StringToHash(addSkelBoneName);
						}
						else
						{
							addSkelBoneName = "";
							addSkelBoneHash = 0;
							canAddSkel = false;
						}
					}
					if (addSkelBoneName != "" && addSkelBoneHash != 0)
					{
						canAddSkel = true;
						alreadyExistedSkel = false;
						//we need to check if there is already a modifier for that bone for the selected property
						for (int i = 0; i < skeletonModifiers.arraySize; i++)
						{
							var thisSkelMod = skeletonModifiers.GetArrayElementAtIndex(i);
							if (thisSkelMod.FindPropertyRelative("property").enumValueIndex == selectedAddProp && thisSkelMod.FindPropertyRelative("hash").intValue == addSkelBoneHash)
							{
								canAddSkel = false;
								alreadyExistedSkel = true;
							}
						}
					}
					if (canAddSkel == false)
					{
						EditorGUI.BeginDisabledGroup(true);
					}
					if (GUI.Button(addSkelAddBut, "Add It!"))
					{
						if (minimalMode)
						{
							if (!hashes.Contains(addSkelBoneHash))
							{
								(target as DynamicDNAConverterBehaviour).hashList.Insert(0, new DynamicDNAConverterBehaviour.HashLisreplacedem(addSkelBoneName, addSkelBoneHash));
								hashList.serializedObject.ApplyModifiedProperties();
								serializedObject.Update();
								UpdateHashNames();
							}
						}
						(target as DynamicDNAConverterBehaviour).skeletonModifiers.Insert(0, new DynamicDNAConverterBehaviour.SkeletonModifier(addSkelBoneName, addSkelBoneHash, (DynamicDNAConverterBehaviour.SkeletonModifier.SkeletonPropType)selectedAddProp));
						skeletonModifiers.serializedObject.ApplyModifiedProperties();
						serializedObject.Update();
						addSkelBoneHash = 0;
						addSkelBoneName = "";
						selectedAddHash = 0;
						EditorGUIUtility.keyboardControl = 0;
					}
					if (canAddSkel == false)
					{
						EditorGUI.EndDisabledGroup();
					}
					if (alreadyExistedSkel == true)
					{
						EditorGUILayout.HelpBox("There was already a modifier for that bone with that property. You can serach the existing modifiers to find it.", MessageType.Warning);
					}
					EditorGUI.indentLevel++;
					//Search Filters Controls- dont show if we dont have any modifiers
					EditorGUILayout.Space();

					//THE ACTUAL MODIFIER LIST
					GUIHelper.BeginVerticalPadded(3, new Color(0.75f, 0.875f, 1f, 0.3f));
					EditorGUILayout.LabelField("Skeleton Modifiers (" + skeletonModifiers.arraySize + ")", EditorStyles.helpBox);
					if (skeletonModifiers.arraySize > 0)
					{
						Rect searchR = EditorGUILayout.GetControlRect();
						var searchL = searchR;
						var searchF = searchR;
						var searchTL = searchR;
						var searchTF = searchR;
						searchL.width = 130;
						searchF.width = (searchR.width / 3) * 2 - searchL.width;
						searchF.x = searchR.x + searchL.width;
						searchTL.width = 35;
						searchTL.x = searchF.xMax;
						searchTF.width = (searchR.width / 3) - searchTL.width + (EditorGUI.indentLevel * 15);
						searchTF.x = searchTL.xMax - (EditorGUI.indentLevel * 15);
						EditorGUI.LabelField(searchL, "Search Modifiers");
						EditorGUI.indentLevel--;
						skeletonModifiersFilter = EditorGUI.TextField(searchF, skeletonModifiersFilter);
						EditorGUI.LabelField(searchTL, "By");
						skeletonModifiersFilterType = EditorGUI.Popup(searchTF, skeletonModifiersFilterType, skeletonModifiersFilterTypeList);
						EditorGUI.indentLevel++;
					}
					EditorGUI.indentLevel++;
					for (int i = 0; i < skeletonModifiers.arraySize; i++)
					{
						var thisSkelEl = skeletonModifiers.GetArrayElementAtIndex(i);
						//Search Filters Method
						if (skeletonModifiersFilterTypeList[skeletonModifiersFilterType] != "DNA")
						{
							if (skeletonModifiersFilterType == 1 || skeletonModifiersFilterType == 2 || skeletonModifiersFilterType == 3)
							{
								string thisProperty = thisSkelEl.FindPropertyRelative("property").enumNames[thisSkelEl.FindPropertyRelative("property").enumValueIndex];
								if (skeletonModifiersFilterType == 1)//Position Modifiers
								{
									if (thisProperty.IndexOf("position", StringComparison.CurrentCultureIgnoreCase) == -1)
										continue;
								}
								else if (skeletonModifiersFilterType == 2)//Rotation Modifiers
								{
									if (thisProperty.IndexOf("rotation", StringComparison.CurrentCultureIgnoreCase) == -1)
										continue;
								}
								else if (skeletonModifiersFilterType == 3)//scale Modifiers
								{
									if (thisProperty.IndexOf("scale", StringComparison.CurrentCultureIgnoreCase) == -1)
										continue;
								}
							}
							else if (skeletonModifiersFilterType == 5)//Adjust Bones
							{
								if (thisSkelEl.displayName.IndexOf("adjust", StringComparison.CurrentCultureIgnoreCase) == -1)
									continue;
							}
							else if (skeletonModifiersFilterType == 6)//Non Adjust Bones
							{
								if (thisSkelEl.displayName.IndexOf("adjust", StringComparison.CurrentCultureIgnoreCase) > -1)
									continue;
							}
						}
						if (skeletonModifiersFilter.Length >= 3)
						{
							if (skeletonModifiersFilterTypeList[skeletonModifiersFilterType] != "DNA")
							{
								if (thisSkelEl.displayName.IndexOf(skeletonModifiersFilter, StringComparison.CurrentCultureIgnoreCase) == -1)
									continue;
							}
							else //Searches for Modifiers that use a given DNA Value- slow but super handy
							{
								string[] XYZ = new string[] { "X", "Y", "Z" };
								SerializedProperty mods;
								SerializedProperty thisMod;
								int modsi;
								bool _continue = true;
								foreach (string xyz in XYZ)
								{
									mods = thisSkelEl.FindPropertyRelative("values" + xyz).FindPropertyRelative("val").FindPropertyRelative("modifiers");
									for (int mi = 0; mi < mods.arraySize; mi++)
									{
										thisMod = mods.GetArrayElementAtIndex(mi);
										modsi = thisMod.FindPropertyRelative("modifier").enumValueIndex;
										if (modsi > 3)
										{
											if (thisMod.FindPropertyRelative("DNATypeName").stringValue.IndexOf(skeletonModifiersFilter, StringComparison.CurrentCultureIgnoreCase) > -1)
												_continue = false;
										}
									}
								}
								if (_continue)
								{
									continue;
								}
							}
						}
						Rect currentRect = EditorGUILayout.GetControlRect(false, _skelModPropDrawer.GetPropertyHeight(thisSkelEl, GUIContent.none));
						//Delete button
						Rect sDelButR = currentRect;
						sDelButR.x = sDelButR.x + sDelButR.width - 100f;
						sDelButR.width = 100f;
						sDelButR.height = EditorGUIUtility.singleLineHeight;
						if (GUI.Button(sDelButR, "Delete"))
						{
							skeletonModifiers.DeleteArrayElementAtIndex(i);
							continue;
						}
						Rect thisSkelRect = new Rect(currentRect.xMin, currentRect.yMin, currentRect.width, _skelModPropDrawer.GetPropertyHeight(thisSkelEl, GUIContent.none));
						_skelModPropDrawer.OnGUI(thisSkelRect, thisSkelEl, new GUIContent(thisSkelEl.displayName));
					}
					GUIHelper.EndVerticalPadded(3);
					EditorGUI.indentLevel--;
					//we want to discourage users from using the starting values to customise their models (if they have any modifiers set up
					if (skeletonModifiers.arraySize > 0)
					{
						_skelModPropDrawer.enableSkelModValueEditing = enableSkelModValueEditing = EditorGUILayout.ToggleLeft("Enable editing of starting Value (not reccommended)", enableSkelModValueEditing);
						//and make it easy to set the starting values back to the defaults
						GUILayout.BeginHorizontal();
						GUILayout.Space(EditorGUI.indentLevel * 15);
						if (GUILayout.Button("Reset All Starting Values to Default"))
						{
							for (int i = 0; i < skeletonModifiers.arraySize; i++)
							{
								var thisSkeModProp = skeletonModifiers.GetArrayElementAtIndex(i).FindPropertyRelative("property").enumNames[skeletonModifiers.GetArrayElementAtIndex(i).FindPropertyRelative("property").enumValueIndex];
								if (thisSkeModProp != "")
								{
									if (thisSkeModProp == "Position" || thisSkeModProp == "Rotation")
									{
										skeletonModifiers.GetArrayElementAtIndex(i).FindPropertyRelative("valuesX").FindPropertyRelative("val").FindPropertyRelative("value").floatValue = 0f;
										skeletonModifiers.GetArrayElementAtIndex(i).FindPropertyRelative("valuesY").FindPropertyRelative("val").FindPropertyRelative("value").floatValue = 0f;
										skeletonModifiers.GetArrayElementAtIndex(i).FindPropertyRelative("valuesZ").FindPropertyRelative("val").FindPropertyRelative("value").floatValue = 0f;
									}
									if (thisSkeModProp == "Scale")
									{
										skeletonModifiers.GetArrayElementAtIndex(i).FindPropertyRelative("valuesX").FindPropertyRelative("val").FindPropertyRelative("value").floatValue = 1f;
										skeletonModifiers.GetArrayElementAtIndex(i).FindPropertyRelative("valuesY").FindPropertyRelative("val").FindPropertyRelative("value").floatValue = 1f;
										skeletonModifiers.GetArrayElementAtIndex(i).FindPropertyRelative("valuesZ").FindPropertyRelative("val").FindPropertyRelative("value").floatValue = 1f;
									}
								}
							}
							skeletonModifiers.serializedObject.ApplyModifiedProperties();
						}
						GUILayout.EndHorizontal();
					}
					EditorGUILayout.Space();
				}
				EditorGUILayout.Space();
				serializedObject.FindProperty("overallModifiersEnabled").boolValue = EditorGUILayout.ToggleLeft("Enable Overall Modifiers", serializedObject.FindProperty("overallModifiersEnabled").boolValue);
				SerializedProperty overallModifiersEnabledProp = serializedObject.FindProperty("overallModifiersEnabled");
				bool overallModifiersEnabled = overallModifiersEnabledProp.boolValue;
				if (overallModifiersEnabled)
				{
					EditorGUI.BeginChangeCheck();
					EditorGUILayout.PropertyField(serializedObject.FindProperty("overallScale"));
					EditorGUILayout.PropertyField(serializedObject.FindProperty("tightenBounds"));
					EditorGUILayout.PropertyField(serializedObject.FindProperty("boundsAdjust"));
					//EditorGUILayout.PropertyField(serializedObject.FindProperty("heightModifiers"));
					EditorGUILayout.PropertyField(serializedObject.FindProperty("radiusAdjust"));
					EditorGUILayout.PropertyField(serializedObject.FindProperty("mreplacedModifiers"));
					if (EditorGUI.EndChangeCheck())
					{
						serializedObject.ApplyModifiedProperties();
					}
				}
				EditorGUI.indentLevel--;
				GUIHelper.EndVerticalPadded(3);
			}
			serializedObject.ApplyModifiedProperties();
			//===========END CONVERTER VALUES AND EDITOR============//
			//
			EditorGUILayout.Space();
			//
			//===========BONEPOSE replacedET AND EDITOR===========//
			startingPoseExpanded = EditorGUILayout.Foldout(startingPoseExpanded, "Starting Pose", foldoutTipStyle);
			if (startingPoseExpanded)
			{
				GUIHelper.BeginVerticalPadded(3, new Color(0.75f, 0.875f, 1f, 0.3f));
				EditorGUI.indentLevel++;
				startingPoseInfoExpanded = EditorGUILayout.Foldout(startingPoseInfoExpanded, "INFO");
				if (startingPoseInfoExpanded)
					EditorGUILayout.HelpBox("The 'Starting Pose'is the initial position/rotation/scale of all the bones in this Avatar's skeleton. Use this to completely transform the mesh of your character. You could (for example) transform standard UMA characters into a backwards compatible 'Short Squat Dwarf' or a 'Bobble- headded Toon'. Optionally, you can create an UMABonePose replacedet from an FBX model using the UMA > Pose Tools > Bone Pose Builder and add the resulting replacedet here. After you have added or created a UMABonePose replacedet, you can add and edit the position, rotation and scale settings for any bone in the active character's skeleton in the 'Bone Poses' section.'.", MessageType.Info);
				EditorGUI.BeginChangeCheck();
				EditorGUILayout.PropertyField(serializedObject.FindProperty("startingPose"), new GUIContent("Starting UMABonePose", "Define an replacedet that will set the starting bone poses of any Avatar using this converter"));
				if (EditorGUI.EndChangeCheck())
				{
					serializedObject.ApplyModifiedProperties();
					//If this gets set we need to back it up
					thisDDCC.BackupConverter();
				}
				//Draw the poses array from the replacedet if set or show controls to create a new replacedet.
				SerializedProperty bonePosereplacedet = serializedObject.FindProperty("startingPose");
				if (bonePosereplacedet.objectReferenceValue != null)
				{
					EditorGUILayout.PropertyField(serializedObject.FindProperty("startingPoseWeight"));
					if (thisUBP == null)
					{
						thisUBP = Editor.CreateEditor((UMA.PoseTools.UMABonePose)bonePosereplacedet.objectReferenceValue, typeof(UMA.PoseTools.UMABonePoseEditor));
						((UMA.PoseTools.UMABonePoseEditor)thisUBP).dynamicDNAConverterMode = true;
						if (umaData != null)
						{
							((UMA.PoseTools.UMABonePoseEditor)thisUBP).context = new UMA.PoseTools.UMABonePoseEditorContext();
							((UMA.PoseTools.UMABonePoseEditor)thisUBP).context.activeUMA = umaData;
						}
					}
					else if (thisUBP.target != (UMA.PoseTools.UMABonePose)bonePosereplacedet.objectReferenceValue)
					{
						thisUBP = Editor.CreateEditor((UMA.PoseTools.UMABonePose)bonePosereplacedet.objectReferenceValue, typeof(UMA.PoseTools.UMABonePoseEditor));
						((UMA.PoseTools.UMABonePoseEditor)thisUBP).dynamicDNAConverterMode = true;
						if (umaData != null)
						{
							((UMA.PoseTools.UMABonePoseEditor)thisUBP).context = new UMA.PoseTools.UMABonePoseEditorContext();
							((UMA.PoseTools.UMABonePoseEditor)thisUBP).context.activeUMA = umaData;
						}
					}
					EditorGUI.BeginChangeCheck();
					thisUBP.OnInspectorGUI();
					if (EditorGUI.EndChangeCheck())
					{
						//Currently we dont need to do anything here as the change is picked up by DynamicDNAConverterCustomizer an this triggers an UMA update
						//this may change though if we have a method in future for modifying the TPose
					}
				}
				else
				{
					if (thisDDCC != null)
					{
						var createPosereplacedetR = EditorGUILayout.GetControlRect(false);
						var createPosereplacedetRLabel = createPosereplacedetR;
						var createPosereplacedetRField = createPosereplacedetR;
						var createPosereplacedetRButton = createPosereplacedetR;
						createPosereplacedetRLabel.width = createPosereplacedetRLabel.width / 3 + 7;
						createPosereplacedetRButton.width = 70f;
						createPosereplacedetRField.width = ((createPosereplacedetRField.width / 3) * 2) - 82;
						createPosereplacedetRField.x = createPosereplacedetRLabel.xMax;
						createPosereplacedetRButton.x = createPosereplacedetRField.xMax + 5;
						EditorGUI.LabelField(createPosereplacedetRLabel, new GUIContent("New BonePose replacedet", "Create a new empty UMABonePose with the name of your choosing."));
						createBonePosereplacedetName = EditorGUI.TextField(createPosereplacedetRField, createBonePosereplacedetName);
						if (GUI.Button(createPosereplacedetRButton, "Create It"))//need to do the button enabled thing here
						{
							var newDnareplacedet = thisDDCC.CreatePosereplacedet("", createBonePosereplacedetName);
							if (newDnareplacedet != null)
							{
								//set this replacedet as the used replacedet
								bonePosereplacedet.objectReferenceValue = newDnareplacedet;
								serializedObject.ApplyModifiedProperties();
								createBonePosereplacedetName = "";
							}
						}
					}
					else
					{
						EditorGUILayout.HelpBox("Edit a character that uses this converter in the 'DynamicDna Converter Behaviour Customizer' scene and you can create a StartingPosereplacedet automatically here", MessageType.Info);
					}
				}
				if (minimalMode && umaData.skeleton != null && bonePosereplacedet.objectReferenceValue == null)
				{
					EditorGUILayout.Space();
					EditorGUILayout.LabelField("Create Poses from Current DNA state");
					EditorGUILayout.HelpBox("Create bone poses from Avatar's current dna modified state. Applies the pose and sets DNA values back to 0. Smaller margin of error equals greater accuracy but more poses to apply on DNA Update.", MessageType.Info);
					if (thisDDCC != null)
					{
						//[Range(0.000005f, 0.0005f)]
						EditorGUI.BeginChangeCheck();
						var thisAccuracy = EditorGUILayout.Slider(new GUIContent("Margin Of Error","The smaller the margin of error, the more accurate the Pose will be, but it will also have more bonePoses to apply when DNA is updated"), thisDDCC.bonePoseAccuracy * 1000, 0.5f, 0.005f);
						if (EditorGUI.EndChangeCheck())
						{
							thisDDCC.bonePoseAccuracy = thisAccuracy / 1000;
							GUI.changed = false;
						}
					}
					GUILayout.BeginHorizontal();
					GUILayout.Space(EditorGUI.indentLevel * 20);
					if (GUILayout.Button(/*createFromDnaButR, */"Create Poses"))
					{
						if (thisDDCC != null)
						{
							if (thisDDCC.CreateBonePosesFromCurrentDna(createBonePosereplacedetName))
							{
								serializedObject.Update();
							}
						}
					}
					GUILayout.EndHorizontal();

				}
				EditorGUI.indentLevel--;
				GUIHelper.EndVerticalPadded(3);
			}
			serializedObject.ApplyModifiedProperties();
			//=============END BONEPOSE replacedET AND EDITOR============//
			//
			EditorGUILayout.Space();

		}

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 : AnnotationHelper.cs
License : MIT License
Project Creator : Adoxio

public static string EnsureValidFileName(string fileName)
		{
			return fileName.IndexOf("\\", StringComparison.Ordinal) >= 0 ? fileName.Substring(fileName.LastIndexOf("\\", StringComparison.Ordinal) + 1) : fileName;
		}

See More Examples