string.Trim(params char[])

Here are the examples of the csharp api string.Trim(params char[]) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

2279 Examples 7

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

public List<int> ToArray(string name)
        {
            var cs = GetValue(name);
            if (string.IsNullOrWhiteSpace(cs))
            {
                return null;
            }
            var css = cs.Trim('[', ']').Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            return css.Length > 0 ? css.Select(int.Parse).ToList() : null;
        }

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

public List<int> ToArray(string name)
        {
            var cs = GetValue(name);
            if (string.IsNullOrWhiteSpace(cs)) return null;
            var css = cs.Trim('[', ']').Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries);
            return css.Length > 0 ? css.Select(int.Parse).ToList() : null;
        }

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

public string ResolvePathForStepHost(string path)
        {
            // make sure container exist.
            ArgUtil.NotNull(Container, nameof(Container));
            ArgUtil.NotNullOrEmpty(Container.ContainerId, nameof(Container.ContainerId));

            // remove double quotes around the path
            path = path.Trim('\"');

            // try to resolve path inside container if the request path is part of the mount volume
#if OS_WINDOWS
            if (Container.MountVolumes.Exists(x => !string.IsNullOrEmpty(x.SourceVolumePath) && path.StartsWith(x.SourceVolumePath, StringComparison.OrdinalIgnoreCase)))
#else
            if (Container.MountVolumes.Exists(x => !string.IsNullOrEmpty(x.SourceVolumePath) && path.StartsWith(x.SourceVolumePath)))
#endif
            {
                return Container.TranslateToContainerPath(path);
            }
            else
            {
                return path;
            }
        }

19 View Source File : AssetManager.cs
License : MIT License
Project Creator : Adsito

public static void SetVolumeGizmos()
    {
		if (File.Exists(VolumesListPath))
        {
			var cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
			var cubeMesh = cube.GetComponent<MeshFilter>().sharedMesh;
			GameObject.DestroyImmediate(cube);
			var sphere = GameObject.CreatePrimitive(PrimitiveType.Sphere);
			var sphereMesh = sphere.GetComponent<MeshFilter>().sharedMesh;
			GameObject.DestroyImmediate(sphere);

			var volumes = File.ReadAllLines(VolumesListPath);
            for (int i = 0; i < volumes.Length; i++)
            {
				var lineSplit = volumes[i].Split(':');
				lineSplit[0] = lineSplit[0].Trim(' '); // Volume Mesh Type
				lineSplit[1] = lineSplit[1].Trim(' '); // Prefab Path
                switch (lineSplit[0])
                {
					case "Cube":
						LoadPrefab(lineSplit[1]).AddComponent<VolumeGizmo>().mesh = cubeMesh;
						break;
					case "Sphere":
						LoadPrefab(lineSplit[1]).AddComponent<VolumeGizmo>().mesh = sphereMesh;
						break;
                }
            }
        }
    }

19 View Source File : Utilities.cs
License : MIT License
Project Creator : ADeltaX

public static string GetFileFromPath(string path)
        {
            string trimmed = path.Trim('\\');

            int index = trimmed.LastIndexOf('\\');
            if (index < 0)
            {
                return trimmed; // No directory, just a file name
            }

            return trimmed.Substring(index + 1);
        }

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

public static bool ResolveACEParameters(Session session, IEnumerable<string> aceParsedParameters, IEnumerable<ACECommandParameter> parameters, bool rawIncluded = false)
        {
            string parameterBlob = "";
            if (rawIncluded)
            {
                parameterBlob = aceParsedParameters.First();
            }
            else
            {
                parameterBlob = aceParsedParameters.Count() > 0 ? aceParsedParameters.Aggregate((a, b) => a + " " + b).Trim(new char[] { ' ', ',' }) : string.Empty;
            }
            int commaCount = parameterBlob.Count(x => x == ',');

            List<ACECommandParameter> acps = parameters.ToList();
            for (int i = acps.Count - 1; i > -1; i--)
            {
                ACECommandParameter acp = acps[i];
                acp.ParameterNo = i + 1;
                if (parameterBlob.Length > 0)
                {
                    try
                    {
                        switch (acp.Type)
                        {
                            case ACECommandParameterType.PositiveLong:
                                Match match4 = Regex.Match(parameterBlob, @"(-?\d+)$", RegexOptions.IgnoreCase);
                                if (match4.Success)
                                {
                                    if (!long.TryParse(match4.Groups[1].Value, out long val))
                                    {
                                        return false;
                                    }
                                    if (val <= 0)
                                    {
                                        return false;
                                    }
                                    acp.Value = val;
                                    acp.Defaulted = false;
                                    parameterBlob = (match4.Groups[1].Index == 0) ? string.Empty : parameterBlob.Substring(0, match4.Groups[1].Index).Trim(new char[] { ' ' });
                                }
                                break;
                            case ACECommandParameterType.Long:
                                Match match3 = Regex.Match(parameterBlob, @"(-?\d+)$", RegexOptions.IgnoreCase);
                                if (match3.Success)
                                {
                                    if (!long.TryParse(match3.Groups[1].Value, out long val))
                                    {
                                        return false;
                                    }
                                    acp.Value = val;
                                    acp.Defaulted = false;
                                    parameterBlob = (match3.Groups[1].Index == 0) ? string.Empty : parameterBlob.Substring(0, match3.Groups[1].Index).Trim(new char[] { ' ', ',' });
                                }
                                break;
                            case ACECommandParameterType.ULong:
                                Match match2 = Regex.Match(parameterBlob, @"(-?\d+)$", RegexOptions.IgnoreCase);
                                if (match2.Success)
                                {
                                    if (!ulong.TryParse(match2.Groups[1].Value, out ulong val))
                                    {
                                        return false;
                                    }
                                    acp.Value = val;
                                    acp.Defaulted = false;
                                    parameterBlob = (match2.Groups[1].Index == 0) ? string.Empty : parameterBlob.Substring(0, match2.Groups[1].Index).Trim(new char[] { ' ', ',' });
                                }
                                break;
                            case ACECommandParameterType.Location:
                                Position position = null;
                                Match match = Regex.Match(parameterBlob, @"([\d\.]+[ns])[^\d\.]*([\d\.]+[ew])$", RegexOptions.IgnoreCase);
                                if (match.Success)
                                {
                                    string ns = match.Groups[1].Value;
                                    string ew = match.Groups[2].Value;
                                    if (!TryParsePosition(new string[] { ns, ew }, out string errorMessage, out position))
                                    {
                                        if (session != null)
                                        {
                                            ChatPacket.SendServerMessage(session, errorMessage, ChatMessageType.Broadcast);
                                        }
                                        else
                                        {
                                            Console.WriteLine(errorMessage);
                                        }
                                        return false;
                                    }
                                    else
                                    {
                                        acp.Value = position;
                                        acp.Defaulted = false;
                                        int coordsStartPos = Math.Min(match.Groups[1].Index, match.Groups[2].Index);
                                        parameterBlob = (coordsStartPos == 0) ? string.Empty : parameterBlob.Substring(0, coordsStartPos).Trim(new char[] { ' ', ',' });
                                    }
                                }
                                break;
                            case ACECommandParameterType.OnlinePlayerName:
                                if (i != 0)
                                {
                                    throw new Exception("Player parameter must be the first parameter, since it can contain spaces.");
                                }
                                parameterBlob = parameterBlob.TrimEnd(new char[] { ' ', ',' });
                                Player targetPlayer = PlayerManager.GetOnlinePlayer(parameterBlob);
                                if (targetPlayer == null)
                                {
                                    string errorMsg = $"Unable to find player {parameterBlob}";
                                    if (session != null)
                                    {
                                        ChatPacket.SendServerMessage(session, errorMsg, ChatMessageType.Broadcast);
                                    }
                                    else
                                    {
                                        Console.WriteLine(errorMsg);
                                    }
                                    return false;
                                }
                                else
                                {
                                    acp.Value = targetPlayer;
                                    acp.Defaulted = false;
                                }
                                break;
                            case ACECommandParameterType.OnlinePlayerNameOrIid:
                                if (i != 0)
                                {
                                    throw new Exception("Player parameter must be the first parameter, since it can contain spaces.");
                                }

                                if (!parameterBlob.Contains(' '))
                                {
                                    if (uint.TryParse(parameterBlob, out uint iid))
                                    {
                                        Player targetPlayer2 = PlayerManager.GetOnlinePlayer(iid);
                                        if (targetPlayer2 == null)
                                        {
                                            string logMsg = $"Unable to find player with iid {iid}";
                                            if (session != null)
                                            {
                                                ChatPacket.SendServerMessage(session, logMsg, ChatMessageType.Broadcast);
                                            }
                                            else
                                            {
                                                Console.WriteLine(logMsg);
                                            }
                                            return false;
                                        }
                                        else
                                        {
                                            acp.Value = targetPlayer2;
                                            acp.Defaulted = false;
                                            break;
                                        }
                                    }
                                }
                                Player targetPlayer3 = PlayerManager.GetOnlinePlayer(parameterBlob);
                                if (targetPlayer3 == null)
                                {
                                    string logMsg = $"Unable to find player {parameterBlob}";
                                    if (session != null)
                                    {
                                        ChatPacket.SendServerMessage(session, logMsg, ChatMessageType.Broadcast);
                                    }
                                    else
                                    {
                                        Console.WriteLine(logMsg);
                                    }

                                    return false;
                                }
                                else
                                {
                                    acp.Value = targetPlayer3;
                                    acp.Defaulted = false;
                                }
                                break;
                            case ACECommandParameterType.OnlinePlayerIid:
                                Match matcha5 = Regex.Match(parameterBlob, /*((i == 0) ? "" : @"\s+") +*/ @"(\d{10})$|(0x[0-9a-f]{8})$", RegexOptions.IgnoreCase);
                                if (matcha5.Success)
                                {
                                    string strIid = "";
                                    if (matcha5.Groups[2].Success)
                                    {
                                        strIid = matcha5.Groups[2].Value;
                                    }
                                    else if (matcha5.Groups[1].Success)
                                    {
                                        strIid = matcha5.Groups[1].Value;
                                    }
                                    try
                                    {
                                        uint iid = 0;
                                        if (strIid.StartsWith("0x"))
                                        {
                                            iid = Convert.ToUInt32(strIid, 16);
                                        }
                                        else
                                        {
                                            iid = uint.Parse(strIid);
                                        }

                                        Player targetPlayer2 = PlayerManager.GetOnlinePlayer(iid);
                                        if (targetPlayer2 == null)
                                        {
                                            string logMsg = $"Unable to find player with iid {strIid}";
                                            if (session != null)
                                            {
                                                ChatPacket.SendServerMessage(session, logMsg, ChatMessageType.Broadcast);
                                            }
                                            else
                                            {
                                                Console.WriteLine(logMsg);
                                            }
                                            return false;
                                        }
                                        else
                                        {
                                            acp.Value = targetPlayer2;
                                            acp.Defaulted = false;
                                            parameterBlob = (matcha5.Groups[1].Index == 0) ? string.Empty : parameterBlob.Substring(0, matcha5.Groups[1].Index).Trim(new char[] { ' ', ',' });
                                        }
                                    }
                                    catch (Exception)
                                    {
                                        string errorMsg = $"Unable to parse {strIid} into a player iid";
                                        if (session != null)
                                        {
                                            ChatPacket.SendServerMessage(session, errorMsg, ChatMessageType.Broadcast);
                                        }
                                        else
                                        {
                                            Console.WriteLine(errorMsg);
                                        }
                                        return false;
                                    }
                                }
                                break;
                            case ACECommandParameterType.PlayerName:
                                if (i != 0)
                                {
                                    throw new Exception("Player name parameter must be the first parameter, since it can contain spaces.");
                                }
                                parameterBlob = parameterBlob.TrimEnd(new char[] { ' ', ',' });
                                if (string.IsNullOrWhiteSpace(parameterBlob))
                                {
                                    break;
                                }
                                else
                                {
                                    acp.Value = parameterBlob;
                                    acp.Defaulted = false;
                                }
                                break;
                            case ACECommandParameterType.Uri:
                                Match match5 = Regex.Match(parameterBlob, @"(https?:\/\/(www\.)?[[email protected]:%._\+~#=]{2,256}\.[a-z]{2,6}\b([[email protected]:%_\+.~#?&//=]*))$", RegexOptions.IgnoreCase);
                                if (match5.Success)
                                {
                                    string strUri = match5.Groups[1].Value;
                                    try
                                    {
                                        Uri url = new Uri(strUri);
                                        acp.Value = url;
                                        acp.Defaulted = false;
                                        parameterBlob = (match5.Groups[1].Index == 0) ? string.Empty : parameterBlob.Substring(0, match5.Groups[1].Index).Trim(new char[] { ' ', ',' });
                                    }
                                    catch (Exception)
                                    {
                                        return false;
                                    }
                                }
                                break;
                            case ACECommandParameterType.DoubleQuoteEnclosedText:
                                Match match6 = Regex.Match(parameterBlob.TrimEnd(), @"(\"".*\"")$", RegexOptions.IgnoreCase);
                                if (match6.Success)
                                {
                                    string txt = match6.Groups[1].Value;
                                    try
                                    {
                                        acp.Value = txt.Trim('"');
                                        acp.Defaulted = false;
                                        parameterBlob = (match6.Groups[1].Index == 0) ? string.Empty : parameterBlob.Substring(0, match6.Groups[1].Index).Trim(new char[] { ' ', ',' });
                                    }
                                    catch (Exception)
                                    {
                                        return false;
                                    }
                                }
                                break;
                            case ACECommandParameterType.CommaPrefixedText:
                                if (i == 0)
                                {
                                    throw new Exception("this parameter type is not appropriate as the first parameter");
                                }
                                if (i == acps.Count - 1 && !acp.Required && commaCount < acps.Count - 1)
                                {
                                    break;
                                }
                                Match match7 = Regex.Match(parameterBlob.TrimEnd(), @"\,\s*([^,]*)$", RegexOptions.IgnoreCase);
                                if (match7.Success)
                                {
                                    string txt = match7.Groups[1].Value;
                                    try
                                    {
                                        acp.Value = txt.TrimStart(new char[] { ' ', ',' });
                                        acp.Defaulted = false;
                                        parameterBlob = (match7.Groups[1].Index == 0) ? string.Empty : parameterBlob.Substring(0, match7.Groups[1].Index).Trim(new char[] { ' ', ',' });
                                    }
                                    catch (Exception)
                                    {
                                        return false;
                                    }
                                }
                                break;
                            case ACECommandParameterType.SimpleWord:
                                Match match8 = Regex.Match(parameterBlob.TrimEnd(), @"([a-zA-Z1-9_]+)\s*$", RegexOptions.IgnoreCase);
                                if (match8.Success)
                                {
                                    string txt = match8.Groups[1].Value;
                                    try
                                    {
                                        acp.Value = txt.TrimStart(' ');
                                        acp.Defaulted = false;
                                        parameterBlob = (match8.Groups[1].Index == 0) ? string.Empty : parameterBlob.Substring(0, match8.Groups[1].Index).Trim(new char[] { ' ', ',' });
                                    }
                                    catch (Exception)
                                    {
                                        return false;
                                    }
                                }
                                break;
                            case ACECommandParameterType.Enum:
                                if (acp.PossibleValues == null)
                                {
                                    throw new Exception("The enum parameter type must be accompanied by the PossibleValues");
                                }
                                if (!acp.PossibleValues.IsEnum)
                                {
                                    throw new Exception("PossibleValues must be an enum type");
                                }
                                Match match9 = Regex.Match(parameterBlob.TrimEnd(), @"([a-zA-Z1-9_]+)\s*$", RegexOptions.IgnoreCase);
                                if (match9.Success)
                                {
                                    string txt = match9.Groups[1].Value;
                                    try
                                    {
                                        txt = txt.Trim(new char[] { ' ', ',' });
                                        Array etvs = Enum.GetValues(acp.PossibleValues);
                                        foreach (object etv in etvs)
                                        {
                                            if (etv.ToString().ToLower() == txt.ToLower())
                                            {
                                                acp.Value = etv;
                                                acp.Defaulted = false;
                                                parameterBlob = (match9.Groups[1].Index == 0) ? string.Empty : parameterBlob.Substring(0, match9.Groups[1].Index).Trim(new char[] { ' ' });
                                                break;
                                            }
                                        }
                                    }
                                    catch (Exception)
                                    {
                                        return false;
                                    }
                                }
                                break;
                        }
                    }
                    catch
                    {
                        return false;
                    }
                }
                if (acp.Defaulted)
                {
                    acp.Value = acp.DefaultValue;
                }

                if (acp.Required && acp.Defaulted)
                {
                    if (!string.IsNullOrWhiteSpace(acp.ErrorMessage))
                    {
                        if (session != null)
                        {
                            ChatPacket.SendServerMessage(session, acp.ErrorMessage, ChatMessageType.Broadcast);
                        }
                        else
                        {
                            Console.WriteLine(acp.ErrorMessage);
                        }
                    }

                    return false;
                }
            }
            return true;
        }

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

public static string DesDecrypt(string val)
        {
            return DesDecryptInner(DesDecryptInner(val)).Trim('[', ']');
        }

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

private string ResolveWhereNode<T>(WhereNode node, T parameter) where T :clreplaced
        {
            var buffer = new StringBuilder();
            foreach (var item in node.Nodes)
            {
                if (parameter!=default && item is IfNode)
                {
                    var text = ResolveIfNode(item as IfNode, parameter);
                    buffer.Append($"{text} ");
                }
                else if (item is TextNode)
                {
                    var text = ResolveTextNode(item as TextNode);
                    buffer.Append($"{text} ");
                }
            }
            var sql = buffer.ToString().Trim(' ');
            if (sql.StartsWith("and", StringComparison.OrdinalIgnoreCase))
            {
                sql = sql.Remove(0, 3);
            }
            else if (sql.StartsWith("or", StringComparison.OrdinalIgnoreCase))
            {
                sql = sql.Remove(0, 2);
            }
            return sql.Length > 0 ? "WHERE " + sql : string.Empty;
        }

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

public static string GetCacheKey(string requestId)
        {
            return RedisKeyBuilder.ToSystemKey("api", "ctx", requestId.Trim('$').ToUpper());
        }

19 View Source File : LUTPanelOptions.cs
License : MIT License
Project Creator : a1xd

private static (Vec2<float>[], int length) UserTextToPoints(string userText)
        {
            if (string.IsNullOrWhiteSpace(userText))
            {
                throw new ApplicationException("Text must be entered in text box to fill Look Up Table.");
            }

            Vec2<float>[] points = new Vec2<float>[AccelArgs.MaxLutPoints];

            var userTextSplit = userText.Trim().Trim(';').Split(';');
            int index = 0;
            float lastX = 0;

            int pointsCount = userTextSplit.Count();

            if (pointsCount < 2)
            {
                throw new ApplicationException("At least 2 points required");
            }

            if (pointsCount > AccelArgs.MaxLutPoints)
            {
                throw new ApplicationException($"Number of points exceeds max ({AccelArgs.MaxLutPoints})");
            }

            foreach(var pointEntry in userTextSplit)
            {
                var pointSplit = pointEntry.Trim().Split(',');

                if (pointSplit.Length != 2)
                {
                    throw new ApplicationException($"Point at index {index} is malformed. Expected format: x,y; Given: {pointEntry.Trim()}");
                }

                float x;
                float y;

                try
                {
                    x = float.Parse(pointSplit[0]);
                }
                catch (Exception ex)
                {
                    throw new ApplicationException($"X-value for point at index {index} is malformed. Expected: float. Given: {pointSplit[0]}", ex);
                }

                if (x <= 0)
                {
                    throw new ApplicationException($"X-value for point at index {index} is less than or equal to 0. Point (0,0) is implied and should not be specified in points text.");
                }

                if (x <= lastX)
                {
                    throw new ApplicationException($"X-value for point at index {index} is less than or equal to previous x-value. Value: {x} Previous: {lastX}");
                }

                lastX = x;

                try
                {
                    y = float.Parse(pointSplit[1]);
                }
                catch (Exception ex)
                {
                    throw new ApplicationException($"Y-value for point at index {index} is malformed. Expected: float. Given: {pointSplit[1]}", ex);
                }

                if (y <= 0)
                {
                    throw new ApplicationException($"Y-value for point at index {index} is less than or equal to 0. Value: {y}");
                }

                points[index] = new Vec2<float> { x = x, y = y };

                index++;
            }

            return (points, userTextSplit.Length);
        }

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

private static string GetDefaultBlogPostPartialUrl(DateTime date, string replacedle)
		{
			if (string.IsNullOrWhiteSpace(replacedle))
			{
				throw new ArgumentException("Value can't be null or whitespace.", "replacedle");
			}

			string replacedleSlug;

			try
			{
				// Encoding the replacedle as Cyrillic, and then back to ASCII, converts accented characters to their
				// unaccented version. We'll try/catch this, since it depends on the underlying platform whether
				// the Cyrillic code page is available.
				replacedleSlug = Encoding.ASCII.GetString(Encoding.GetEncoding("Cyrillic").GetBytes(replacedle)).ToLowerInvariant();
			}
			catch
			{
				replacedleSlug = replacedle.ToLowerInvariant();
			}

			// Strip all disallowed characters.
			replacedleSlug = Regex.Replace(replacedleSlug, @"[^a-z0-9\s-]", string.Empty);

			// Convert all runs of multiple spaces to a single space.
			replacedleSlug = Regex.Replace(replacedleSlug, @"\s+", " ").Trim();

			// Cap the length of the replacedle slug.
			replacedleSlug = replacedleSlug.Substring(0, replacedleSlug.Length <= 50 ? replacedleSlug.Length : 50).Trim();

			// Replace all spaces with hyphens.
			replacedleSlug = Regex.Replace(replacedleSlug, @"\s", "-").Trim('-');

			return "{0:yyyy}-{0:MM}-{0:dd}-{1}".FormatWith(date, replacedleSlug);
		}

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

private static string GetDefaultIdeaPartialUrl(string replacedle)
		{
			if (string.IsNullOrWhiteSpace(replacedle))
			{
				throw new ArgumentException("Value can't be null or whitespace.", "replacedle");
			}

			string replacedleSlug;

			try
			{
				// Encoding the replacedle as Cyrillic, and then back to ASCII, converts accented characters to their
				// unaccented version. We'll try/catch this, since it depends on the underlying platform whether
				// the Cyrillic code page is available.
				replacedleSlug = Encoding.ASCII.GetString(Encoding.GetEncoding("Cyrillic").GetBytes(replacedle)).ToLowerInvariant();
			}
			catch
			{
				replacedleSlug = replacedle.ToLowerInvariant();
			}

			// Strip all disallowed characters.
			replacedleSlug = Regex.Replace(replacedleSlug, @"[^a-z0-9\s-]", string.Empty);

			// Convert all runs of multiple spaces to a single space.
			replacedleSlug = Regex.Replace(replacedleSlug, @"\s+", " ").Trim();

			// Cap the length of the replacedle slug.
			replacedleSlug = replacedleSlug.Substring(0, replacedleSlug.Length <= 50 ? replacedleSlug.Length : 50).Trim();

			// Replace all spaces with hyphens.
			replacedleSlug = Regex.Replace(replacedleSlug, @"\s", "-").Trim('-');

			return replacedleSlug;
		}

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

private string ParseFormattedDescription(string formattedDescription)
        {
            if (string.IsNullOrEmpty(formattedDescription)) return string.Empty;

            var formatted = formattedDescription
                .Trim('\n', ' ')
                .Replace("\r\n", "\n")
                .Replace("\n", "<LineBreak/>")
                .Replace("[b][i]", "<Run FontWeight=\"Bold\" FontStyle=\"Italic\">")
                .Replace("[i][b]", "<Run FontWeight=\"Bold\" FontStyle=\"Italic\">")
                .Replace("[b]", "<Run FontWeight=\"Bold\">")
                .Replace("[i]", "<Run FontStyle=\"Italic\">")
                .Replace("[/b][/i]", "</Run>")
                .Replace("[/i][/b]", "</Run>")
                .Replace("[/b]", "</Run>")
                .Replace("[/i]", "</Run>");

#if SILVERLIGHT
            const string replace = "<Hyperlink Foreground=\"{StaticResource SciChartGreenBrush}\" " +
                                            "MouseOverForeground=\"{StaticResource SciChartDarkGreenBrush}\" " + 
                                            "TextDecorations=\"Underline\" " + 
                                            "MouseOverTextDecorations=\"None\" " + 
                                            "NavigateUri=\"$1\" TargetName=\"_blank\">" + 
                                                "<Run>$2</Run>" + 
                                   "</Hyperlink>";
#else 
            const string replace = "<Hyperlink Style=\"{DynamicResource HyperlinkStyle}\" NavigateUri=\"$1\"><Run>$2</Run></Hyperlink>";
#endif

            // TO dump all links out to console, uncomment 
            // 

//            Regex urlRegexShort = new Regex(@"\[url='(.*?)'?\]");
//            var allLinks = urlRegexShort.Matches(formatted)
//                .Cast<Match>()
//                .Select(x => x.ToString().Replace("url=[", "").Replace("]", ""))
//                .Distinct()
//                .Select(y => string.Format("{0}\t{1}", this.replacedle, y))
//                .OrderBy(x => x)
//                .ToList();
//
//            foreach (var match in allLinks)
//            {
//                Trace.WriteLine(match);
//            }
                

            formatted = _urlRegex.Replace(formatted, replace);

            return formatted;
        }

19 View Source File : TerminalCommonNameValidator.cs
License : MIT License
Project Creator : Adyen

public static bool ValidateCertificate(string certificateSubject, Model.Enum.Environment environment)
        {
            var environmentName = environment.ToString().ToLower();
            var regexPatternTerminalSpecificCert = _terminalApiCnRegex.Replace(_environmentWildcard, environmentName);
            var regexPatternLegacyCert = _terminalApiLegacy.Replace(_environmentWildcard, environmentName);
            var subject = certificateSubject.Split(',')
                     .Select(x => x.Split('='))
                     .ToDictionary(x => x[0].Trim(' '), x => x[1]);
            if (subject.ContainsKey("CN"))
            {
                string commonNameValue = subject["CN"];
                if (Regex.Match(commonNameValue, regexPatternTerminalSpecificCert).Success || string.Equals(commonNameValue, regexPatternLegacyCert))
                {
                    return true;
                }
            }
            return false;
        }

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

public string Resolve<T>(CommandNode command, T parameter) where T : clreplaced
        {
            var buffer = new StringBuilder();
            foreach (var item in command.Nodes)
            {
                if (item is TextNode)
                {
                    var txt = ResolveTextNode(item as TextNode);
                    if (txt.Length > 0)
                    {
                        buffer.AppendFormat($" {txt}");
                    }
                }
                else if (item is WhereNode)
                {
                    var wheresql = ResolveWhereNode(item as WhereNode, parameter);
                    if (wheresql.Length > 0)
                    {
                        buffer.AppendFormat($" {wheresql}");
                    }
                }
                else if (item is IfNode)
                {
                    var txt = ResolveIfNode(item as IfNode, parameter);
                    if (txt.Length > 0)
                    {
                        buffer.AppendFormat($" {txt}");
                    }
                }
            }
            return buffer.ToString().Trim(' ');
        }

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

private string ConvertExpression(Expression expression)
        {
            var binaryExpression = expression as BinaryExpression;
            if (binaryExpression != null)
            {
                return Convert(binaryExpression);
            }
            var Unary = expression as UnaryExpression;
            if (Unary != null)
            {
                return this.Convert(Unary);
            }
            var call = expression as MethodCallExpression;
            if (call != null)
            {
                return this.Convert(call);
            }
            var memberExpression = expression as MemberExpression;
            if (memberExpression != null)
            {
                return Convert(memberExpression);
            }
            var constantExpression = expression as ConstantExpression;
            if (constantExpression != null)
            {
                return this.Convert(constantExpression);
            }
            var array = expression as NewArrayExpression;
            if (array != null)
            {
                var sb = new StringBuilder();
                foreach (var arg in array.Expressions)
                {
                    sb.AppendFormat(",{0}", this.ConvertExpression(arg));
                }
                return sb.ToString().Trim(',');
            }
            if (expression.NodeType == ExpressionType.IsTrue)
            {
                return "1";
            }
            if (expression.NodeType == ExpressionType.IsFalse)
            {
                return "0";
            }
            throw new ArgumentException("Invalid lambda expression");
        }

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

public async Task RunAsync(RunnerActionPluginExecutionContext executionContext, CancellationToken token)
        {
            string runnerWorkspace = executionContext.GetRunnerContext("workspace");
            ArgUtil.Directory(runnerWorkspace, nameof(runnerWorkspace));
            string tempDirectory = executionContext.GetRunnerContext("temp");
            ArgUtil.Directory(tempDirectory, nameof(tempDirectory));

            var repoFullName = executionContext.GetInput(Pipelines.PipelineConstants.CheckoutTaskInputs.Repository);
            if (string.IsNullOrEmpty(repoFullName))
            {
                repoFullName = executionContext.GetGitHubContext("repository");
            }

            var repoFullNameSplit = repoFullName.Split("/", StringSplitOptions.RemoveEmptyEntries);
            if (repoFullNameSplit.Length != 2)
            {
                throw new ArgumentOutOfRangeException(repoFullName);
            }

            string expectRepoPath;
            var path = executionContext.GetInput(Pipelines.PipelineConstants.CheckoutTaskInputs.Path);
            if (!string.IsNullOrEmpty(path))
            {
                expectRepoPath = IOUtil.ResolvePath(runnerWorkspace, path);
                if (!expectRepoPath.StartsWith(runnerWorkspace.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar))
                {
                    throw new ArgumentException($"Input path '{path}' should resolve to a directory under '{runnerWorkspace}', current resolved path '{expectRepoPath}'.");
                }
            }
            else
            {
                // When repository doesn't has path set, default to sources directory 1/repoName
                expectRepoPath = Path.Combine(runnerWorkspace, repoFullNameSplit[1]);
            }

            var workspaceRepo = executionContext.GetGitHubContext("repository");
            // for self repository, we need to let the worker knows where it is after checkout.
            if (string.Equals(workspaceRepo, repoFullName, StringComparison.OrdinalIgnoreCase))
            {
                var workspaceRepoPath = executionContext.GetGitHubContext("workspace");

                executionContext.Debug($"Repository requires to be placed at '{expectRepoPath}', current location is '{workspaceRepoPath}'");
                if (!string.Equals(workspaceRepoPath.Trim(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar), expectRepoPath.Trim(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar), IOUtil.FilePathStringComparison))
                {
                    executionContext.Output($"Repository is current at '{workspaceRepoPath}', move to '{expectRepoPath}'.");
                    var count = 1;
                    var staging = Path.Combine(tempDirectory, $"_{count}");
                    while (Directory.Exists(staging))
                    {
                        count++;
                        staging = Path.Combine(tempDirectory, $"_{count}");
                    }

                    try
                    {
                        executionContext.Debug($"Move existing repository '{workspaceRepoPath}' to '{expectRepoPath}' via staging directory '{staging}'.");
                        IOUtil.MoveDirectory(workspaceRepoPath, expectRepoPath, staging, CancellationToken.None);
                    }
                    catch (Exception ex)
                    {
                        executionContext.Debug("Catch exception during repository move.");
                        executionContext.Debug(ex.ToString());
                        executionContext.Warning("Unable move and reuse existing repository to required location.");
                        IOUtil.DeleteDirectory(expectRepoPath, CancellationToken.None);
                    }

                    executionContext.Output($"Repository will locate at '{expectRepoPath}'.");
                }

                executionContext.Debug($"Update workspace repository location.");
                executionContext.SetRepositoryPath(repoFullName, expectRepoPath, true);
            }

            string sourceBranch;
            string sourceVersion;
            string refInput = executionContext.GetInput(Pipelines.PipelineConstants.CheckoutTaskInputs.Ref);
            if (string.IsNullOrEmpty(refInput))
            {
                sourceBranch = executionContext.GetGitHubContext("ref");
                sourceVersion = executionContext.GetGitHubContext("sha");
            }
            else
            {
                sourceBranch = refInput;
                sourceVersion = executionContext.GetInput(Pipelines.PipelineConstants.CheckoutTaskInputs.Version);  // version get removed when checkout move to repo in the graph
                if (string.IsNullOrEmpty(sourceVersion) && RegexUtility.IsMatch(sourceBranch, WellKnownRegularExpressions.SHA1))
                {
                    sourceVersion = sourceBranch;
                    // If Ref is a SHA and the repo is self, we need to use github.ref as source branch since it might be refs/pull/*
                    if (string.Equals(workspaceRepo, repoFullName, StringComparison.OrdinalIgnoreCase))
                    {
                        sourceBranch = executionContext.GetGitHubContext("ref");
                    }
                    else
                    {
                        sourceBranch = "refs/heads/master";
                    }
                }
            }

            bool clean = StringUtil.ConvertToBoolean(executionContext.GetInput(Pipelines.PipelineConstants.CheckoutTaskInputs.Clean), true);
            string submoduleInput = executionContext.GetInput(Pipelines.PipelineConstants.CheckoutTaskInputs.Submodules);

            int fetchDepth = 0;
            if (!int.TryParse(executionContext.GetInput("fetch-depth"), out fetchDepth) || fetchDepth < 0)
            {
                fetchDepth = 0;
            }

            bool gitLfsSupport = StringUtil.ConvertToBoolean(executionContext.GetInput(Pipelines.PipelineConstants.CheckoutTaskInputs.Lfs));
            string accessToken = executionContext.GetInput(Pipelines.PipelineConstants.CheckoutTaskInputs.Token);
            if (string.IsNullOrEmpty(accessToken))
            {
                accessToken = executionContext.GetGitHubContext("token");
            }

            // register problem matcher
            string matcherFile = Path.Combine(tempDirectory, $"git_{Guid.NewGuid()}.json");
            File.WriteAllText(matcherFile, GitHubSourceProvider.ProblemMatcher, new UTF8Encoding(false));
            executionContext.Output($"##[add-matcher]{matcherFile}");
            try
            {
                await new GitHubSourceProvider().GetSourceAsync(executionContext,
                                                                expectRepoPath,
                                                                repoFullName,
                                                                sourceBranch,
                                                                sourceVersion,
                                                                clean,
                                                                submoduleInput,
                                                                fetchDepth,
                                                                gitLfsSupport,
                                                                accessToken,
                                                                token);
            }
            finally
            {
                executionContext.Output("##[remove-matcher owner=checkout-git]");
            }
        }

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

public static string SafeTrim(this string str,params char[] chars)
        {
            return string.IsNullOrWhiteSpace(str) ? null : str.Trim(chars);
        }

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

private string ReplaceVariable(Dictionary<string, string> variables, string text)
        {
            var matches = Regex.Matches(text, @"\${(?<key>.*?)}");
            foreach (Match item in matches)
            {
                var key = item.Groups["key"].Value;
                if (variables.ContainsKey(key))
                {
                    var value = variables[key];
                    text = text.Replace("${" + key + "}", value);
                }
            }
            return Regex.Replace(text, @"\s+", " ").Trim(' ');
        }

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

private string ConvertExpression(Expression expression)
        {
            if (expression is BinaryExpression binaryExpression)
            {
                return Convert(binaryExpression);
            }
            if (expression is UnaryExpression unary)
            {
                return Convert(unary);
            }
            if (expression is MethodCallExpression call)
            {
                return Convert(call);
            }
            if (expression is MemberExpression memberExpression)
            {
                return Convert(memberExpression);
            }
            if (expression is ConstantExpression constantExpression)
            {
                return Convert(constantExpression);
            }
            if (expression is NewArrayExpression array)
            {
                var sb = new StringBuilder();
                foreach (var arg in array.Expressions)
                {
                    sb.AppendFormat(",{0}", ConvertExpression(arg));
                }
                return sb.ToString().Trim(',');
            }
            if (expression.NodeType == ExpressionType.IsTrue)
            {
                return "1";
            }
            if (expression.NodeType == ExpressionType.IsFalse)
            {
                return "0";
            }
            throw new ArgumentException("Invalid lambda expression");
        }

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

private void GetSingleDacAndConstantTags(ITextSnapshot newSnapshot, string bqlCommand, int offset)
		{
			var matches = RegExpressions.DacOrConstantRegex.Matches(bqlCommand);

			foreach (Match dacOrConstMatch in matches)
			{
				string dacOrConst = dacOrConstMatch.Value.Trim(',', '<', '>');
				CreateTag(newSnapshot, dacOrConstMatch, offset, dacOrConst, Provider[PXCodeType.Dac]);
			}
		}

19 View Source File : HiveHeader.cs
License : MIT License
Project Creator : ADeltaX

public int ReadFrom(byte[] buffer, int offset)
        {
            uint sig = EndianUtilities.ToUInt32LittleEndian(buffer, offset + 0);
            if (sig != Signature)
            {
                throw new IOException("Invalid signature for registry hive");
            }

            Sequence1 = EndianUtilities.ToInt32LittleEndian(buffer, offset + 0x0004);
            Sequence2 = EndianUtilities.ToInt32LittleEndian(buffer, offset + 0x0008);

            Timestamp = DateTime.FromFileTimeUtc(EndianUtilities.ToInt64LittleEndian(buffer, offset + 0x000C));

            MajorVersion = EndianUtilities.ToInt32LittleEndian(buffer, 0x0014);
            MinorVersion = EndianUtilities.ToInt32LittleEndian(buffer, 0x0018);

            int isLog = EndianUtilities.ToInt32LittleEndian(buffer, 0x001C);

            RootCell = EndianUtilities.ToInt32LittleEndian(buffer, 0x0024);
            Length = EndianUtilities.ToInt32LittleEndian(buffer, 0x0028);

            Path = Encoding.Unicode.GetString(buffer, 0x0030, 0x0040).Trim('\0');

            Guid1 = EndianUtilities.ToGuidLittleEndian(buffer, 0x0070);
            Guid2 = EndianUtilities.ToGuidLittleEndian(buffer, 0x0094);

            Checksum = EndianUtilities.ToUInt32LittleEndian(buffer, 0x01FC);

            if (Sequence1 != Sequence2)
            {
                throw new NotImplementedException("Support for replaying registry log file");
            }

            if (Checksum != CalcChecksum(buffer, offset))
            {
                throw new IOException("Invalid checksum on registry file");
            }

            return HeaderSize;
        }

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

private string ResolveOrder()
        {
            var buffer = new StringBuilder();
            foreach (var item in _orderExpressions)
            {
                if (item == _orderExpressions.First())
                {
                    buffer.Append($" ORDER BY ");
                }
                var result = new OrderExpressionResovle(item.Expression, item.Asc).Resovle();
                buffer.Append(result);
                buffer.Append(",");
            }
            return buffer.ToString().Trim(',');
        }

19 View Source File : RegistryValue.cs
License : MIT License
Project Creator : ADeltaX

private static object ConvertToObject(byte[] data, RegistryValueType type)
        {
            switch (type)
            {
                case RegistryValueType.String:
                case RegistryValueType.ExpandString:
                case RegistryValueType.Link:
                    return Encoding.Unicode.GetString(data).Trim('\0');

                case RegistryValueType.Dword:
                    return EndianUtilities.ToInt32LittleEndian(data, 0);

                case RegistryValueType.DwordBigEndian:
                    return EndianUtilities.ToInt32BigEndian(data, 0);

                case RegistryValueType.MultiString:
                    string multiString = Encoding.Unicode.GetString(data).Trim('\0');
                    return multiString.Split('\0');

                case RegistryValueType.QWord:
                    return string.Empty + EndianUtilities.ToUInt64LittleEndian(data, 0);

                default:
                    return data;
            }
        }

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

internal string AddSpacesIfRequired(string newText, TextViewPosition start, TextViewPosition end)
		{
			if (EnableVirtualSpace && InsertVirtualSpaces(newText, start, end)) {
				var line = textArea.Doreplacedent.GetLineByNumber(start.Line);
				string lineText = textArea.Doreplacedent.GetText(line);
				var vLine = textArea.TextView.GetOrConstructVisualLine(line);
				int colDiff = start.VisualColumn - vLine.VisualLengthWithEndOfLineMarker;
				if (colDiff > 0) {
					string additionalSpaces = "";
					if (!textArea.Options.ConvertTabsToSpaces && lineText.Trim('\t').Length == 0) {
						int tabCount = (int)(colDiff / textArea.Options.IndentationSize);
						additionalSpaces = new string('\t', tabCount);
						colDiff -= tabCount * textArea.Options.IndentationSize;
					}
					additionalSpaces += new string(' ', colDiff);
					return additionalSpaces + newText;
				}
			}
			return newText;
		}

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

protected virtual MailMessage GetMailMessage(Exception error, HttpContext context, TraceContext trace, int dropped)
		{
			var from = GetFrom(context);
			var to = GetTo(context);
			var subject = GetSubject(error, context);
			var body = GetBody(error, context, trace);

			// ensure that e-mail follows SMTP standards

			if (!body.EndsWith("\r\n"))
			{
				body += "\r\n";
			}

			var message = new MailMessage { IsBodyHtml = true, Subject = subject, Body = body };

			if (from != null) message.From = from;
			if (!string.IsNullOrWhiteSpace(to)) message.To.Add(to.Trim(new[] { ';', ',' }).Replace(';', ','));

			foreach (var header in GetHeaders(error, context, dropped))
			{
				if (!string.IsNullOrEmpty(header.Value))
				{
					message.Headers.Add(header.Key, header.Value);
				}
			}

			foreach (var attachment in GetAttachments(error, context))
			{
				message.Attachments.Add(attachment);
			}

			return message;
		}

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

private static string GetDefaultIssuePartialUrl(string replacedle)
		{
			if (string.IsNullOrWhiteSpace(replacedle))
			{
				throw new ArgumentException("Value can't be null or whitespace.", "replacedle");
			}

			string replacedleSlug;

			try
			{
				// Encoding the replacedle as Cyrillic, and then back to ASCII, converts accented characters to their
				// unaccented version. We'll try/catch this, since it depends on the underlying platform whether
				// the Cyrillic code page is available.
				replacedleSlug = Encoding.ASCII.GetString(Encoding.GetEncoding("Cyrillic").GetBytes(replacedle)).ToLowerInvariant();
			}
			catch
			{
				replacedleSlug = replacedle.ToLowerInvariant();
			}

			// Strip all disallowed characters.
			replacedleSlug = Regex.Replace(replacedleSlug, @"[^a-z0-9\s-]", string.Empty);

			// Convert all runs of multiple spaces to a single space.
			replacedleSlug = Regex.Replace(replacedleSlug, @"\s+", " ").Trim();

			// Cap the length of the replacedle slug.
			replacedleSlug = replacedleSlug.Substring(0, replacedleSlug.Length <= 50 ? replacedleSlug.Length : 50).Trim();

			// Replace all spaces with hyphens.
			replacedleSlug = Regex.Replace(replacedleSlug, @"\s", "-").Trim('-');

			return replacedleSlug;
		}

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

private string ParseHtmlDescription(string description)
        {
            if (string.IsNullOrEmpty(description)) return string.Empty;

            var formatted = description
                .Trim('\n', ' ')
                .Replace("\r\n", "\n")
                .Replace("\n", "<br/>")
                .Replace("[b][i]", "<strong><em>")
                .Replace("[i][b]", "<strong><em>")
                .Replace("[b]", "<strong>")
                .Replace("[i]", "<em>")
                .Replace("[/b][/i]", "</em></strong>")
                .Replace("[/i][/b]", "</em></strong>")
                .Replace("[/b]", "</strong>")
                .Replace("[/i]", "</em>");

            const string replace = "<a href=\"$1\" target=\"_blank\">$2</a>";

            formatted = _urlRegex.Replace(formatted, replace);

            return formatted;
        }

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

protected override bool TryCreateHandler(OrganizationServiceContext context, string logicalName, Guid id, out IHttpHandler handler)
		{
			if (string.Equals(logicalName, "annotation", StringComparison.InvariantCulture))
			{
				var annotation = context.CreateQuery(logicalName).FirstOrDefault(e => e.GetAttributeValue<Guid>("annotationid") == id);

				if (annotation != null)
				{
					var regarding = annotation.GetAttributeValue<EnreplacedyReference>("objectid");

					if (regarding != null && string.Equals(regarding.LogicalName, "knowledgearticle", StringComparison.InvariantCulture))
					{
						// Access to a note replacedociated to a knowledge article requires the CMS Security to grant read of the annotation and the related knowledge article. 
						// Additionally, if CAL or Product filtering is enabled and the CAL and/or Product providers reject access to the knowledge article 
						// then access to the note is denied. If CAL and Product filtering are NOT enabled or CAL and/or Product Provider replacedertion preplaceded, 
						// we must continue to check the Enreplacedy Permissions. If the Enreplacedy Permission Provider grants read to the knowledge article then the 
						// note can be accessed, otherwise access will be denied.

						// replacedert CMS Security on the annotation and knowledge article.
						if (TryreplacedertByCrmEnreplacedySecurityProvider(context, annotation.ToEnreplacedyReference()) && TryreplacedertByCrmEnreplacedySecurityProvider(context, regarding))
						{
							// replacedert CAL and/or Product Filtering if enabled.
							var contentAccessLevelProvider = new ContentAccessLevelProvider();
							var productAccessProvider = new ProductAccessProvider();

							if (contentAccessLevelProvider.IsEnabled() || productAccessProvider.IsEnabled())
							{
								if (!replacedertKnowledgeArticleCalAndProductFiltering(annotation, context, contentAccessLevelProvider, productAccessProvider))
								{
									ADXTrace.Instance.TraceInfo(TraceCategory.Application, $"Access to {EnreplacedyNamePrivacy.GetEnreplacedyName(annotation.LogicalName)} was denied. Id:{id} RegardingId={regarding.Id} RegardingLogicalName={EnreplacedyNamePrivacy.GetEnreplacedyName(regarding.LogicalName)}");
									handler = null;
									return false;
								}
							}

							// replacedert Enreplacedy Permissions on the knowledge article.
							if (TryreplacedertByCrmEnreplacedyPermissionProvider(context, regarding))
							{
								ADXTrace.Instance.TraceInfo(TraceCategory.Application, $"Access to {EnreplacedyNamePrivacy.GetEnreplacedyName(annotation.LogicalName)} was granted. Id:{id} RegardingId={regarding.Id} RegardingLogicalName={EnreplacedyNamePrivacy.GetEnreplacedyName(regarding.LogicalName)}");
								handler = CreateAnnotationHandler(annotation);
								return true;
							}
						}

						ADXTrace.Instance.TraceInfo(TraceCategory.Application, $"Access to {EnreplacedyNamePrivacy.GetEnreplacedyName(annotation.LogicalName)} was denied. Id:{id} RegardingId={regarding.Id} RegardingLogicalName={EnreplacedyNamePrivacy.GetEnreplacedyName(regarding.LogicalName)}");
						handler = null;
						return false;
					}

					// replacedert CMS security on the regarding enreplacedy or replacedert enreplacedy permission on the annotation and the regarding enreplacedy.
					if (TryreplacedertByCrmEnreplacedySecurityProvider(context, regarding) || TryreplacedertByCrmEnreplacedyPermissionProvider(context, annotation, regarding))
					{
						ADXTrace.Instance.TraceInfo(TraceCategory.Application, $"Access to {EnreplacedyNamePrivacy.GetEnreplacedyName(annotation.LogicalName)} was granted. Id={id} RegardingId={regarding?.Id} RegardingLogicalName={EnreplacedyNamePrivacy.GetEnreplacedyName(regarding?.LogicalName)}");
						handler = CreateAnnotationHandler(annotation);
						return true;
					}
				}
			}

			if (string.Equals(logicalName, "salesliteratureitem", StringComparison.InvariantCulture))
			{
				var salesliteratureitem = context.CreateQuery(logicalName).FirstOrDefault(e => e.GetAttributeValue<Guid>("salesliteratureitemid") == id);

				if (salesliteratureitem != null)
				{
					//Currently salesliteratureitem.iscustomerviewable is not exposed to CRM UI, therefore get the parent and check visibility.
					//var isCustomerViewable = salesliteratureitem.GetAttributeValue<bool?>("iscustomerviewable").GetValueOrDefault();
					var salesliterature =
						context.CreateQuery("salesliterature")
						       .FirstOrDefault(
							       e =>
							       e.GetAttributeValue<Guid>("salesliteratureid") ==
							       salesliteratureitem.GetAttributeValue<EnreplacedyReference>("salesliteratureid").Id);

					if (salesliterature != null)
					{
						var isCustomerViewable = salesliterature.GetAttributeValue<bool?>("iscustomerviewable").GetValueOrDefault();

						if (isCustomerViewable)
						{
							handler = CreateSalesAttachmentHandler(salesliteratureitem);
							return true;
						}
					}
				}
			}

			if (string.Equals(logicalName, "sharepointdoreplacedentlocation", StringComparison.InvariantCulture))
			{
				var location = context.CreateQuery(logicalName).FirstOrDefault(e => e.GetAttributeValue<Guid>("sharepointdoreplacedentlocationid") == id);

				if (location != null)
				{
					var httpContext = HttpContext.Current;
					var regardingId = location.GetAttributeValue<EnreplacedyReference>("regardingobjectid");

					// replacedert CMS access to the regarding enreplacedy or replacedert enreplacedy permission on the enreplacedy
					if (TryreplacedertByCrmEnreplacedySecurityProvider(context, regardingId) || TryreplacedertByCrmEnreplacedyPermissionProvider(context, location, location.GetAttributeValue<EnreplacedyReference>("regardingobjectid")))
					{
						var locationUrl = context.GetDoreplacedentLocationUrl(location);
						var fileName = httpContext.Request["file"];
						
						// Ensure safe file URL - it cannot begin or end with dot, contain consecutive dots, or any of ~ " # % & * : < > ? \ { | }
						fileName = Regex.Replace(fileName, @"(\.{2,})|([\~\""\#\%\&\*\:\<\>\?\/\\\{\|\}])|(^\.)|(\.$)", string.Empty); // also removes solidus

						var folderPath = httpContext.Request["folderPath"];
						
						Uri sharePointFileUrl;

						if (!string.IsNullOrWhiteSpace(folderPath))
						{
							// Ensure safe folder URL - it cannot begin or end with dot, contain consecutive dots, or any of ~ " # % & * : < > ? \ { | }
							folderPath = Regex.Replace(folderPath, @"(\.{2,})|([\~\""\#\%\&\*\:\<\>\?\\\{\|\}])|(^\.)|(\.$)", string.Empty).Trim('/');

							sharePointFileUrl = new Uri("{0}/{1}/{2}".FormatWith(locationUrl.OriginalString, folderPath, fileName));
						}
						else
						{
							sharePointFileUrl = new Uri("{0}/{1}".FormatWith(locationUrl.OriginalString, fileName));
						}

						

						handler = CreateSharePointFileHandler(sharePointFileUrl, fileName);
						return true;
					}

					if (!httpContext.Request.IsAuthenticated)
					{
						httpContext.Response.ForbiddenAndEndResponse();
					}
					else
					{
						// Sending Forbidden gets caught by the Application_EndRequest and throws an error trying to redirect to the Access Denied page.
						// Send a 404 instead with plain text indicating Access Denied.
						httpContext.Response.StatusCode = (int)HttpStatusCode.NotFound;
						httpContext.Response.ContentType = "text/plain";
						httpContext.Response.Write("Access Denied");
						httpContext.Response.End();
					}
				}
			}

			if (string.Equals(logicalName, "activitymimeattachment", StringComparison.InvariantCulture))
			{
				var attachment = context.CreateQuery(logicalName).FirstOrDefault(e => e.GetAttributeValue<Guid>("attachmentid") == id);

				if (attachment != null)
				{
					// retrieve the parent object for the annoation

					var objectId = attachment.GetAttributeValue<EnreplacedyReference>("objectid");

					// replacedert CMS access to the regarding enreplacedy or replacedert enreplacedy permission on the enreplacedy

					if (TryreplacedertByCrmEnreplacedySecurityProvider(context, objectId) || TryreplacedertByCrmEnreplacedyPermissionProvider(context, attachment, attachment.GetAttributeValue<EnreplacedyReference>("objectid")))
					{
						handler = CreateActivityMimeAttachmentHandler(attachment);
						return true;
					}
				}
			}

			handler = null;
			return false;
		}

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

private Expression ResovleConstantExpression(string expression)
        {
            //自动类型推断生成表达式
            if (expression.StartsWith("'") && expression.EndsWith("'"))
            {
                //字符串常量
                return Expression.Constant(expression.Trim('\''), typeof(string));
            }
            else if (expression == "true" || expression == "false")
            {
                return Expression.Constant(expression, typeof(bool));
            }
            else if (Regex.IsMatch(expression, @"^\d+$"))
            {
                //int类型常量
                return Expression.Constant(expression, typeof(int));
            }
            else if (Regex.IsMatch(expression, @"^\d*\.\d*$"))
            {
                //double
                return Expression.Constant(expression, typeof(int));
            }
            else if (expression == "null")
            {
                return Expression.Constant(null, typeof(object));
            }
            return Expression.Constant(expression, typeof(object));
        }

19 View Source File : AssetManager.cs
License : MIT License
Project Creator : Adsito

public static IEnumerator SetMaterials(int materialID)
		{
			if (File.Exists(MaterialsListPath))
			{
				Shader std = Shader.Find("Standard");
				Shader spc = Shader.Find("Standard (Specular setup)");
				string[] materials = File.ReadAllLines(MaterialsListPath);
				for (int i = 0; i < materials.Length; i++)
				{
					var lineSplit = materials[i].Split(':');
					lineSplit[0] = lineSplit[0].Trim(' '); // Shader Name
					lineSplit[1] = lineSplit[1].Trim(' '); // Material Path
					Progress.Report(materialID, (float)i / materials.Length, "Setting: " + lineSplit[1]);
					switch (lineSplit[0])
					{
						case "Standard":
							Material matStd = Loadreplacedet<Material>(lineSplit[1]);
							if (matStd == null)
                            {
								Debug.LogWarning(lineSplit[1] + " is not a valid replacedet.");
								break;
                            }
							EditorCoroutineUtility.StartCoroutineOwnerless(UpdateShader(matStd, std));
							break;

						case "Specular":
							Material matSpc= Loadreplacedet<Material>(lineSplit[1]);
							if (matSpc == null)
							{
								Debug.LogWarning(lineSplit[1] + " is not a valid replacedet.");
								break;
							}
							EditorCoroutineUtility.StartCoroutineOwnerless(UpdateShader(matSpc, spc));
							break;

						case "Foliage":
							Material mat = Loadreplacedet<Material>(lineSplit[1]);
							if(mat == null)
                            {
								Debug.LogWarning(lineSplit[1] + " is not a valid replacedet.");
								break;
							}
							mat.DisableKeyword("_TINTENABLED_ON");
							break;

						default:
							Debug.LogWarning(lineSplit[0] + " is not a valid shader.");
							break;
					}
					yield return null;
				}
				Progress.Report(materialID, 0.99f, "Set " + materials.Length + " materials.");
				Progress.Finish(materialID, Progress.Status.Succeeded);
			}
		}

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

private string SimplifyDescription(string formattedDescription)
        {
            if (string.IsNullOrEmpty(formattedDescription)) return string.Empty;

            var formatted = formattedDescription
                .Trim('\n', ' ')
                .Replace("\r\n", "\n")
                .Replace("\n", " ")
                .Replace("    ", " ")
                .Replace("   ", " ")
                .Replace("  ", " ")
                .Replace("[b]", string.Empty)
                .Replace("[/b]", string.Empty)
                .Replace("[i]", string.Empty)
                .Replace("[i]", string.Empty)
                .Trim();

            formatted = _urlRegex.Replace(formatted, "$2");

            return formatted;
        }

19 View Source File : ObjLoader.cs
License : The Unlicense
Project Creator : aeroson

Mesh Parse(Resource resource, GameObject appendToGameObject)
        {
            using (StreamReader textReader = new StreamReader(resource))
            {

                int i1, i2, i3, i4;

                string line;
                while ((line = textReader.ReadLine()) != null)
                {
                    line = line.Trim(trimCharacters);
                    line = line.Replace("  ", " ");

                    string[] parameters = line.Split(splitCharacters);

                    switch (parameters[0])
                    {
                        case "p": // Point
                            break;

                        case "v": // Vertex
                            var v = Vector3.Zero;
                            Parse(ref parameters[1], ref v.X);
                            Parse(ref parameters[2], ref v.Y);
                            Parse(ref parameters[3], ref v.Z);
                            verticesObj.Add(v);
                            break;

                        case "vt": // TexCoord
                            gotUvs = true;
                            var vt = Vector2.Zero;
                            Parse(ref parameters[1], ref vt.X);
                            Parse(ref parameters[2], ref vt.Y);
                            uvsObj.Add(vt);
                            break;

                        case "vn": // Normal
                            gotNormal = true;
                            var vn = Vector3.Zero;
                            Parse(ref parameters[1], ref vn.X);
                            Parse(ref parameters[2], ref vn.Y);
                            Parse(ref parameters[3], ref vn.Z);
                            normalsObj.Add(vn);
                            break;

                        case "f":
                            switch (parameters.Length)
                            {
                                case 4:
                                    i1 = ParseFaceParameter(parameters[1]);
                                    i2 = ParseFaceParameter(parameters[2]);
                                    i3 = ParseFaceParameter(parameters[3]);
                                    triangleIndiciesMesh.Add(i1);
                                    triangleIndiciesMesh.Add(i2);
                                    triangleIndiciesMesh.Add(i3);
                                    break;

                                case 5:
                                    i1 = ParseFaceParameter(parameters[1]);
                                    i2 = ParseFaceParameter(parameters[2]);
                                    i3 = ParseFaceParameter(parameters[3]);
                                    i4 = ParseFaceParameter(parameters[4]);
                                    triangleIndiciesMesh.Add(i1);
                                    triangleIndiciesMesh.Add(i2);
                                    triangleIndiciesMesh.Add(i3);
                                    triangleIndiciesMesh.Add(i1);
                                    triangleIndiciesMesh.Add(i3);
                                    triangleIndiciesMesh.Add(i4);
                                    break;
                            }
                            break;
                        case "mtllib":
                            if (Resource.ResourceInFolderExists(resource, parameters[1]))
                            {
                                materialLibrary = new MaterialLibrary(Resource.GetResourceInFolder(resource, parameters[1]));
                            }
                            break;
                        case "usemtl":
                            if (materialLibrary!=null) lastMaterial = materialLibrary.GetMat(parameters[1]);
                            break;
                    }
                }

                textReader.Close();
            }


            if(appendToGameObject!=null) return EndObjPart(appendToGameObject);

            Debug.Info("Loaded " + resource.originalPath + " vertices:" + verticesMesh.Count + " faces:" + triangleIndiciesMesh.Count / 3);

            return EndMesh();
    
        }

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

private Expression CreateExpression(ParameterExpression parameter, string expression)
        {
            var expressions1 = Factorization(expression);
            var expressions2 = new Dictionary<string, Expression>();
            foreach (var item in expressions1)
            {
                var subexpr = item.Value.Trim('(', ')');
                var @opterator = ResovleOperator(item.Value);
                var opt = GetExpressionType(@opterator);
                if (opt == ExpressionType.Not)
                {
                    Expression exp;
                    var text = subexpr.Split(new string[] { @opterator }, StringSplitOptions.RemoveEmptyEntries)[0].Trim();
                    if (expressions2.ContainsKey(text))
                    {
                        exp = expressions2[text];
                    }
                    else if (parameter.Type.GetProperties().Any(a => a.Name == text))
                    {
                        var property = parameter.Type.GetProperty(text);
                        exp = Expression.MakeMemberAccess(parameter, property);
                    }
                    else
                    {
                        exp = Expression.Constant(Convert.ToBoolean(text));
                    }
                    expressions2.Add(item.Key, Expression.MakeUnary(opt, exp, null));
                }
                else
                {
                    var text1 = subexpr
                        .Split(new string[] { @opterator }, StringSplitOptions.RemoveEmptyEntries)[0]
                        .Trim();
                    var text2 = subexpr
                        .Split(new string[] { @opterator }, StringSplitOptions.RemoveEmptyEntries)[1]
                        .Trim();
                    string temp = null;
                    Expression exp1, exp2;
                    //永远将变量放在第一个操作数
                    if (parameter.Type.GetProperties().Any(a => a.Name == text2))
                    {
                        temp = text1;
                        text1 = text2;
                        text2 = temp;
                    }
                    //是否为上一次的分式
                    if (expressions2.ContainsKey(text1))
                    {
                        exp1 = expressions2[text1];
                    }
                    else if (parameter.Type.GetProperties().Any(a => a.Name == text1))
                    {
                        //是否为变量
                        var property = parameter.Type.GetProperty(text1);
                        exp1 = Expression.MakeMemberAccess(parameter, property);
                    }
                    else
                    {
                        exp1 = ResovleConstantExpression(text1);
                    }
                    //是否为上一次的分式
                    if (expressions2.ContainsKey(text2))
                    {
                        exp2 = expressions2[text2];
                    }
                    //如果第一个操作数是变量
                    else if (parameter.Type.GetProperties().Any(a => a.Name == text1))
                    {
                        var constantType = parameter.Type.GetProperty(text1).PropertyType;
                        exp2 = ResovleConstantExpression(text2, constantType);
                    }
                    else
                    {
                        exp2 = ResovleConstantExpression(text1, (exp1 as ConstantExpression)?.Type);
                    }
                    expressions2.Add(item.Key, Expression.MakeBinary(opt, exp1, exp2));
                }
            }
            return expressions2.Last().Value;
        }

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

public List<T>  ToArray<T>(string name,Func<string,T> parse)
        {
            var cs = GetValue(name);
            if (string.IsNullOrWhiteSpace(cs))
            {
                return null;
            }
            var css = cs.Trim('[', ']').Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            return css.Length > 0 ? css.Select(parse).ToList() : null;
        }

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

public async Task GetSourceAsync(
            RunnerActionPluginExecutionContext executionContext,
            string repositoryPath,
            string repoFullName,
            string sourceBranch,
            string sourceVersion,
            bool clean,
            string submoduleInput,
            int fetchDepth,
            bool gitLfsSupport,
            string accessToken,
            CancellationToken cancellationToken)
        {
            // Validate args.
            ArgUtil.NotNull(executionContext, nameof(executionContext));
            Dictionary<string, string> configModifications = new Dictionary<string, string>();
            executionContext.Output($"Syncing repository: {repoFullName}");
            Uri repositoryUrl = new Uri($"https://github.com/{repoFullName}");
            if (!repositoryUrl.IsAbsoluteUri)
            {
                throw new InvalidOperationException("Repository url need to be an absolute uri.");
            }

            string targetPath = repositoryPath;

            // input Submodules can be ['', true, false, recursive]
            // '' or false indicate don't checkout submodules
            // true indicate checkout top level submodules
            // recursive indicate checkout submodules recursively 
            bool checkoutSubmodules = false;
            bool checkoutNestedSubmodules = false;
            if (!string.IsNullOrEmpty(submoduleInput))
            {
                if (string.Equals(submoduleInput, Pipelines.PipelineConstants.CheckoutTaskInputs.SubmodulesOptions.Recursive, StringComparison.OrdinalIgnoreCase))
                {
                    checkoutSubmodules = true;
                    checkoutNestedSubmodules = true;
                }
                else
                {
                    checkoutSubmodules = StringUtil.ConvertToBoolean(submoduleInput);
                }
            }

            executionContext.Debug($"repository url={repositoryUrl}");
            executionContext.Debug($"targetPath={targetPath}");
            executionContext.Debug($"sourceBranch={sourceBranch}");
            executionContext.Debug($"sourceVersion={sourceVersion}");
            executionContext.Debug($"clean={clean}");
            executionContext.Debug($"checkoutSubmodules={checkoutSubmodules}");
            executionContext.Debug($"checkoutNestedSubmodules={checkoutNestedSubmodules}");
            executionContext.Debug($"fetchDepth={fetchDepth}");
            executionContext.Debug($"gitLfsSupport={gitLfsSupport}");

            // Initialize git command manager with additional environment variables.
            Dictionary<string, string> gitEnv = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);

            // Disable git prompt
            gitEnv["GIT_TERMINAL_PROMPT"] = "0";

            // Disable prompting for git credential manager
            gitEnv["GCM_INTERACTIVE"] = "Never";

            // Git-lfs will try to pull down replacedet if any of the local/user/system setting exist.
            // If customer didn't enable `LFS` in their pipeline definition, we will use ENV to disable LFS fetch/checkout.
            if (!gitLfsSupport)
            {
                gitEnv["GIT_LFS_SKIP_SMUDGE"] = "1";
            }

            // Add the public variables.
            foreach (var variable in executionContext.Variables)
            {
                // Add the variable using the formatted name.
                string formattedKey = (variable.Key ?? string.Empty).Replace('.', '_').Replace(' ', '_').ToUpperInvariant();
                gitEnv[formattedKey] = variable.Value?.Value ?? string.Empty;
            }

            GitCliManager gitCommandManager = new GitCliManager(gitEnv);
            await gitCommandManager.LoadGitExecutionInfo(executionContext);

            // Make sure the build machine met all requirements for the git repository
            // For now, the requirement we have are:
            // 1. git version greater than 2.9 since we need to use auth header.
            // 2. git-lfs version greater than 2.1 since we need to use auth header.
            // 3. git version greater than 2.14.2 if use SChannel for SSL backend (Windows only)
            RequirementCheck(executionContext, gitCommandManager, gitLfsSupport);

            // prepare askpreplaced for client cert private key, if the repository's endpoint url match the runner config url
            var systemConnection = executionContext.Endpoints.Single(x => string.Equals(x.Name, WellKnownServiceEndpointNames.SystemVssConnection, StringComparison.OrdinalIgnoreCase));

            // Check the current contents of the root folder to see if there is already a repo
            // If there is a repo, see if it matches the one we are expecting to be there based on the remote fetch url
            // if the repo is not what we expect, remove the folder
            if (!await IsRepositoryOriginUrlMatch(executionContext, gitCommandManager, targetPath, repositoryUrl))
            {
                // Delete source folder
                IOUtil.DeleteDirectory(targetPath, cancellationToken);
            }
            else
            {
                // delete the index.lock file left by previous canceled build or any operation cause git.exe crash last time.
                string lockFile = Path.Combine(targetPath, ".git\\index.lock");
                if (File.Exists(lockFile))
                {
                    try
                    {
                        File.Delete(lockFile);
                    }
                    catch (Exception ex)
                    {
                        executionContext.Debug($"Unable to delete the index.lock file: {lockFile}");
                        executionContext.Debug(ex.ToString());
                    }
                }

                // delete the shallow.lock file left by previous canceled build or any operation cause git.exe crash last time.		
                string shallowLockFile = Path.Combine(targetPath, ".git\\shallow.lock");
                if (File.Exists(shallowLockFile))
                {
                    try
                    {
                        File.Delete(shallowLockFile);
                    }
                    catch (Exception ex)
                    {
                        executionContext.Debug($"Unable to delete the shallow.lock file: {shallowLockFile}");
                        executionContext.Debug(ex.ToString());
                    }
                }

                // When repo.clean is selected for a git repo, execute git clean -ffdx and git reset --hard HEAD on the current repo.
                // This will help us save the time to reclone the entire repo.
                // If any git commands exit with non-zero return code or any exception happened during git.exe invoke, fall back to delete the repo folder.
                if (clean)
                {
                    Boolean softCleanSucceed = true;

                    // git clean -ffdx
                    int exitCode_clean = await gitCommandManager.GitClean(executionContext, targetPath);
                    if (exitCode_clean != 0)
                    {
                        executionContext.Debug($"'git clean -ffdx' failed with exit code {exitCode_clean}, this normally caused by:\n    1) Path too long\n    2) Permission issue\n    3) File in use\nFor futher investigation, manually run 'git clean -ffdx' on repo root: {targetPath} after each build.");
                        softCleanSucceed = false;
                    }

                    // git reset --hard HEAD
                    if (softCleanSucceed)
                    {
                        int exitCode_reset = await gitCommandManager.GitReset(executionContext, targetPath);
                        if (exitCode_reset != 0)
                        {
                            executionContext.Debug($"'git reset --hard HEAD' failed with exit code {exitCode_reset}\nFor futher investigation, manually run 'git reset --hard HEAD' on repo root: {targetPath} after each build.");
                            softCleanSucceed = false;
                        }
                    }

                    // git clean -ffdx and git reset --hard HEAD for each submodule
                    if (checkoutSubmodules)
                    {
                        if (softCleanSucceed)
                        {
                            int exitCode_submoduleclean = await gitCommandManager.GitSubmoduleClean(executionContext, targetPath);
                            if (exitCode_submoduleclean != 0)
                            {
                                executionContext.Debug($"'git submodule foreach git clean -ffdx' failed with exit code {exitCode_submoduleclean}\nFor futher investigation, manually run 'git submodule foreach git clean -ffdx' on repo root: {targetPath} after each build.");
                                softCleanSucceed = false;
                            }
                        }

                        if (softCleanSucceed)
                        {
                            int exitCode_submodulereset = await gitCommandManager.GitSubmoduleReset(executionContext, targetPath);
                            if (exitCode_submodulereset != 0)
                            {
                                executionContext.Debug($"'git submodule foreach git reset --hard HEAD' failed with exit code {exitCode_submodulereset}\nFor futher investigation, manually run 'git submodule foreach git reset --hard HEAD' on repo root: {targetPath} after each build.");
                                softCleanSucceed = false;
                            }
                        }
                    }

                    if (!softCleanSucceed)
                    {
                        //fall back
                        executionContext.Warning("Unable to run \"git clean -ffdx\" and \"git reset --hard HEAD\" successfully, delete source folder instead.");
                        IOUtil.DeleteDirectory(targetPath, cancellationToken);
                    }
                }
            }

            // if the folder is missing, create it
            if (!Directory.Exists(targetPath))
            {
                Directory.CreateDirectory(targetPath);
            }

            // if the folder contains a .git folder, it means the folder contains a git repo that matches the remote url and in a clean state.
            // we will run git fetch to update the repo.
            if (!Directory.Exists(Path.Combine(targetPath, ".git")))
            {
                // init git repository
                int exitCode_init = await gitCommandManager.GitInit(executionContext, targetPath);
                if (exitCode_init != 0)
                {
                    throw new InvalidOperationException($"Unable to use git.exe init repository under {targetPath}, 'git init' failed with exit code: {exitCode_init}");
                }

                int exitCode_addremote = await gitCommandManager.GitRemoteAdd(executionContext, targetPath, "origin", repositoryUrl.AbsoluteUri);
                if (exitCode_addremote != 0)
                {
                    throw new InvalidOperationException($"Unable to use git.exe add remote 'origin', 'git remote add' failed with exit code: {exitCode_addremote}");
                }
            }

            cancellationToken.ThrowIfCancellationRequested();

            // disable git auto gc
            int exitCode_disableGC = await gitCommandManager.GitDisableAutoGC(executionContext, targetPath);
            if (exitCode_disableGC != 0)
            {
                executionContext.Warning("Unable turn off git auto garbage collection, git fetch operation may trigger auto garbage collection which will affect the performance of fetching.");
            }

            // always remove any possible left extraheader setting from git config.
            if (await gitCommandManager.GitConfigExist(executionContext, targetPath, $"http.{repositoryUrl.AbsoluteUri}.extraheader"))
            {
                executionContext.Debug("Remove any extraheader setting from git config.");
                await RemoveGitConfig(executionContext, gitCommandManager, targetPath, $"http.{repositoryUrl.AbsoluteUri}.extraheader", string.Empty);
            }

            List<string> additionalFetchArgs = new List<string>();
            List<string> additionalLfsFetchArgs = new List<string>();

            // Add http.https://github.com.extraheader=... to gitconfig
            // accessToken as basic auth header to handle any auth challenge from github.com 
            string configKey = $"http.https://github.com/.extraheader";
            string configValue = $"\"AUTHORIZATION: {GenerateBasicAuthHeader(executionContext, accessToken)}\"";
            configModifications[configKey] = configValue.Trim('\"');
            int exitCode_config = await gitCommandManager.GitConfig(executionContext, targetPath, configKey, configValue);
            if (exitCode_config != 0)
            {
                throw new InvalidOperationException($"Git config failed with exit code: {exitCode_config}");
            }

            // Prepare gitlfs url for fetch and checkout
            if (gitLfsSupport)
            {
                // Initialize git lfs by execute 'git lfs install'
                executionContext.Debug("Setup the local Git hooks for Git LFS.");
                int exitCode_lfsInstall = await gitCommandManager.GitLFSInstall(executionContext, targetPath);
                if (exitCode_lfsInstall != 0)
                {
                    throw new InvalidOperationException($"Git-lfs installation failed with exit code: {exitCode_lfsInstall}");
                }
            }

            List<string> additionalFetchSpecs = new List<string>();
            additionalFetchSpecs.Add("+refs/heads/*:refs/remotes/origin/*");

            if (IsPullRequest(sourceBranch))
            {
                additionalFetchSpecs.Add($"+{sourceBranch}:{GetRemoteRefName(sourceBranch)}");
            }

            int exitCode_fetch = await gitCommandManager.GitFetch(executionContext, targetPath, "origin", fetchDepth, additionalFetchSpecs, string.Join(" ", additionalFetchArgs), cancellationToken);
            if (exitCode_fetch != 0)
            {
                throw new InvalidOperationException($"Git fetch failed with exit code: {exitCode_fetch}");
            }

            // Checkout
            // sourceToBuild is used for checkout
            // if sourceBranch is a PR branch or sourceVersion is null, make sure branch name is a remote branch. we need checkout to detached head. 
            // (change refs/heads to refs/remotes/origin, refs/pull to refs/remotes/pull, or leave it as it when the branch name doesn't contain refs/...)
            // if sourceVersion provide, just use that for checkout, since when you checkout a commit, it will end up in detached head.
            cancellationToken.ThrowIfCancellationRequested();
            string sourcesToBuild;
            if (IsPullRequest(sourceBranch) || string.IsNullOrEmpty(sourceVersion))
            {
                sourcesToBuild = GetRemoteRefName(sourceBranch);
            }
            else
            {
                sourcesToBuild = sourceVersion;
            }

            // fetch lfs object upfront, this will avoid fetch lfs object during checkout which cause checkout taking forever
            // since checkout will fetch lfs object 1 at a time, while git lfs fetch will fetch lfs object in parallel.
            if (gitLfsSupport)
            {
                int exitCode_lfsFetch = await gitCommandManager.GitLFSFetch(executionContext, targetPath, "origin", sourcesToBuild, string.Join(" ", additionalLfsFetchArgs), cancellationToken);
                if (exitCode_lfsFetch != 0)
                {
                    // local repository is shallow repository, lfs fetch may fail due to lack of commits history.
                    // this will happen when the checkout commit is older than tip -> fetchDepth
                    if (fetchDepth > 0)
                    {
                        executionContext.Warning($"Git lfs fetch failed on shallow repository, this might because of git fetch with depth '{fetchDepth}' doesn't include the lfs fetch commit '{sourcesToBuild}'.");
                    }

                    // git lfs fetch failed, get lfs log, the log is critical for debug.
                    int exitCode_lfsLogs = await gitCommandManager.GitLFSLogs(executionContext, targetPath);
                    throw new InvalidOperationException($"Git lfs fetch failed with exit code: {exitCode_lfsFetch}. Git lfs logs returned with exit code: {exitCode_lfsLogs}.");
                }
            }

            // Finally, checkout the sourcesToBuild (if we didn't find a valid git object this will throw)
            int exitCode_checkout = await gitCommandManager.GitCheckout(executionContext, targetPath, sourcesToBuild, cancellationToken);
            if (exitCode_checkout != 0)
            {
                // local repository is shallow repository, checkout may fail due to lack of commits history.
                // this will happen when the checkout commit is older than tip -> fetchDepth
                if (fetchDepth > 0)
                {
                    executionContext.Warning($"Git checkout failed on shallow repository, this might because of git fetch with depth '{fetchDepth}' doesn't include the checkout commit '{sourcesToBuild}'.");
                }

                throw new InvalidOperationException($"Git checkout failed with exit code: {exitCode_checkout}");
            }

            // Submodule update
            if (checkoutSubmodules)
            {
                cancellationToken.ThrowIfCancellationRequested();

                int exitCode_submoduleSync = await gitCommandManager.GitSubmoduleSync(executionContext, targetPath, checkoutNestedSubmodules, cancellationToken);
                if (exitCode_submoduleSync != 0)
                {
                    throw new InvalidOperationException($"Git submodule sync failed with exit code: {exitCode_submoduleSync}");
                }

                List<string> additionalSubmoduleUpdateArgs = new List<string>();

                int exitCode_submoduleUpdate = await gitCommandManager.GitSubmoduleUpdate(executionContext, targetPath, fetchDepth, string.Join(" ", additionalSubmoduleUpdateArgs), checkoutNestedSubmodules, cancellationToken);
                if (exitCode_submoduleUpdate != 0)
                {
                    throw new InvalidOperationException($"Git submodule update failed with exit code: {exitCode_submoduleUpdate}");
                }
            }

            // Set intra-task variable for post job cleanup
            executionContext.SetIntraActionState("repositoryPath", targetPath);
            executionContext.SetIntraActionState("modifiedgitconfig", JsonUtility.ToString(configModifications.Keys));
            foreach (var config in configModifications)
            {
                executionContext.SetIntraActionState(config.Key, config.Value);
            }
        }

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

private string ConvertExpression(Expression expression)
        {
            var binaryExpression = expression as BinaryExpression;
            if (binaryExpression != null)
            {
                return Convert(binaryExpression);
            }
            var unary = expression as UnaryExpression;
            if (unary != null)
            {
                return Convert(unary);
            }
            var call = expression as MethodCallExpression;
            if (call != null)
            {
                return Convert(call);
            }
            var memberExpression = expression as MemberExpression;
            if (memberExpression != null)
            {
                return Convert(memberExpression);
            }
            var constantExpression = expression as ConstantExpression;
            if (constantExpression != null)
            {
                return Convert(constantExpression);
            }
            var array = expression as NewArrayExpression;
            if (array != null)
            {
                var sb = new StringBuilder();
                foreach (var arg in array.Expressions)
                {
                    sb.AppendFormat(",{0}", ConvertExpression(arg));
                }
                return sb.ToString().Trim(',');
            }
            if (expression.NodeType == ExpressionType.IsTrue)
            {
                return "1";
            }
            if (expression.NodeType == ExpressionType.IsFalse)
            {
                return "0";
            }
            throw new ArgumentException("Invalid lambda expression");
        }

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

private string ResolveUpdate()
        {
            var table = GetTableMetaInfo().TableName;
            var builder = new StringBuilder();
            if (_setExpressions.Count > 0)
            {
                var where = ResolveWhere();
                foreach (var item in _setExpressions)
                {
                    var column = new BooleanExpressionResovle(item.Column).Resovle();
                    var expression = new BooleanExpressionResovle(item.Expression, _parameters).Resovle();
                    builder.Append($"{column} = {expression},");
                }
                var sql = $"UPDATE {table} SET {builder.ToString().Trim(',')}{where}";
                return sql;
            }
            else
            {
                var filters = new GroupExpressionResovle(_filterExpression).Resovle().Split(',');
                var where = ResolveWhere();
                var columns = GetColumnMetaInfos();
                var updcolumns = columns
                    .Where(a => !filters.Contains(a.ColumnName))
                    .Where(a => !a.IsComplexType)
                    .Where(a => !a.IsIdenreplacedy && !a.IsPrimaryKey && !a.IsNotMapped)
                    .Where(a => !a.IsConcurrencyCheck)
                    .Select(s => $"{s.ColumnName} = @{s.CsharpName}");
                if (string.IsNullOrEmpty(where))
                {
                    var primaryKey = columns.Where(a => a.IsPrimaryKey).FirstOrDefault()
                        ?? columns.First();
                    where = $" WHERE {primaryKey.ColumnName} = @{primaryKey.CsharpName}";
                    if (columns.Exists(a => a.IsConcurrencyCheck))
                    {
                        var checkColumn = columns.Where(a => a.IsConcurrencyCheck).FirstOrDefault();
                        where += $" AND {checkColumn.ColumnName} = @{checkColumn.CsharpName}";
                    }
                }
                var sql = $"UPDATE {table} SET {string.Join(",", updcolumns)}";
                if (columns.Exists(a => a.IsConcurrencyCheck))
                {
                    var checkColumn = columns.Where(a => a.IsConcurrencyCheck).FirstOrDefault();
                    sql += $",{checkColumn.ColumnName} = @New{checkColumn.CsharpName}";
                    if (checkColumn.CsharpType.IsValueType)
                    {
                        var version = Convert.ToInt32((DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0)).TotalSeconds);
                        _parameters.Add($"New{checkColumn.CsharpName}", version);
                    }
                    else
                    {
                        var version = Guid.NewGuid().ToString("N");
                        _parameters.Add($"New{checkColumn.CsharpName}", version);
                    }
                }
                sql += where;
                return sql;
            }
        }

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

public static string ToBj(string s)
        {
            if(string.IsNullOrWhiteSpace(s))
            {
                return s ;
            }
            s = s.Trim();
            var sb = new StringBuilder(s.Length) ;
            foreach(var t in s)
            {
                switch(t)
                {
                case '\u3000' :
                    sb.Append('\u0020') ;
                    break ;
                default :
                    if(IsQjChar(t))
                    {
                        sb.Append((char) (t - 65248)) ;
                    }
                    else
                    {
                        sb.Append(t) ;
                    }
                    break ;
                }
            }
            return sb.ToString().Trim(' ', '\r', '\n', '\t') ;
        }

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

public async Task RunAsync(RunnerActionPluginExecutionContext executionContext, CancellationToken token)
        {
            string runnerWorkspace = executionContext.GetRunnerContext("workspace");
            ArgUtil.Directory(runnerWorkspace, nameof(runnerWorkspace));
            string tempDirectory = executionContext.GetRunnerContext("temp");
            ArgUtil.Directory(tempDirectory, nameof(tempDirectory));

            var repoFullName = executionContext.GetInput(Pipelines.PipelineConstants.CheckoutTaskInputs.Repository);
            if (string.IsNullOrEmpty(repoFullName))
            {
                repoFullName = executionContext.GetGitHubContext("repository");
            }

            var repoFullNameSplit = repoFullName.Split("/", StringSplitOptions.RemoveEmptyEntries);
            if (repoFullNameSplit.Length != 2)
            {
                throw new ArgumentOutOfRangeException(repoFullName);
            }

            string expectRepoPath;
            var path = executionContext.GetInput(Pipelines.PipelineConstants.CheckoutTaskInputs.Path);
            if (!string.IsNullOrEmpty(path))
            {
                expectRepoPath = IOUtil.ResolvePath(runnerWorkspace, path);
                if (!expectRepoPath.StartsWith(runnerWorkspace.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar))
                {
                    throw new ArgumentException($"Input path '{path}' should resolve to a directory under '{runnerWorkspace}', current resolved path '{expectRepoPath}'.");
                }
            }
            else
            {
                // When repository doesn't has path set, default to sources directory 1/repoName
                expectRepoPath = Path.Combine(runnerWorkspace, repoFullNameSplit[1]);
            }

            var workspaceRepo = executionContext.GetGitHubContext("repository");
            // for self repository, we need to let the worker knows where it is after checkout.
            if (string.Equals(workspaceRepo, repoFullName, StringComparison.OrdinalIgnoreCase))
            {
                var workspaceRepoPath = executionContext.GetGitHubContext("workspace");

                executionContext.Debug($"Repository requires to be placed at '{expectRepoPath}', current location is '{workspaceRepoPath}'");
                if (!string.Equals(workspaceRepoPath.Trim(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar), expectRepoPath.Trim(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar), IOUtil.FilePathStringComparison))
                {
                    executionContext.Output($"Repository is current at '{workspaceRepoPath}', move to '{expectRepoPath}'.");
                    var count = 1;
                    var staging = Path.Combine(tempDirectory, $"_{count}");
                    while (Directory.Exists(staging))
                    {
                        count++;
                        staging = Path.Combine(tempDirectory, $"_{count}");
                    }

                    try
                    {
                        executionContext.Debug($"Move existing repository '{workspaceRepoPath}' to '{expectRepoPath}' via staging directory '{staging}'.");
                        IOUtil.MoveDirectory(workspaceRepoPath, expectRepoPath, staging, CancellationToken.None);
                    }
                    catch (Exception ex)
                    {
                        executionContext.Debug("Catch exception during repository move.");
                        executionContext.Debug(ex.ToString());
                        executionContext.Warning("Unable move and reuse existing repository to required location.");
                        IOUtil.DeleteDirectory(expectRepoPath, CancellationToken.None);
                    }

                    executionContext.Output($"Repository will locate at '{expectRepoPath}'.");
                }

                executionContext.Debug($"Update workspace repository location.");
                executionContext.SetRepositoryPath(repoFullName, expectRepoPath, true);
            }

            string sourceBranch;
            string sourceVersion;
            string refInput = executionContext.GetInput(Pipelines.PipelineConstants.CheckoutTaskInputs.Ref);
            if (string.IsNullOrEmpty(refInput))
            {
                sourceBranch = executionContext.GetGitHubContext("ref");
                sourceVersion = executionContext.GetGitHubContext("sha");
            }
            else
            {
                sourceBranch = refInput;
                sourceVersion = executionContext.GetInput(Pipelines.PipelineConstants.CheckoutTaskInputs.Version);  // version get removed when checkout move to repo in the graph
                if (string.IsNullOrEmpty(sourceVersion) && RegexUtility.IsMatch(sourceBranch, WellKnownRegularExpressions.SHA1))
                {
                    sourceVersion = sourceBranch;

                    // If Ref is a SHA and the repo is self, we need to use github.ref as source branch since it might be refs/pull/*
                    if (string.Equals(workspaceRepo, repoFullName, StringComparison.OrdinalIgnoreCase))
                    {
                        sourceBranch = executionContext.GetGitHubContext("ref");
                    }
                    else
                    {
                        sourceBranch = "refs/heads/master";
                    }
                }
            }

            bool clean = StringUtil.ConvertToBoolean(executionContext.GetInput(Pipelines.PipelineConstants.CheckoutTaskInputs.Clean), true);
            string submoduleInput = executionContext.GetInput(Pipelines.PipelineConstants.CheckoutTaskInputs.Submodules);

            int fetchDepth = 0;
            if (!int.TryParse(executionContext.GetInput("fetch-depth"), out fetchDepth) || fetchDepth < 0)
            {
                fetchDepth = 0;
            }

            bool gitLfsSupport = StringUtil.ConvertToBoolean(executionContext.GetInput(Pipelines.PipelineConstants.CheckoutTaskInputs.Lfs));
            string accessToken = executionContext.GetInput(Pipelines.PipelineConstants.CheckoutTaskInputs.Token);
            if (string.IsNullOrEmpty(accessToken))
            {
                accessToken = executionContext.GetGitHubContext("token");
            }

            // register problem matcher
            string problemMatcher = @"    
{
    ""problemMatcher"": [
        {
            ""owner"": ""checkout-git"",
            ""pattern"": [
                {
                    ""regexp"": ""^fatal: (.*)$"",
                    ""message"": 1
                }
            ]
        }
    ]
}";
            string matcherFile = Path.Combine(tempDirectory, $"git_{Guid.NewGuid()}.json");
            File.WriteAllText(matcherFile, problemMatcher, new UTF8Encoding(false));
            executionContext.Output($"##[add-matcher]{matcherFile}");
            try
            {
                await new GitHubSourceProvider().GetSourceAsync(executionContext,
                                                                expectRepoPath,
                                                                repoFullName,
                                                                sourceBranch,
                                                                sourceVersion,
                                                                clean,
                                                                submoduleInput,
                                                                fetchDepth,
                                                                gitLfsSupport,
                                                                accessToken,
                                                                token);
            }
            finally
            {
                executionContext.Output("##[remove-matcher owner=checkout-git]");
            }
        }

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

private static string ReadResultData(string json, string property)
		{
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Expected O, but got Unknown
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Invalid comparison between Unknown and I4
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006a: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: Expected I4, but got Unknown
			if (json == null || json.Trim()[0] != '{')
			{
				return json;
			}
			var code = new StringBuilder();
			using (var textReader = new StringReader(json))
			{
				var reader = new JsonTextReader(textReader);
				var isResultData = false;
				var levle = 0;
				while (reader.Read())
				{
					if (!isResultData && (int)reader.TokenType == 4)
					{
						if (reader.Value.ToString() == property)
						{
							isResultData = true;
						}
					}
					else if (isResultData)
					{
						var tokenType = reader.TokenType;
						switch ((int)tokenType)
						{
						case 2:
							code.Append('[');
							continue;
						case 1:
							code.Append('{');
							levle++;
							continue;
						case 4:
							code.Append($"\"{reader.Value}\"=");
							continue;
						case 17:
							code.Append($"\"{reader.Value}\"");
							goto default;
						case 9:
						case 16:
							code.Append($"\"{reader.Value}\"");
							goto default;
						case 7:
						case 8:
						case 10:
							code.Append("null");
							goto default;
						case 11:
							code.Append("null");
							goto default;
						case 13:
							if (code.Length > 0 && code[code.Length - 1] == ',')
							{
								code[code.Length - 1] = '}';
							}
							else
							{
								code.Append('}');
							}
							levle--;
							goto default;
						case 14:
							if (code.Length > 0 && code[code.Length - 1] == ',')
							{
								code[code.Length - 1] = ']';
							}
							else
							{
								code.Append(']');
							}
							goto default;
						case 6:
							code.Append(reader.Value);
							goto default;
						default:
							if (levle == 0)
							{
								break;
							}
							code.Append(',');
							continue;
						}
						break;
					}
				}
			}
			if (code.Length > 0 && code[code.Length - 1] == ',')
			{
				code[code.Length - 1] = ' ';
			}
			return code.ToString().Trim('\'', '"');
		}

19 View Source File : ZooKeeperServiceDiscovery.cs
License : MIT License
Project Creator : 1100100

private static string GetServiceNameFromPath(string path)
        {
            return path.Replace(Root, "").Trim('/');
        }

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

public List<T> ToArray<T>(string name, Func<string, T> parse)
        {
            var cs = GetValue(name);
            if (string.IsNullOrWhiteSpace(cs)) return null;
            var css = cs.Trim('[', ']').Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries);
            return css.Length > 0 ? css.Select(parse).ToList() : null;
        }

19 View Source File : CustomShellService.cs
License : MIT License
Project Creator : Actipro

private string CombineCloudStorageParsingNames(params string[] relativeParsingNames) {
			if (relativeParsingNames is null || relativeParsingNames.Length == 0)
				return null;

			string parsingName = relativeParsingNames[0].TrimEnd(CloudStorageParsingNameSeparator.ToCharArray());
			for (int i = 1; i < relativeParsingNames.Length; i++) {
				parsingName += CloudStorageParsingNameSeparator + relativeParsingNames[i].Trim(CloudStorageParsingNameSeparator.ToCharArray());
			}

			return parsingName;
		}

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

private static ITemplateOutput Parser(string tplcode, string[] usings, IDictionary options) {
			int view = Interlocked.Increment(ref _view);
			StringBuilder sb = new StringBuilder();
			IDictionary options_copy = new Hashtable();
			foreach (DictionaryEntry options_de in options) options_copy[options_de.Key] = options_de.Value;
			sb.AppendFormat(@"
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;{1}

//namespace TplDynamicCodeGenerate {{
	public clreplaced TplDynamicCodeGenerate_view{0} : FreeSql.Template.TemplateEngin.ITemplateOutput {{
		public FreeSql.Template.TemplateEngin.TemplateReturnInfo OuTpUt(StringBuilder tOuTpUt, IDictionary oPtIoNs, string rEfErErFiLeNaMe, FreeSql.Template.TemplateEngin tEmPlAtEsEnDeR) {{
			FreeSql.Template.TemplateEngin.TemplateReturnInfo rTn = tOuTpUt == null ? 
				new FreeSql.Template.TemplateEngin.TemplateReturnInfo {{ Sb = (tOuTpUt = new StringBuilder()), Blocks = new Dictionary<string, int[]>() }} :
				new FreeSql.Template.TemplateEngin.TemplateReturnInfo {{ Sb = tOuTpUt, Blocks = new Dictionary<string, int[]>() }};
			Dictionary<string, int[]> TPL__blocks = rTn.Blocks;
			Stack<int[]> TPL__blocks_stack = new Stack<int[]>();
			int[] TPL__blocks_stack_peek;
			List<IDictionary> TPL__forc = new List<IDictionary>();
			Func<IDictionary> pRoCeSsOpTiOnS = new Func<IDictionary>(delegate () {{
				IDictionary nEwoPtIoNs = new Hashtable();
				foreach (DictionaryEntry oPtIoNs_dE in oPtIoNs)
					nEwoPtIoNs[oPtIoNs_dE.Key] = oPtIoNs_dE.Value;
				foreach (IDictionary TPL__forc_dIc in TPL__forc)
					foreach (DictionaryEntry TPL__forc_dIc_dE in TPL__forc_dIc)
						nEwoPtIoNs[TPL__forc_dIc_dE.Key] = TPL__forc_dIc_dE.Value;
				return nEwoPtIoNs;
			}});
			FreeSql.Template.TemplateEngin.TemplateIf tPlIf = delegate(object exp) {{
				if (exp is bool) return (bool)exp;
				if (exp == null) return false;
				if (exp is int && (int)exp == 0) return false;
				if (exp is string && (string)exp == string.Empty) return false;
				if (exp is long && (long)exp == 0) return false;
				if (exp is short && (short)exp == 0) return false;
				if (exp is byte && (byte)exp == 0) return false;
				if (exp is double && (double)exp == 0) return false;
				if (exp is float && (float)exp == 0) return false;
				if (exp is decimal && (decimal)exp == 0) return false;
				return true;
			}};
			FreeSql.Template.TemplateEngin.TemplatePrint print = delegate(object[] pArMs) {{
				if (pArMs == null || pArMs.Length == 0) return;
				foreach (object pArMs_A in pArMs) if (pArMs_A != null) tOuTpUt.Append(pArMs_A);
			}};
			FreeSql.Template.TemplateEngin.TemplatePrint Print = print;", view, usings?.Any() == true ? $"\r\nusing {string.Join(";\r\nusing ", usings)};" : "");

			#region {miss}...{/miss}块内容将不被解析
			string[] tmp_content_arr = _reg_miss.Split(tplcode);
			if (tmp_content_arr.Length > 1) {
				sb.AppendFormat(@"
			string[] TPL__MISS = new string[{0}];", Math.Ceiling(1.0 * (tmp_content_arr.Length - 1) / 2));
				int miss_len = -1;
				for (int a = 1; a < tmp_content_arr.Length; a += 2) {
					sb.Append(string.Concat(@"
			TPL__MISS[", ++miss_len, @"] = """, Utils.GetConstString(tmp_content_arr[a]), @""";"));
					tmp_content_arr[a] = string.Concat("{#TPL__MISS[", miss_len, "]}");
				}
				tplcode = string.Join("", tmp_content_arr);
			}
			#endregion
			#region 扩展语法如 <div @if="表达式"></div>
			tplcode = htmlSyntax(tplcode, 3); //<div @if="c#表达式" @for="index 1,100"></div>
											  //处理 {% %} 块 c#代码
			tmp_content_arr = _reg_code.Split(tplcode);
			if (tmp_content_arr.Length == 1) {
				tplcode = Utils.GetConstString(tplcode)
					.Replace("{%", "{$TEMPLATE__CODE}")
					.Replace("%}", "{/$TEMPLATE__CODE}");
			} else {
				tmp_content_arr[0] = Utils.GetConstString(tmp_content_arr[0]);
				for (int a = 1; a < tmp_content_arr.Length; a += 4) {
					tmp_content_arr[a] = "{$TEMPLATE__CODE}";
					tmp_content_arr[a + 2] = "{/$TEMPLATE__CODE}";
					tmp_content_arr[a + 3] = Utils.GetConstString(tmp_content_arr[a + 3]);
				}
				tplcode = string.Join("", tmp_content_arr);
			}
			#endregion
			sb.Append(@"
			tOuTpUt.Append(""");

			string error = null;
			int tpl_tmpid = 0;
			int forc_i = 0;
			string extends = null;
			Stack<string> codeTree = new Stack<string>();
			Stack<string> forEndRepl = new Stack<string>();
			sb.Append(_reg.Replace(tplcode, delegate (Match m) {
				string _0 = m.Groups[0].Value;
				if (!string.IsNullOrEmpty(error)) return _0;

				string _1 = m.Groups[1].Value.Trim(' ', '\t');
				string _2 = m.Groups[2].Value
					.Replace("\\\\", "\\")
					.Replace("\\\"", "\"");
				_2 = Utils.ReplaceSingleQuote(_2);

				switch (_1) {
					#region $TEMPLATE__CODE--------------------------------------------------
					case "$TEMPLATE__CODE":
						codeTree.Push(_1);
						return @""");
";
					case "/$TEMPLATE__CODE":
						string pop = codeTree.Pop();
						if (pop != "$TEMPLATE__CODE") {
							codeTree.Push(pop);
							error = "编译出错,{% 与 %} 并没有配对";
							return _0;
						}
						return @"
			tOuTpUt.Append(""";
					#endregion
					case "include":
						return string.Format(@""");
tEmPlAtEsEnDeR.RenderFile2(tOuTpUt, pRoCeSsOpTiOnS(), ""{0}"", rEfErErFiLeNaMe);
			tOuTpUt.Append(""", _2);
					case "import":
						return _0;
					case "module":
						return _0;
					case "/module":
						return _0;
					case "extends":
						//{extends ../inc/layout.html}
						if (string.IsNullOrEmpty(extends) == false) return _0;
						extends = _2;
						return string.Empty;
					case "block":
						codeTree.Push("block");
						return string.Format(@""");
TPL__blocks_stack_peek = new int[] {{ tOuTpUt.Length, 0 }};
TPL__blocks_stack.Push(TPL__blocks_stack_peek);
TPL__blocks.Add(""{0}"", TPL__blocks_stack_peek);
tOuTpUt.Append(""", _2.Trim(' ', '\t'));
					case "/block":
						codeTreeEnd(codeTree, "block");
						return @""");
TPL__blocks_stack_peek = TPL__blocks_stack.Pop();
TPL__blocks_stack_peek[1] = tOuTpUt.Length - TPL__blocks_stack_peek[0];
tOuTpUt.Append(""";

					#region ##---------------------------------------------------------
					case "#":
						if (_2[0] == '#')
							return string.Format(@""");
			try {{ Print({0}); }} catch {{ }}
			tOuTpUt.Append(""", _2.Substring(1));
						return string.Format(@""");
			Print({0});
			tOuTpUt.Append(""", _2);
					#endregion
					#region for--------------------------------------------------------
					case "for":
						forc_i++;
						int cur_tpl_tmpid = tpl_tmpid;
						string sb_endRepl = string.Empty;
						StringBuilder sbfor = new StringBuilder();
						sbfor.Append(@""");");
						Match mfor = _reg_forin.Match(_2);
						if (mfor.Success) {
							string mfor1 = mfor.Groups[1].Value.Trim(' ', '\t');
							string mfor2 = mfor.Groups[2].Value.Trim(' ', '\t');
							sbfor.AppendFormat(@"
//new Action(delegate () {{
	IDictionary TPL__tmp{0} = new Hashtable();
	TPL__forc.Add(TPL__tmp{0});
	var TPL__tmp{1} = {3};
	var TPL__tmp{2} = {4};", ++tpl_tmpid, ++tpl_tmpid, ++tpl_tmpid, mfor.Groups[3].Value, mfor1);
							sb_endRepl = string.Concat(sb_endRepl, string.Format(@"
	{0} = TPL__tmp{1};", mfor1, cur_tpl_tmpid + 3));
							if (options_copy.Contains(mfor1) == false) options_copy[mfor1] = null;
							if (!string.IsNullOrEmpty(mfor2)) {
								sbfor.AppendFormat(@"
	var TPL__tmp{1} = {0};
	{0} = 0;", mfor2, ++tpl_tmpid);
								sb_endRepl = string.Concat(sb_endRepl, string.Format(@"
	{0} = TPL__tmp{1};", mfor2, tpl_tmpid));
								if (options_copy.Contains(mfor2) == false) options_copy[mfor2] = null;
							}
							sbfor.AppendFormat(@"
	if (TPL__tmp{1} != null)
	foreach (var TPL__tmp{0} in TPL__tmp{1}) {{", ++tpl_tmpid, cur_tpl_tmpid + 2);
							if (!string.IsNullOrEmpty(mfor2))
								sbfor.AppendFormat(@"
		TPL__tmp{1}[""{0}""] = ++ {0};", mfor2, cur_tpl_tmpid + 1);
							sbfor.AppendFormat(@"
		TPL__tmp{1}[""{0}""] = TPL__tmp{2};
		{0} = TPL__tmp{2};
		tOuTpUt.Append(""", mfor1, cur_tpl_tmpid + 1, tpl_tmpid);
							codeTree.Push("for");
							forEndRepl.Push(sb_endRepl);
							return sbfor.ToString();
						}
						mfor = _reg_foron.Match(_2);
						if (mfor.Success) {
							string mfor1 = mfor.Groups[1].Value.Trim(' ', '\t');
							string mfor2 = mfor.Groups[2].Value.Trim(' ', '\t');
							string mfor3 = mfor.Groups[3].Value.Trim(' ', '\t');
							sbfor.AppendFormat(@"
//new Action(delegate () {{
	IDictionary TPL__tmp{0} = new Hashtable();
	TPL__forc.Add(TPL__tmp{0});
	var TPL__tmp{1} = {3};
	var TPL__tmp{2} = {4};", ++tpl_tmpid, ++tpl_tmpid, ++tpl_tmpid, mfor.Groups[4].Value, mfor1);
							sb_endRepl = string.Concat(sb_endRepl, string.Format(@"
	{0} = TPL__tmp{1};", mfor1, cur_tpl_tmpid + 3));
							if (options_copy.Contains(mfor1) == false) options_copy[mfor1] = null;
							if (!string.IsNullOrEmpty(mfor2)) {
								sbfor.AppendFormat(@"
	var TPL__tmp{1} = {0};", mfor2, ++tpl_tmpid);
								sb_endRepl = string.Concat(sb_endRepl, string.Format(@"
	{0} = TPL__tmp{1};", mfor2, tpl_tmpid));
								if (options_copy.Contains(mfor2) == false) options_copy[mfor2] = null;
							}
							if (!string.IsNullOrEmpty(mfor3)) {
								sbfor.AppendFormat(@"
	var TPL__tmp{1} = {0};
	{0} = 0;", mfor3, ++tpl_tmpid);
								sb_endRepl = string.Concat(sb_endRepl, string.Format(@"
	{0} = TPL__tmp{1};", mfor3, tpl_tmpid));
								if (options_copy.Contains(mfor3) == false) options_copy[mfor3] = null;
							}
							sbfor.AppendFormat(@"
	if (TPL__tmp{2} != null)
	foreach (DictionaryEntry TPL__tmp{1} in TPL__tmp{2}) {{
		{0} = TPL__tmp{1}.Key;
		TPL__tmp{3}[""{0}""] = {0};", mfor1, ++tpl_tmpid, cur_tpl_tmpid + 2, cur_tpl_tmpid + 1);
							if (!string.IsNullOrEmpty(mfor2))
								sbfor.AppendFormat(@"
		{0} = TPL__tmp{1}.Value;
		TPL__tmp{2}[""{0}""] = {0};", mfor2, tpl_tmpid, cur_tpl_tmpid + 1);
							if (!string.IsNullOrEmpty(mfor3))
								sbfor.AppendFormat(@"
		TPL__tmp{1}[""{0}""] = ++ {0};", mfor3, cur_tpl_tmpid + 1);
							sbfor.AppendFormat(@"
		tOuTpUt.Append(""");
							codeTree.Push("for");
							forEndRepl.Push(sb_endRepl);
							return sbfor.ToString();
						}
						mfor = _reg_forab.Match(_2);
						if (mfor.Success) {
							string mfor1 = mfor.Groups[1].Value.Trim(' ', '\t');
							sbfor.AppendFormat(@"
//new Action(delegate () {{
	IDictionary TPL__tmp{0} = new Hashtable();
	TPL__forc.Add(TPL__tmp{0});
	var TPL__tmp{1} = {5};
	{5} = {3} - 1;
	if ({5} == null) {5} = 0;
	var TPL__tmp{2} = {4} + 1;
	while (++{5} < TPL__tmp{2}) {{
		TPL__tmp{0}[""{5}""] = {5};
		tOuTpUt.Append(""", ++tpl_tmpid, ++tpl_tmpid, ++tpl_tmpid, mfor.Groups[2].Value, mfor.Groups[3].Value, mfor1);
							sb_endRepl = string.Concat(sb_endRepl, string.Format(@"
	{0} = TPL__tmp{1};", mfor1, cur_tpl_tmpid + 1));
							if (options_copy.Contains(mfor1) == false) options_copy[mfor1] = null;
							codeTree.Push("for");
							forEndRepl.Push(sb_endRepl);
							return sbfor.ToString();
						}
						return _0;
					case "/for":
						if (--forc_i < 0) return _0;
						codeTreeEnd(codeTree, "for");
						return string.Format(@""");
	}}{0}
	TPL__forc.RemoveAt(TPL__forc.Count - 1);
//}})();
			tOuTpUt.Append(""", forEndRepl.Pop());
					#endregion
					#region if---------------------------------------------------------
					case "if":
						codeTree.Push("if");
						return string.Format(@""");
			if ({1}tPlIf({0})) {{
				tOuTpUt.Append(""", _2[0] == '!' ? _2.Substring(1) : _2, _2[0] == '!' ? '!' : ' ');
					case "elseif":
						codeTreeEnd(codeTree, "if");
						codeTree.Push("if");
						return string.Format(@""");
			}} else if ({1}tPlIf({0})) {{
				tOuTpUt.Append(""", _2[0] == '!' ? _2.Substring(1) : _2, _2[0] == '!' ? '!' : ' ');
					case "else":
						codeTreeEnd(codeTree, "if");
						codeTree.Push("if");
						return @""");
			} else {
			tOuTpUt.Append(""";
					case "/if":
						codeTreeEnd(codeTree, "if");
						return @""");
			}
			tOuTpUt.Append(""";
						#endregion
				}
				return _0;
			}));

			sb.Append(@""");");
			if (string.IsNullOrEmpty(extends) == false) {
				sb.AppendFormat(@"
FreeSql.Template.TemplateEngin.TemplateReturnInfo eXtEnDs_ReT = tEmPlAtEsEnDeR.RenderFile2(null, pRoCeSsOpTiOnS(), ""{0}"", rEfErErFiLeNaMe);
string rTn_Sb_string = rTn.Sb.ToString();
foreach(string eXtEnDs_ReT_blocks_key in eXtEnDs_ReT.Blocks.Keys) {{
	if (rTn.Blocks.ContainsKey(eXtEnDs_ReT_blocks_key)) {{
		int[] eXtEnDs_ReT_blocks_value = eXtEnDs_ReT.Blocks[eXtEnDs_ReT_blocks_key];
		eXtEnDs_ReT.Sb.Remove(eXtEnDs_ReT_blocks_value[0], eXtEnDs_ReT_blocks_value[1]);
		int[] rTn_blocks_value = rTn.Blocks[eXtEnDs_ReT_blocks_key];
		eXtEnDs_ReT.Sb.Insert(eXtEnDs_ReT_blocks_value[0], rTn_Sb_string.Substring(rTn_blocks_value[0], rTn_blocks_value[1]));
		foreach(string eXtEnDs_ReT_blocks_keyb in eXtEnDs_ReT.Blocks.Keys) {{
			if (eXtEnDs_ReT_blocks_keyb == eXtEnDs_ReT_blocks_key) continue;
			int[] eXtEnDs_ReT_blocks_valueb = eXtEnDs_ReT.Blocks[eXtEnDs_ReT_blocks_keyb];
			if (eXtEnDs_ReT_blocks_valueb[0] >= eXtEnDs_ReT_blocks_value[0])
				eXtEnDs_ReT_blocks_valueb[0] = eXtEnDs_ReT_blocks_valueb[0] - eXtEnDs_ReT_blocks_value[1] + rTn_blocks_value[1];
		}}
		eXtEnDs_ReT_blocks_value[1] = rTn_blocks_value[1];
	}}
}}
return eXtEnDs_ReT;
", extends);
			} else {
				sb.Append(@"
return rTn;");
			}
			sb.Append(@"
		}
	}
//}
");
			var str = "FreeSql.Template.TemplateEngin.TemplatePrint Print = print;";
			int dim_idx = sb.ToString().IndexOf(str) + str.Length;
			foreach (string dic_name in options_copy.Keys) {
				sb.Insert(dim_idx, string.Format(@"
			dynamic {0} = oPtIoNs[""{0}""];", dic_name));
			}
			//Console.WriteLine(sb.ToString());
			return Complie(sb.ToString(), @"TplDynamicCodeGenerate_view" + view);
		}

19 View Source File : ZooKeeperServiceDiscovery.cs
License : MIT License
Project Creator : 1100100

private async Task CreatePath(string path, byte[] data)
        {
            path = path.Trim('/');
            if (string.IsNullOrWhiteSpace(path))
                return;
            var children = path.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
            var nodePath = new StringBuilder();
            for (var i = 0; i < children.Length; i++)
            {
                nodePath.Append("/" + children[i]);
                if (await ZooKeeper.existsAsync(nodePath.ToString()) == null)
                {
                    await ZooKeeper.createAsync(nodePath.ToString(), i == children.Length - 1 ? data : null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
                }
            }
        }

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

internal static async Task Main(string[] args)
        {
            try
            {
                if (args.Length == 0)
                {
                    Console.WriteLine("Drag .pkg files and/or folders onto this .exe to verify the packages.");
                    var isFirstChar = true;
                    var completedPath = false;
                    var path = new StringBuilder();
                    do
                    {
                        var keyInfo = Console.ReadKey(true);
                        if (isFirstChar)
                        {
                            isFirstChar = false;
                            if (keyInfo.KeyChar != '"')
                                return;
                        }
                        else
                        {
                            if (keyInfo.KeyChar == '"')
                            {
                                completedPath = true;
                                args = new[] {path.ToString()};
                            }
                            else
                                path.Append(keyInfo.KeyChar);
                        }
                    } while (!completedPath);
                    Console.Clear();
                }

                Console.OutputEncoding = new UTF8Encoding(false);
                Console.replacedle = replacedle;
                Console.CursorVisible = false;
                Console.WriteLine("Scanning for PKGs...");
                var pkgList = new List<FileInfo>();
                Console.ForegroundColor = ConsoleColor.Yellow;
                foreach (var item in args)
                {
                    var path = item.Trim('"');
                    if (File.Exists(path))
                        pkgList.Add(new FileInfo(path));
                    else if (Directory.Exists(path))
                        pkgList.AddRange(GetFilePaths(path, "*.pkg", SearchOption.AllDirectories).Select(p => new FileInfo(p)));
                    else
                        Console.WriteLine("Unknown path: " + path);
                }
                Console.ResetColor();
                if (pkgList.Count == 0)
                {
                    Console.WriteLine("No packages were found. Check paths, and try again.");
                    return;
                }

                var longestFilename = Math.Max(pkgList.Max(i => i.Name.Length), HeaderPkgName.Length);
                var sigWidth = Math.Max(HeaderSignature.Length, 8);
                var csumWidth = Math.Max(HeaderChecksum.Length, 5);
                var csumsWidth = 1 + sigWidth + 1 + csumWidth + 1;
                var idealWidth = longestFilename + csumsWidth;
                try
                {
                    if (idealWidth > Console.LargestWindowWidth)
                    {
                        longestFilename = Console.LargestWindowWidth - csumsWidth;
                        idealWidth = Console.LargestWindowWidth;
                    }
                    if (idealWidth > Console.WindowWidth)
                    {
                        Console.BufferWidth = Math.Max(Console.BufferWidth, idealWidth);
                        Console.WindowWidth = idealWidth;
                    }
                    Console.BufferHeight = Math.Max(Console.BufferHeight, Math.Min(9999, pkgList.Count + 10));
                }
                catch (PlatformNotSupportedException) { }
                Console.WriteLine($"{HeaderPkgName.Trim(longestFilename).PadRight(longestFilename)} {HeaderSignature.PadLeft(sigWidth)} {HeaderChecksum.PadLeft(csumWidth)}");
                using var cts = new CancellationTokenSource();
                Console.CancelKeyPress += (sender, eventArgs) => { cts.Cancel(); };
                var t = new Thread(() =>
                                   {
                                       try
                                       {
                                           var indicatorIdx = 0;
                                           while (!cts.Token.IsCancellationRequested)
                                           {
                                               Task.Delay(1000, cts.Token).ConfigureAwait(false).GetAwaiter().GetResult();
                                               if (cts.Token.IsCancellationRequested)
                                                   return;

                                               PkgChecker.Sync.Wait(cts.Token);
                                               try
                                               {
                                                   var frame = Animation[(indicatorIdx++) % Animation.Length];
                                                   var currentProgress = PkgChecker.CurrentFileProcessedBytes;
                                                   Console.replacedle = $"{replacedle} [{(double)(PkgChecker.ProcessedBytes + currentProgress) / PkgChecker.TotalFileSize * 100:0.00}%] {frame}";
                                                   if (PkgChecker.CurrentPadding > 0)
                                                   {
                                                       Console.CursorVisible = false;
                                                       var (top, left) = (Console.CursorTop, Console.CursorLeft);
                                                       Console.Write($"{(double)currentProgress / PkgChecker.CurrentFileSize * 100:0}%".PadLeft(PkgChecker.CurrentPadding));
                                                       Console.CursorTop = top;
                                                       Console.CursorLeft = left;
                                                       Console.CursorVisible = false;
                                                   }
                                               }
                                               finally
                                               {
                                                   PkgChecker.Sync.Release();
                                               }
                                           }
                                       }
                                       catch (TaskCanceledException)
                                       {
                                       }
                                   });
                t.Start();
                await PkgChecker.CheckAsync(pkgList, longestFilename, sigWidth, csumWidth, csumsWidth-2, cts.Token).ConfigureAwait(false);
                cts.Cancel(false);
                t.Join();
            }
            finally
            {
                Console.replacedle = replacedle;
                Console.WriteLine("Press any key to exit");
                Console.ReadKey();
                Console.WriteLine();
                Console.CursorVisible = true;
            }
        }

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

private Expression ResovleConstantExpression(string expression, Type type)
        {
            //生成指定类型的表达式
            if (expression == "null")
            {
                return Expression.Constant(null, type);
            }
            else if (type == typeof(string))
            {
                return Expression.Constant(expression.Trim('\'', '\''), type);
            }
            else
            {
                if (Nullable.GetUnderlyingType(type) == null)
                {
                    var value = Convert.ChangeType(expression, type);
                    return Expression.Constant(value, type);
                }
                else
                {
                    var undertype = Nullable.GetUnderlyingType(type);
                    var value = Convert.ChangeType(expression, undertype);
                    var expr = Expression.Constant(value, undertype);
                    return Expression.MakeUnary(ExpressionType.Convert, expr, type);
                }
            }
        }

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

internal static bool TryGetVersionComponents(
            string packageVersion,
            out Version version,
            out float prerelease)
        {
            char[] trimChars = new char[] { ' ', '\"', ',' };

            // Note: The version is in the following format Major.Minor.Revision[-Date.Build]

            // Attempt to split the version string into version and float components
            string[] versionComponents = packageVersion.Split(new char[] { '-' }, 2);

            // Parse the version component.
            string versionString = versionComponents[0].Trim(trimChars);
            if (Version.TryParse(versionString, out version))
            {
                if (versionComponents.Length == 2)
                {
                    // Parse the float component
                    string prereleaseString = versionComponents[1].Trim(trimChars);
                    if (float.TryParse(prereleaseString, NumberStyles.AllowDecimalPoint, NumberFormatInfo.InvariantInfo, out prerelease))
                    {
                        return true;
                    }
                }
                else
                {
                    prerelease = 0f;
                    return true;
                }
            }

            version = null;
            prerelease = float.NaN;
            return false;
        }

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

public static Folder AddOrGetExistingFolder(this ClientContext context, string listUrl, string folderUrl)
		{
			// Ensure safe folder URL - it cannot begin or end with dot, contain consecutive dots, or any of ~ " # % & * : < > ? \ { | }
			var spSafeFolderUrl = Regex.Replace(folderUrl, @"(\.{2,})|([\~\""\#\%\&\*\:\<\>\?\\\{\|\}])|(^\.)|(\.$)", string.Empty);

			var trimmedFolderUrl = spSafeFolderUrl.Trim('/');

			Folder folder;
			if (TryGetFolder(context, listUrl + "/" + trimmedFolderUrl, out folder))
			{
				return folder;
			}

			var list = context.GetListByUrl(listUrl);

			return context.CreateFolderPath(list.RootFolder, trimmedFolderUrl);
		}

See More Examples