string.Join(string, System.Collections.Generic.IEnumerable)

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

10237 Examples 7

19 View Source File : AdjacentSeats.cs
License : Apache License 2.0
Project Creator : 42skillz

public override string ToString()
        {
            return $"{string.Join("-", _seats.Select(s => s.ToString()))}";
        }

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

private async Task DoWork(PlayerEnreplacedy player)
        {
            await _mudProvider.ShowMessage(player.Id, $"你正在{player.Status}。。。");
            WorkTypeEnum workType = WorkTypeEnum.伐木;
            switch (player.Status)
            {
                case PlayerStatusEnum.伐木:
                    workType = WorkTypeEnum.伐木;
                    break;
                case PlayerStatusEnum.挖矿:
                    workType = WorkTypeEnum.挖矿;
                    break;
                case PlayerStatusEnum.打猎:
                    workType = WorkTypeEnum.打猎;
                    break;
                case PlayerStatusEnum.采药:
                    workType = WorkTypeEnum.采药;
                    break;
                case PlayerStatusEnum.钓鱼:
                    workType = WorkTypeEnum.钓鱼;
                    break;
                case PlayerStatusEnum.打工:
                    workType = WorkTypeEnum.打工;
                    break;

                default:
                    return;
            }

            var ids = (await _roomItemDropDomainService.GetAll()).Where(x => x.RoomId == player.RoomId).Select(x=>x.ItemDropId).ToList();

            var itemDrop = (await _itemDropDomainService.GetAll()).Where(x => ids.Contains(x.Id)).FirstOrDefault(x => x.WorkType == workType);
            if (itemDrop == null)
            {
                return;
            }
           

            var itemDropRates = (await _itemDropRateDomainService.GetAll()).Where(x => x.ItemDropId == itemDrop.Id).ToList();
            if (itemDropRates?.Count == 0)
            {
                return;
            }

            var random = new Random();
            int maxWeight = 100;//掉落总权重
            var itemDropModels = new List<ItemDropRateModel>();
            foreach (var itemDropRate in itemDropRates.OrderBy(x=>x.Order))
            {
                if (itemDropRate.Percent < random.Next(0, 100))
                {
                    continue;
                }

                int number = random.Next(Math.Min(itemDropRate.MinNumber, itemDropRate.MaxNumber), itemDropRate.MaxNumber + 1);
                if (number <= 0)
                {
                    continue;
                }

                //掉落
                maxWeight -= itemDropRate.Weight;

                var itemDropModel = new ItemDropRateModel
                {
                    DropType = itemDropRate.DropType,
                    Number = number,
                    WareId = itemDropRate.WareId
                };
                itemDropModels.Add(itemDropModel);



                if (maxWeight <= 0)
                {
                    break;
                }
            }

            if (itemDropModels.Count == 0)
            {
                //没有掉落
                return;
            }

            var playerAttributeChanged = false;
            List<string> dropContents = new List<string>() ;

            foreach (var itemDropModel in itemDropModels)
            {
                switch (itemDropModel.DropType)
                {
                    case ItemDropTypeEnum.潜能:
                        playerAttributeChanged = true;
                        player.Pot += itemDropModel.Number;
                        dropContents.Add($"潜能 +{itemDropModel.Number}");
                        break;
                    case ItemDropTypeEnum.经验:
                        playerAttributeChanged = true;
                        player.Exp += itemDropModel.Number;
                        dropContents.Add($"经验 +{itemDropModel.Number}");
                        break;
                    case ItemDropTypeEnum.金钱:
                        playerAttributeChanged = true;
                        player.Money += itemDropModel.Number;
                        dropContents.Add($" +{itemDropModel.Number.ToMoney()}");
                        break;
                    case ItemDropTypeEnum.物品:
                        #region MyRegion
                        int wareId = itemDropModel.WareId;
                        int number = itemDropModel.Number;

                        var ware = await _wareDomainService.Get(wareId);
                        if (ware == null)
                        {
                            continue;
                        }

                        dropContents.Add($"{number}{ware.Unit}{ware.Name}");

                        var canStack = ware.Category != WareCategoryEnum.武器;

                        if (canStack)
                        {
                            var playerWare = await _playerWareDomainService.Get(x => x.WareId == ware.Id && x.PlayerId == player.Id);
                            if (playerWare == null)
                            {
                                playerWare = new PlayerWareEnreplacedy
                                {
                                    IsBind = false,
                                    IsTemp = false,
                                    Level = 1,
                                    Number = number,
                                    Damage = 0,
                                    PlayerId = player.Id,
                                    Status = WareStatusEnum.卸下,
                                    WareId = wareId,
                                    WareName = ware.Name
                                };
                                await _playerWareDomainService.Add(playerWare);
                            }
                            else
                            {
                                playerWare.Number += number;
                                await _playerWareDomainService.Update(playerWare);
                            }
                        }
                        else
                        {
                            var playerWare = new PlayerWareEnreplacedy
                            {
                                IsBind = false,
                                IsTemp = false,
                                Level = 1,
                                Number = number,
                                Damage = 0,
                                PlayerId = player.Id,
                                Status = WareStatusEnum.卸下,
                                WareId = wareId,
                                WareName = ware.Name
                            };
                            await _playerWareDomainService.Add(playerWare);
                        }
                        #endregion


                        break;
                }
               
            }

            if (playerAttributeChanged)
            {
                await _bus.RaiseEvent(new PlayerAttributeChangedEvent(player)).ConfigureAwait(false);
            }


            if (dropContents.Count > 0)
            {
                await _mudProvider.ShowMessage(player.Id, $"获得{ string.Join(",", dropContents)   }。");   
            }


        }

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

public static DynamicProxyMeta CreateDynamicProxyMeta(Type type, bool isCompile, bool isThrow)
        {
            if (type == null) return null;
            var typeCSharpName = type.DisplayCsharp();

            if (type.IsNotPublic)
            {
                if (isThrow) throw new ArgumentException($"FreeSql.DynamicProxy 失败提示:{typeCSharpName} 需要使用 public 标记");
                return null;
            }

            var matchedMemberInfos = new List<MemberInfo>();
            var matchedAttributes = new List<DynamicProxyAttribute>();
            var matchedAttributesFromServices = new List<FieldInfo[]>();
            var clreplacedName = $"AopProxyClreplaced___{Guid.NewGuid().ToString("N")}";
            var methodOverrideSb = new StringBuilder();
            var sb = methodOverrideSb;

            #region Common Code

            Func<Type, DynamicProxyInjectorType, bool, int, string, string> getMatchedAttributesCode = (returnType, injectorType, isAsync, attrsIndex, proxyMethodName) =>
            {
                var sbt = new StringBuilder();
                for (var a = attrsIndex; a < matchedAttributes.Count; a++)
                {
                    sbt.Append([email protected]"{(proxyMethodName == "Before" ? [email protected]"
        var __DP_ARG___attribute{a} = __DP_Meta.{nameof(DynamicProxyMeta.CreateDynamicProxyAttribute)}({a});
        __DP_ARG___attribute{a}_FromServicesCopyTo(__DP_ARG___attribute{a});" : "")}
        var __DP_ARG___{proxyMethodName}{a} = new {(proxyMethodName == "Before" ? _beforeAgumentsName : _afterAgumentsName)}(this, {_injectorTypeName}.{injectorType.ToString()}, __DP_Meta.MatchedMemberInfos[{a}], __DP_ARG___parameters, {(proxyMethodName == "Before" ? "null" : "__DP_ARG___return_value, __DP_ARG___exception")});
        {(isAsync ? "await " : "")}__DP_ARG___attribute{a}.{proxyMethodName}(__DP_ARG___{proxyMethodName}{a});
        {(proxyMethodName == "Before" ? 
        [email protected]"if (__DP_ARG___is_return == false)
        {{
            __DP_ARG___is_return = __DP_ARG___{proxyMethodName}{a}.Returned;{(returnType != typeof(void) ? [email protected]"
            if (__DP_ARG___is_return) __DP_ARG___return_value = __DP_ARG___{proxyMethodName}{a}.ReturnValue;" : "")}
        }}" : 
        $"if (__DP_ARG___{proxyMethodName}{a}.Exception != null && __DP_ARG___{proxyMethodName}{a}.ExceptionHandled == false) throw __DP_ARG___{proxyMethodName}{a}.Exception;")}");
                }
                return sbt.ToString();
            };
            Func<Type, DynamicProxyInjectorType, bool, string, string> getMatchedAttributesCodeReturn = (returnType, injectorType, isAsync, basePropertyValueTpl) =>
            {
                var sbt = new StringBuilder();
                var taskType = returnType.ReturnTypeWithoutTask();
                sbt.Append([email protected]"
        {(returnType == typeof(void) ? "return;" : (isAsync == false && returnType.IsTask() ?
                (taskType.IsValueType || taskType.IsGenericParameter ?
                    $"return __DP_ARG___return_value == null ? null : (__DP_ARG___return_value.GetType() == typeof({taskType.DisplayCsharp()}) ? System.Threading.Tasks.Task.FromResult(({taskType.DisplayCsharp()})__DP_ARG___return_value) : ({returnType.DisplayCsharp()})__DP_ARG___return_value);" :
                    $"return __DP_ARG___return_value == null ? null : (__DP_ARG___return_value.GetType() == typeof({taskType.DisplayCsharp()}) ? System.Threading.Tasks.Task.FromResult(__DP_ARG___return_value as {taskType.DisplayCsharp()}) : ({returnType.DisplayCsharp()})__DP_ARG___return_value);"
                ) :
                (returnType.IsValueType || returnType.IsGenericParameter ? $"return ({returnType.DisplayCsharp()})__DP_ARG___return_value;" : $"return __DP_ARG___return_value as {returnType.DisplayCsharp()};")))}");
                return sbt.ToString();
            };
            Func<string, Type, string> getMatchedAttributesCodeAuditParameter = (methodParameterName, methodParameterType) =>
            {
                return [email protected]"
            if (!object.ReferenceEquals({methodParameterName}, __DP_ARG___parameters[""{methodParameterName}""])) {methodParameterName} = {(methodParameterType.IsValueType ? [email protected]"({methodParameterType.DisplayCsharp()})__DP_ARG___parameters[""{methodParameterName}""]" : [email protected]"__DP_ARG___parameters[""{methodParameterName}""] as {methodParameterType.DisplayCsharp()}")};";
            };
            #endregion

            #region Methods
            var ctors = type.GetConstructors(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).Where(a => a.IsStatic == false).ToArray();
            var methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly);
            foreach (var method in methods)
            {
                if (method.Name.StartsWith("get_") || method.Name.StartsWith("set_"))
                    if (type.GetProperty(method.Name.Substring(4), BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly) != null) continue;
                var attrs = method.GetCustomAttributes(false).Select(a => a as DynamicProxyAttribute).Where(a => a != null).ToArray();
                if (attrs.Any() == false) continue;
                var attrsIndex = matchedAttributes.Count;
                matchedMemberInfos.AddRange(attrs.Select(a => method));
                matchedAttributes.AddRange(attrs);
#if net50 || ns21 || ns20
                matchedAttributesFromServices.AddRange(attrs.Select(af => af.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly)
                    .Where(gf => gf.GetCustomAttribute(typeof(DynamicProxyFromServicesAttribute)) != null).ToArray()));
#else
                matchedAttributesFromServices.AddRange(attrs.Select(af => new FieldInfo[0]));
#endif
                if (method.IsVirtual == false || method.IsFinal)
                {
                    if (isThrow) throw new ArgumentException($"FreeSql.DynamicProxy 失败提示:{typeCSharpName} 方法 {method.Name} 需要使用 virtual 标记");
                    continue;
                }

#if net40
                var returnType = method.ReturnType;
                var methodIsAsync = false;
#else
                var returnType = method.ReturnType.ReturnTypeWithoutTask();
                var methodIsAsync = method.ReturnType.IsTask();

                //if (attrs.Where(a => a.GetType().GetMethod("BeforeAsync", BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly) != null).Any() ||
                //    attrs.Where(a => a.GetType().GetMethod("AfterAsync", BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly) != null).Any())
                //{

                //}
#endif

                var baseInvoke = type.IsInterface == false ? [email protected]"

        try
        {{
            if (__DP_ARG___is_return == false)
            {{{string.Join("", method.GetParameters().Select(a => getMatchedAttributesCodeAuditParameter(a.Name, a.ParameterType)))}
                {(returnType != typeof(void) ? "__DP_ARG___return_value = " : "")}{(methodIsAsync ? "await " : "")}base.{method.Name}({(string.Join(", ", method.GetParameters().Select(a => a.Name)))});
            }}
        }}
        catch (Exception __DP_ARG___ex)
        {{
            __DP_ARG___exception = __DP_ARG___ex;
        }}" : "";

                sb.Append([email protected]"

    {(methodIsAsync ? "async " : "")}{method.DisplayCsharp(true)}
    {{
        Exception __DP_ARG___exception = null;
        var __DP_ARG___is_return = false;
        object __DP_ARG___return_value = null;
        var __DP_ARG___parameters = new Dictionary<string, object>();{string.Join("\r\n        ", method.GetParameters().Select(a => $"__DP_ARG___parameters.Add(\"{a.Name}\", {a.Name});"))}
        {getMatchedAttributesCode(returnType, DynamicProxyInjectorType.Method, methodIsAsync, attrsIndex, "Before")}{baseInvoke}
        {getMatchedAttributesCode(returnType, DynamicProxyInjectorType.Method, methodIsAsync, attrsIndex, "After")}
        {getMatchedAttributesCodeReturn(returnType, DynamicProxyInjectorType.Method, methodIsAsync, null)}
    }}");
            }
            #endregion

            var propertyOverrideSb = new StringBuilder();
            sb = propertyOverrideSb;
            #region Property
            var props = type.IsInterface == false ? type.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly) : new PropertyInfo[0];
            foreach (var prop2 in props)
            {
                var getMethod = prop2.GetGetMethod(false);
                var setMethod = prop2.GetSetMethod(false);
                if (getMethod?.IsFinal == true || setMethod?.IsFinal == true || (getMethod?.IsVirtual == false && setMethod?.IsVirtual == false))
                {
                    if (getMethod?.GetCustomAttributes(false).Select(a => a as DynamicProxyAttribute).Where(a => a != null).Any() == true ||
                        setMethod?.GetCustomAttributes(false).Select(a => a as DynamicProxyAttribute).Where(a => a != null).Any() == true)
                    {
                        if (isThrow) throw new ArgumentException($"FreeSql.DynamicProxy 失败提示:{typeCSharpName} 属性 {prop2.Name} 需要使用 virtual 标记");
                        continue;
                    }
                }

                var attrs = prop2.GetCustomAttributes(false).Select(a => a as DynamicProxyAttribute).Where(a => a != null).ToArray();
                var prop2AttributeAny = attrs.Any();
                var getMethodAttributeAny = prop2AttributeAny;
                var setMethodAttributeAny = prop2AttributeAny;
                if (attrs.Any() == false && getMethod?.IsVirtual == true)
                {
                    attrs = getMethod.GetCustomAttributes(false).Select(a => a as DynamicProxyAttribute).Where(a => a != null).ToArray();
                    getMethodAttributeAny = attrs.Any();
                }
                if (attrs.Any() == false && setMethod?.IsVirtual == true)
                {
                    attrs = setMethod.GetCustomAttributes(false).Select(a => a as DynamicProxyAttribute).Where(a => a != null).ToArray();
                    setMethodAttributeAny = attrs.Any();
                }
                if (attrs.Any() == false) continue;

                var attrsIndex = matchedAttributes.Count;
                matchedMemberInfos.AddRange(attrs.Select(a => prop2));
                matchedAttributes.AddRange(attrs);
#if net50 || ns21 || ns20
                matchedAttributesFromServices.AddRange(attrs.Select(af => af.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly)
                    .Where(gf => gf.GetCustomAttribute(typeof(DynamicProxyFromServicesAttribute)) != null).ToArray()));
#else
                matchedAttributesFromServices.AddRange(attrs.Select(af => new FieldInfo[0]));
#endif

                var returnTypeCSharpName = prop2.PropertyType.DisplayCsharp();

                var propModification = (getMethod?.IsPublic == true || setMethod?.IsPublic == true ? "public " : (getMethod?.Isreplacedembly == true || setMethod?.Isreplacedembly == true ? "internal " : (getMethod?.IsFamily == true || setMethod?.IsFamily == true ? "protected " : (getMethod?.IsPrivate == true || setMethod?.IsPrivate == true ? "private " : ""))));
                var propSetModification = (setMethod?.IsPublic == true ? "public " : (setMethod?.Isreplacedembly == true ? "internal " : (setMethod?.IsFamily == true ? "protected " : (setMethod?.IsPrivate == true ? "private " : ""))));
                var propGetModification = (getMethod?.IsPublic == true ? "public " : (getMethod?.Isreplacedembly == true ? "internal " : (getMethod?.IsFamily == true ? "protected " : (getMethod?.IsPrivate == true ? "private " : ""))));
                if (propSetModification == propModification) propSetModification = "";
                if (propGetModification == propModification) propGetModification = "";

                //if (getMethod.IsAbstract) sb.Append("abstract ");
                sb.Append([email protected]"

    {propModification}{(getMethod?.IsStatic == true ? "static " : "")}{(getMethod?.IsVirtual == true ? "override " : "")}{returnTypeCSharpName} {prop2.Name}
    {{");

                if (getMethod != null)
                {
                    if (getMethodAttributeAny == false) sb.Append([email protected]"
        {propGetModification} get
        {{
            return base.{prop2.Name}
        }}");
                    else sb.Append([email protected]"
        {propGetModification} get
        {{
            Exception __DP_ARG___exception = null;
            var __DP_ARG___is_return = false;
            object __DP_ARG___return_value = null;
            var __DP_ARG___parameters = new Dictionary<string, object>();
            {getMatchedAttributesCode(prop2.PropertyType, DynamicProxyInjectorType.PropertyGet, false, attrsIndex, "Before")}

            try
            {{
                if (__DP_ARG___is_return == false) __DP_ARG___return_value = base.{prop2.Name};
            }}
            catch (Exception __DP_ARG___ex)
            {{
                __DP_ARG___exception = __DP_ARG___ex;
            }}
            {getMatchedAttributesCode(prop2.PropertyType, DynamicProxyInjectorType.PropertyGet, false, attrsIndex, "After")}
            {getMatchedAttributesCodeReturn(prop2.PropertyType, DynamicProxyInjectorType.Method, false, null)}
        }}");
                }

                if (setMethod != null)
                {
                    if (setMethodAttributeAny == false) sb.Append([email protected]"
        {propSetModification} set
        {{
            base.{prop2.Name} = value;
        }}");
                    else sb.Append([email protected]"
        {propSetModification} set
        {{
            Exception __DP_ARG___exception = null;
            var __DP_ARG___is_return = false;
            object __DP_ARG___return_value = null;
            var __DP_ARG___parameters = new Dictionary<string, object>();
            __DP_ARG___parameters.Add(""value"", value);
            {getMatchedAttributesCode(prop2.PropertyType, DynamicProxyInjectorType.PropertySet, false, attrsIndex, "Before")}

            try
            {{
                if (__DP_ARG___is_return == false)
                {{{getMatchedAttributesCodeAuditParameter("value", prop2.PropertyType)}
                    base.{prop2.Name} = value;
                }}
            }}
            catch (Exception __DP_ARG___ex)
            {{
                __DP_ARG___exception = __DP_ARG___ex;
            }}
            {getMatchedAttributesCode(prop2.PropertyType, DynamicProxyInjectorType.PropertySet, false, attrsIndex, "After")}
        }}");
                }


                sb.Append([email protected]"
    }}");
            }
            #endregion

            string proxyCscode = "";
            replacedembly proxyreplacedembly = null;
            Type proxyType = null;

            if (matchedMemberInfos.Any())
            {
                #region Constructors
                sb = new StringBuilder();
                var fromServicesTypes = matchedAttributesFromServices.SelectMany(fs => fs).GroupBy(a => a.FieldType).Select((a, b) => new KeyValuePair<Type, string>(a.Key, $"__DP_ARG___FromServices_{b}")).ToDictionary(a => a.Key, a => a.Value);
                sb.Append(string.Join("", fromServicesTypes.Select(serviceType => [email protected]"
    private {serviceType.Key.DisplayCsharp()} {serviceType.Value};")));
                foreach (var ctor in ctors)
                {
                    var ctorParams = ctor.GetParameters();
                    sb.Append([email protected]"

    {(ctor.IsPrivate ? "private " : "")}{(ctor.IsFamily ? "protected " : "")}{(ctor.Isreplacedembly ? "internal " : "")}{(ctor.IsPublic ? "public " : "")}{clreplacedName}({string.Join(", ", ctorParams.Select(a => $"{a.ParameterType.DisplayCsharp()} {a.Name}"))}{
                        (ctorParams.Any() && fromServicesTypes.Any() ? ", " : "")}{
                        string.Join(", ", fromServicesTypes.Select(serviceType => [email protected]"{serviceType.Key.DisplayCsharp()} parameter{serviceType.Value}"))})
        : base({(string.Join(", ", ctorParams.Select(a => a.Name)))})
    {{{string.Join("", fromServicesTypes.Select(serviceType => [email protected]"
        {serviceType.Value} = parameter{serviceType.Value};"))}
    }}");
                }
                for (var a = 0; a < matchedAttributesFromServices.Count; a++)
                {
                    sb.Append([email protected]"

    private void __DP_ARG___attribute{a}_FromServicesCopyTo({_idynamicProxyName} attr)
    {{{string.Join("", matchedAttributesFromServices[a].Select(fs => [email protected]"
        __DP_Meta.{nameof(DynamicProxyMeta.SetDynamicProxyAttributePropertyValue)}({a}, attr, ""{fs.Name}"", {fromServicesTypes[fs.FieldType]});"))}
    }}");
                }
                #endregion

                proxyCscode = [email protected]"using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;

public clreplaced {clreplacedName} : {typeCSharpName}
{{
    private {_metaName} __DP_Meta = {typeof(DynamicProxy).DisplayCsharp()}.{nameof(GetAvailableMeta)}(typeof({typeCSharpName}));

    //这里要注释掉,如果重写的基类没有无参构造函数,会报错
    //public {clreplacedName}({_metaName} meta)
    //{{
    //    __DP_Meta = meta;
    //}}
    {sb.ToString()}
    {methodOverrideSb.ToString()}

    {propertyOverrideSb.ToString()}
}}";
                proxyreplacedembly = isCompile == false ? null : CompileCode(proxyCscode);
                proxyType = isCompile == false ? null : proxyreplacedembly.GetExportedTypes()/*.DefinedTypes*/.Where(a => a.FullName.EndsWith(clreplacedName)).FirstOrDefault();
            }
            methodOverrideSb.Clear();
            propertyOverrideSb.Clear();
            sb.Clear();
            return new DynamicProxyMeta(
                type, ctors,
                matchedMemberInfos.ToArray(), matchedAttributes.ToArray(),
                isCompile == false ? proxyCscode : null, clreplacedName, proxyreplacedembly, proxyType);
        }

19 View Source File : MainWindow.xaml.cs
License : MIT License
Project Creator : 3RD-Dimension

private void ButtonSaveViewport_Click(object sender, RoutedEventArgs e)
		{
			List<double> coords = new List<double>();

			coords.AddRange(new Vector3(viewport.Camera.Position).Array);
			coords.AddRange(new Vector3(viewport.Camera.LookDirection).Array);

			Properties.Settings.Default.ViewPortPos = string.Join(";", coords.Select(d => d.ToString()));
		}

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

public static string ToInterface(this MethodInfo method, bool isAlign = true)
        {
            if (method == null) return null;
            var sb = new StringBuilder();
            //if (method.IsPublic) sb.Append("public ");
            //if (method.Isreplacedembly) sb.Append("internal ");
            //if (method.IsFamily) sb.Append("protected ");
            //if (method.IsPrivate) sb.Append("private ");
            //if (method.IsPrivate) sb.Append("private ");
            //if (method.IsStatic) sb.Append("static ");
            //if (method.IsAbstract && method.DeclaringType.IsInterface == false) sb.Append("abstract ");
            //if (method.IsVirtual && method.DeclaringType.IsInterface == false) sb.Append(isOverride ? "override " : "virtual ");
            if (isAlign)
                sb.Append("        ");
            sb.Append(method.ReturnType.DisplayCsharp()).Append(" ").Append(method.Name);

            var genericParameters = method.GetGenericArguments();
            if (method.DeclaringType.IsNested && method.DeclaringType.DeclaringType.IsGenericType)
            {
                var dic = genericParameters.ToDictionary(a => a.Name);
                foreach (var nestedGenericParameter in method.DeclaringType.DeclaringType.GetGenericArguments())
                    if (dic.ContainsKey(nestedGenericParameter.Name))
                        dic.Remove(nestedGenericParameter.Name);
                genericParameters = dic.Values.ToArray();
            }
            if (genericParameters.Any())
                sb.Append("<")
                    .Append(string.Join(", ", genericParameters.Select(a => a.DisplayCsharp())))
                    .Append(">");

            sb.Append("(").Append(string.Join(", ", method.GetParameters().Select(a => $"{a.ParameterType.DisplayCsharp()} {a.Name}"))).Append(")");

            if (isAlign)
                sb.Append(";\r\n\r\n");

            return sb.ToString();
        }

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

public override string ToString() => $"{length}, {radix_tree_keys}, {radix_tree_nodes}, {last_generated_id}, [{string.Join("], [", entries?.Select(a => a?.ToString()))}], [{string.Join(", ", groups?.Select(a => a?.ToString()))}]";

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

static void Gen1(int tag, int scd)
        {
            if (tag == 0 && scd == 0) return;

            for (int whereable = 0; whereable <= tag; whereable++)
            {
                //Every time there is an scd, gen a no filter, and filtered (1,2) version.
                for (int ft = 0; ft < scd + 1; ft++)
                {
                    List<string> componentTypes = new List<string>();
                    List<string> whereableTypes = new List<string>();
                    List<string> whereableUsings = new List<string>();
                    List<string> whereableWhere = new List<string>();
                    List<string> scds = new List<string>();
                    List<string> args = new List<string>();
                    List<string> argsForward = new List<string>();
                    List<string> argsFilter = new List<string>();
                    for (int i = 0; i < tag; i++)
                    {
                        componentTypes.Add($"CD{i + 1}");
                        if (i < whereable)
                        {
                            whereableTypes.Add($"CD{i + 1}");
                            whereableUsings.Add($"using(var cd{i + 1}Cda = eq.ToComponentDataArray<CD{i + 1}>(Allocator.TempJob))");
                            whereableWhere.Add($"cd{i + 1}Cda[i]");
                        }
                    }
                    if (whereable != 0)
                    {
                        args.Add($"Func<{string.Join(",", whereableTypes)}, bool> where");
                        argsForward.Add("where");
                    }
                    for (int i = 0; i < scd; i++)
                    {
                        componentTypes.Add($"SCD{i + 1}");
                        if (i >= ft)
                        {
                            scds.Add($"filter{i + 1}");
                            args.Add($"SCD{i + 1} filter{i + 1}");
                            argsForward.Add($"filter{i + 1}");
                        }
                        else
                        {
                            args.Add($"bool nf{(scd > 1 ? (i + 1).ToString() : string.Empty)}");
                            argsForward.Add($"nf{(scd > 1 ? (i + 1).ToString() : string.Empty)}");
                        }
                    }
                    string typeHor = string.Join(",", componentTypes);
                    string argsString = scd > 0 || whereable > 0 ? string.Join(",", args) : string.Empty;
                    string wheres = string.Join("\n", componentTypes.Select(x =>
                    {
                        if (x.Contains("SCD"))
                        {
                            return $"where {x} : struct, ISharedComponentData";
                        }
                        else
                        {
                            return $"where {x} : struct, IComponentData";
                        }
                    }));
                    string typeVert = string.Join(",\n", componentTypes.Select(x => $"ComponentType.ReadOnly<{x}>()"));
                    string filters = scd > 0 && ft != scd ?
                    $"eq.SetSharedComponentFilter({string.Join(",", scds)});"
                    : string.Empty;

                    if (whereable == 0)
                    {
                        if (tag != 0)
                        {
                            Do(gsGetSingleton);
                        }
                        else
                        {
                            Do(gsGetSingletonScdFirst);
                        }

                        if (tag != 0)
                        {
                            Do(gsGet);
                        }
                    }

                    Do(gsGetSingletonEnreplacedy);
                    Do(gsEnreplacedyCount);
                    Do(gsEnreplacedies);

                    void Do(string tem)
                    {
                        sw.WriteLine(tem
                            .Replace("<<MAIN>>", componentTypes[0])
                            .Replace("<<NOFILTER>>", string.Empty)
                            .Replace("<<TYPEHOR>>", typeHor)
                            .Replace("<<ARGS>>", argsString)
                            .Replace("<<ARGSFORWARD>>", string.Join(",",argsForward))
                            .Replace("<<WHERE>>", wheres)
                            .Replace("<<TYPEVERT>>", typeVert)
                            .Replace("<<FILTER>>", filters)
                            .Replace("<<WHEREABLES>>", whereable == 0 ? string.Empty : whereableCheck.Replace("<<WHEREABLEUSINGS>>", string.Join("\n", whereableUsings)).Replace("<<WHEREABLEWHERE>>", string.Join(",", whereableWhere)))
                        );
                    }
                }
            }
        }

19 View Source File : X86Assembly.cs
License : MIT License
Project Creator : 20chan

public static string FromInline(ASM inst, IEnumerable<object> parameters)
        {
            return parameters.Count() == 0 ? inst.ToString() : $"{inst} {string.Join(", ", parameters)}";
        }

19 View Source File : MacroPatterns.cs
License : Apache License 2.0
Project Creator : aaaddress1

public static List<String> ImportMacroPattern(List<string> macrosToImport)
        {
            List<string> importedMacros = new List<string>();

            foreach (var macro in macrosToImport)
            {
                List<string> cellContent = macro.Split(";").ToList();
                //Replace the single ; separator with an unlikely separator like ;;;;; since shellcode can contain a single ;
                string importedMacro = string.Join(MacroColumnSeparator, cellContent.Select(ImportCellFormula));
                importedMacros.Add(importedMacro);
            }

            return importedMacros;
        }

19 View Source File : Form1.cs
License : MIT License
Project Creator : 1y0n

private void button1_Click(object sender, EventArgs e)
        {
            if ((textBox2.Enabled) && (textBox2.Text.Trim() == ""))
            {
                MessageBox.Show("注入进程时应按照要求填写进程名或 pid", "警告");
                return;
            }
            string file_type = comboBox1.Text;
            string target_arch = null;
            Compiler compiler = new Compiler();
            target_arch = " /platform:x86 /optimize ";

            switch (file_type)
            {
                case ".exe":
                    saveFileDialog1.Filter = "可执行文件|*.exe";
                    break;
                case ".js":
                    saveFileDialog1.Filter = "js脚本|*.js";
                    break;
                case ".xsl":
                    saveFileDialog1.Filter = "xsl文件|*.xsl";
                    break;
            }
            DialogResult dr = saveFileDialog1.ShowDialog();

            if (dr == DialogResult.OK && saveFileDialog1.FileName.Length > 0)
            {
                switch (file_type)
                {
                    case ".exe":
                        if (radioButton2.Checked)
                        {
                            target_arch = " /platform:x64 /optimize";
                        }

                        if (checkBox2.Checked)
                        {
                            target_arch += "/target:winexe ";
                        }

                        if (ico_filename != null)
                        {
                            target_arch += " /win32icon:" + ico_filename;
                        }

                        KEY = Random_Key();
                        List<string> temp_list = new List<string>();
                        foreach (byte i in KEY)
                        {
                            temp_list.Add("0x" + i.ToString("X2"));
                        }
                        KEY_String = string.Join(",", temp_list); //生成key的字符串形式,用于写入到文件


                        switch (comboBox4.Text)
                        {
                            case "直接执行(VirtualAlloc)":
                                TP_VirtualAlloc va = new TP_VirtualAlloc(KEY_String, Handle_Payload());
                                compiler.compileToExe(va.GetCode(), KEY_String, saveFileDialog1.FileName, target_arch);
                                break;
                            case "直接执行(VirtualProtect)":
                                TP_VirtualProtect vp = new TP_VirtualProtect(KEY_String, Handle_Payload());
                                compiler.compileToExe(vp.GetCode(), KEY_String, saveFileDialog1.FileName, target_arch);
                                break;
                            case "[x64]新进程注入(SYSCALL)":
                                TP_Syscall_New scn = new TP_Syscall_New(KEY_String, Handle_Payload(), textBox2.Text.Trim());
                                target_arch += " /unsafe"; //必需,因为包含了不安全代码
                                compiler.compileToExe(scn.GetCode(), KEY_String, saveFileDialog1.FileName, target_arch);
                                break;
                            case "新进程注入(VirtualAllocEx)":
                                TP_VirtualAllocEx vaex = new TP_VirtualAllocEx(KEY_String, Handle_Payload(), textBox2.Text);
                                compiler.compileToExe(vaex.GetCode(), KEY_String, saveFileDialog1.FileName, target_arch);
                                break;
                            case "注入现有进程(VirtualAllocEx)":
                                TP_VirtualAllocEx_Exist vaee = new TP_VirtualAllocEx_Exist(KEY_String, Handle_Payload(), Convert.ToInt32(textBox2.Text.Trim()));
                                compiler.compileToExe(vaee.GetCode(), KEY_String, saveFileDialog1.FileName, target_arch);
                                break;
                            case "[x64]注入现有进程(SYSCALL)":
                                TP_Syscall_Exist sce = new TP_Syscall_Exist(KEY_String, Handle_Payload(), Convert.ToInt32(textBox2.Text.Trim()));
                                target_arch += " /unsafe"; //必需,因为包含了不安全代码
                                compiler.compileToExe(sce.GetCode(), KEY_String, saveFileDialog1.FileName, target_arch);
                                break;
                            case "进程镂空(Process Hollowing)":
                                TP_Process_Hollowing ph = new TP_Process_Hollowing(KEY_String, Handle_Payload(), textBox2.Text);
                                target_arch += " /unsafe"; //必需,因为包含了不安全代码
                                compiler.compileToExe(ph.GetCode(), KEY_String, saveFileDialog1.FileName, target_arch);
                                break;
                        }
                        break;
                    default:
                        string temp = Generate_JS_XSL(file_type);
                        System.IO.File.WriteAllText(saveFileDialog1.FileName, temp);
                        break;
                }
                MessageBox.Show("All seems fine. Lets Hack the Plant!\r\n\r\nWARNING: 不要将生成的程序上传到在线杀毒网站!", "ALL SUCCESS!");
            }
        }

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

public string GetColumnAttribute(DbColumnInfo col, bool isInsertValueSql = false)
	{
		var sb = new List<string>();

		if (GetCsName(col.Name) != col.Name)
			sb.Add("Name = \"" + col.Name + "\"");

		if (col.CsType != null)
		{
			var dbinfo = fsql.CodeFirst.GetDbInfo(col.CsType);
			if (dbinfo != null && string.Compare(dbinfo.dbtypeFull.Replace("NOT NULL", "").Trim(), col.DbTypeTextFull, true) != 0)
			{
				#region StringLength 反向
				switch (fsql.Ado.DataType)
				{
					case DataType.MySql:
					case DataType.OdbcMySql:
						switch (col.DbTypeTextFull.ToLower())
						{
							case "longtext": sb.Add("StringLength = -2"); break;
							case "text": sb.Add("StringLength = -1"); break;
							default:
								var m_stringLength = Regex.Match(col.DbTypeTextFull, @"^varchar\s*\((\w+)\)$", RegexOptions.IgnoreCase);
								if (m_stringLength.Success) sb.Add($"StringLength = {m_stringLength.Groups[1].Value}");
								else sb.Add("DbType = \"" + col.DbTypeTextFull + "\"");
								break;
						}
						break;
					case DataType.SqlServer:
					case DataType.OdbcSqlServer:
						switch (col.DbTypeTextFull.ToLower())
						{
							case "nvarchar(max)": sb.Add("StringLength = -2"); break;
							default:
								var m_stringLength = Regex.Match(col.DbTypeTextFull, @"^nvarchar\s*\((\w+)\)$", RegexOptions.IgnoreCase);
								if (m_stringLength.Success) sb.Add($"StringLength = {m_stringLength.Groups[1].Value}");
								else sb.Add("DbType = \"" + col.DbTypeTextFull + "\"");
								break;
						}
						break;
					case DataType.PostgreSQL:
					case DataType.OdbcPostgreSQL:
					case DataType.OdbcKingbaseES:
					case DataType.ShenTong:
						switch (col.DbTypeTextFull.ToLower())
						{
							case "text": sb.Add("StringLength = -2"); break;
							default:
								var m_stringLength = Regex.Match(col.DbTypeTextFull, @"^varchar\s*\((\w+)\)$", RegexOptions.IgnoreCase);
								if (m_stringLength.Success) sb.Add($"StringLength = {m_stringLength.Groups[1].Value}");
								else sb.Add("DbType = \"" + col.DbTypeTextFull + "\"");
								break;
						}
						break;
					case DataType.Oracle:
					case DataType.OdbcOracle:
						switch (col.DbTypeTextFull.ToLower())
						{
							case "nclob": sb.Add("StringLength = -2"); break;
							default:
								var m_stringLength = Regex.Match(col.DbTypeTextFull, @"^nvarchar2\s*\((\w+)\)$", RegexOptions.IgnoreCase);
								if (m_stringLength.Success) sb.Add($"StringLength = {m_stringLength.Groups[1].Value}");
								else sb.Add("DbType = \"" + col.DbTypeTextFull + "\"");
								break;
						}
						break;
					case DataType.Dameng:
					case DataType.OdbcDameng:
						switch (col.DbTypeTextFull.ToLower())
						{
							case "text": sb.Add("StringLength = -2"); break;
							default:
								var m_stringLength = Regex.Match(col.DbTypeTextFull, @"^nvarchar2\s*\((\w+)\)$", RegexOptions.IgnoreCase);
								if (m_stringLength.Success) sb.Add($"StringLength = {m_stringLength.Groups[1].Value}");
								else sb.Add("DbType = \"" + col.DbTypeTextFull + "\"");
								break;
						}
						break;
					case DataType.Sqlite:
						switch (col.DbTypeTextFull.ToLower())
						{
							case "text": sb.Add("StringLength = -2"); break;
							default:
								var m_stringLength = Regex.Match(col.DbTypeTextFull, @"^nvarchar\s*\((\w+)\)$", RegexOptions.IgnoreCase);
								if (m_stringLength.Success) sb.Add($"StringLength = {m_stringLength.Groups[1].Value}");
								else sb.Add("DbType = \"" + col.DbTypeTextFull + "\"");
								break;
						}
						break;
					case DataType.MsAccess:
						switch (col.DbTypeTextFull.ToLower())
						{
							case "longtext": sb.Add("StringLength = -2"); break;
							default:
								var m_stringLength = Regex.Match(col.DbTypeTextFull, @"^varchar\s*\((\w+)\)$", RegexOptions.IgnoreCase);
								if (m_stringLength.Success) sb.Add($"StringLength = {m_stringLength.Groups[1].Value}");
								else sb.Add("DbType = \"" + col.DbTypeTextFull + "\"");
								break;
						}
						break;
				}
				#endregion
			}
			if (col.IsPrimary)
				sb.Add("IsPrimary = true");
			if (col.IsIdenreplacedy)
				sb.Add("IsIdenreplacedy = true");

			if (dbinfo != null && dbinfo.isnullable != col.IsNullable)
			{
				if (col.IsNullable && fsql.DbFirst.GetCsType(col).Contains("?") == false && col.CsType.IsValueType)
					sb.Add("IsNullable = true");
				if (col.IsNullable == false && fsql.DbFirst.GetCsType(col).Contains("?") == true)
					sb.Add("IsNullable = false");
			}

			if (isInsertValueSql)
			{
				var defval = GetColumnDefaultValue(col, false);
				if (defval == null) //c#默认属性值,就不需要设置 InsertValueSql 了
				{
					defval = GetColumnDefaultValue(col, true);
					if (defval != null)
					{
						sb.Add("InsertValueSql = \"" + defval.Replace("\"", "\\\"") + "\"");
						sb.Add("CanInsert = false");
					}
				}
				else
					sb.Add("CanInsert = false");
			}
		}
		if (sb.Any() == false) return null;
		return "[Column(" + string.Join(", ", sb) + ")]";
	}

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

static string DisplayCsharp(this MethodInfo method, bool isOverride)
    {
        if (method == null) return null;
        var sb = new StringBuilder();
        if (method.IsPublic) sb.Append("public ");
        if (method.Isreplacedembly) sb.Append("internal ");
        if (method.IsFamily) sb.Append("protected ");
        if (method.IsPrivate) sb.Append("private ");
        if (method.IsPrivate) sb.Append("private ");
        if (method.IsStatic) sb.Append("static ");
        if (method.IsAbstract && method.DeclaringType.IsInterface == false) sb.Append("abstract ");
        if (method.IsVirtual && method.DeclaringType.IsInterface == false) sb.Append(isOverride ? "override " : "virtual ");
        sb.Append(method.ReturnType.DisplayCsharp()).Append(" ").Append(method.Name);

        var genericParameters = method.GetGenericArguments();
        if (method.DeclaringType.IsNested && method.DeclaringType.DeclaringType.IsGenericType)
        {
            var dic = genericParameters.ToDictionary(a => a.Name);
            foreach (var nestedGenericParameter in method.DeclaringType.DeclaringType.GetGenericArguments())
                if (dic.ContainsKey(nestedGenericParameter.Name))
                    dic.Remove(nestedGenericParameter.Name);
            genericParameters = dic.Values.ToArray();
        }
        if (genericParameters.Any())
            sb.Append("<")
                .Append(string.Join(", ", genericParameters.Select(a => a.DisplayCsharp())))
                .Append(">");

        sb.Append("(").Append(string.Join(", ", method.GetParameters().Select(a => $"{a.ParameterType.DisplayCsharp()} {a.Name}"))).Append(")");
        return sb.ToString();
    }

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

public override string ToString() => $"{_replication_offset} {string.Join("], [", _slaves.Select(a => a?.ToString()))}";

19 View Source File : LoremFuzzer.cs
License : Apache License 2.0
Project Creator : 42skillz

public string GenerateText(int? nbOfParagraphs = null)
        {
            var paragraphs = GenerateParagraphs(nbOfParagraphs);

            var text = string.Join(Environment.NewLine + Environment.NewLine, paragraphs);

            return text;
        }

19 View Source File : RouteGenerator.cs
License : MIT License
Project Creator : 188867052

private static string GeneraParameters(IList<ParameterInfo> parameters, bool hasType, bool hasPre)
        {
            StringBuilder sb = new StringBuilder();
            IList<string> list = new List<string>();
            if (parameters != null && parameters.Count > 0)
            {
                foreach (var item in parameters)
                {
                    if (hasType)
                    {
                        list.Add($"{item.Type} {item.Name}");
                    }
                    else
                    {
                        list.Add($"{item.Name}");
                    }
                }

                sb.Append((hasPre ? ", " : string.Empty) + string.Join(", ", list));
            }

            return sb.ToString();
        }

19 View Source File : Richtext.cs
License : MIT License
Project Creator : 499116344

public override string ToString()
        {
            return string.Join("", Snippets);
        }

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

public override string ToString() => $"{name}, {seen_time}, {pel_count}, [{string.Join("], [", pending?.Select(a => a?.ToString()))}]";

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

public override string ToString() => $"orderby {string.Join(", ", Orderings)}";

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

private string ResovleInsert(bool idenreplacedy)
        {
            var table = GetTableMetaInfo().TableName;
            var filters = new GroupExpressionResovle(_filterExpression).Resovle().Split(',');
            var columns = GetColumnMetaInfos();
            var intcolumns = columns
                .Where(a => !filters.Contains(a.ColumnName) && !a.IsNotMapped && !a.IsIdenreplacedy)
                .Where(a => !a.IsComplexType)
                .Where(a => !a.IsDefault || (_parameters.ContainsKey(a.CsharpName) && _parameters[a.CsharpName] != null));//如果是默认字段
            var columnNames = string.Join(",", intcolumns.Select(s => s.ColumnName));
            var parameterNames = string.Join(",", intcolumns.Select(s => $"@{s.CsharpName}"));
            var sql = $"INSERT INTO {table}({columnNames}) VALUES ({parameterNames})";
            if (idenreplacedy)
            {
                sql = $"{sql};SELECT @@IDENreplacedY";
            }
            return sql;
        }

19 View Source File : Database.cs
License : Apache License 2.0
Project Creator : aadreja

internal virtual void CreateAddCommand(IDbCommand cmd, object enreplacedy, IAuditTrail audit = null, string columnNames = null, bool doNotAppendCommonFields = false, bool overrideCreatedUpdatedOn = false)
        {
            TableAttribute tableInfo = EnreplacedyCache.Get(enreplacedy.GetType());

            if (tableInfo.NeedsHistory && tableInfo.IsCreatedByEmpty(enreplacedy))
                throw new MissingFieldException("CreatedBy is required when Audit Trail is enabled");

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

            if (!string.IsNullOrEmpty(columnNames)) columns.AddRange(columnNames.Split(','));
            else columns.AddRange(tableInfo.DefaultInsertColumns);//Get columns from Enreplacedy attributes loaded in TableInfo

            bool isPrimaryKeyEmpty = false;

            foreach(ColumnAttribute pkCol in tableInfo.Columns.Where(p=>p.Value.IsPrimaryKey).Select(p=>p.Value))
            {
                if (pkCol.PrimaryKeyInfo.IsIdenreplacedy && tableInfo.IsKeyIdEmpty(enreplacedy, pkCol))
                {
                    isPrimaryKeyEmpty = true;
                    //if idenreplacedy remove keyfield if added in field list
                    columns.Remove(pkCol.Name);
                }
                else if (pkCol.Property.PropertyType == typeof(Guid) && tableInfo.IsKeyIdEmpty(enreplacedy, pkCol))
                {
                    isPrimaryKeyEmpty = true;
                    //if not idenreplacedy and key not generated, generate before save
                    tableInfo.SetKeyId(enreplacedy, pkCol, Guid.NewGuid());
                }
            }

            #region append common columns

            if (!doNotAppendCommonFields)
            {
                if (!tableInfo.NoIsActive)
                {
                    if (!columns.Contains(Config.ISACTIVE_COLUMN.Name))
                        columns.Add(Config.ISACTIVE_COLUMN.Name);

                    bool isActive = tableInfo.GetIsActive(enreplacedy) ?? true;
                    //when IsActive is not set then true for insert
                    cmd.AddInParameter("@" + Config.ISACTIVE_COLUMN.Name, Config.ISACTIVE_COLUMN.ColumnDbType, isActive);

                    if (tableInfo.NeedsHistory)
                        audit.AppendDetail(Config.ISACTIVE_COLUMN.Name, isActive, DbType.Boolean, null);

                    tableInfo.SetIsActive(enreplacedy, isActive); //Set IsActive value
                }

                if (!tableInfo.NoVersionNo)
                {
                    int versionNo = tableInfo.GetVersionNo(enreplacedy) ?? 1;  //set defualt versionno 1 for Insert
                    if (versionNo == 0) versionNo = 1; //set defualt versionno 1 for Insert even if its zero or null

                    if (!columns.Contains(Config.VERSIONNO_COLUMN.Name))
                        columns.Add(Config.VERSIONNO_COLUMN.Name);

                    cmd.AddInParameter("@" + Config.VERSIONNO_COLUMN.Name, Config.VERSIONNO_COLUMN.ColumnDbType, versionNo);

                    tableInfo.SetVersionNo(enreplacedy, versionNo); //Set VersionNo value
                }

                if (!tableInfo.NoCreatedBy)
                {
                    if (!columns.Contains(Config.CREATEDBY_COLUMN.Name))
                        columns.Add(Config.CREATEDBY_COLUMN.Name);

                    cmd.AddInParameter("@" + Config.CREATEDBY_COLUMN.Name, Config.CREATEDBY_COLUMN.ColumnDbType, tableInfo.GetCreatedBy(enreplacedy));
                }

                if (!tableInfo.NoCreatedOn & !columns.Contains(Config.CREATEDON_COLUMN.Name))
                {
                    columns.Add(Config.CREATEDON_COLUMN.Name);
                }

                if (!tableInfo.NoUpdatedBy)
                {
                    if (!columns.Contains(Config.UPDATEDBY_COLUMN.Name))
                        columns.Add(Config.UPDATEDBY_COLUMN.Name);

                    cmd.AddInParameter("@" + Config.UPDATEDBY_COLUMN.Name, Config.UPDATEDBY_COLUMN.ColumnDbType, tableInfo.GetCreatedBy(enreplacedy));
                }

                if (!tableInfo.NoUpdatedOn & !columns.Contains(Config.UPDATEDON_COLUMN.Name))
                {
                    columns.Add(Config.UPDATEDON_COLUMN.Name);
                }
            }

            #endregion

            //append @ before each fields to add as parameter
            List<string> parameters = columns.Select(c => "@" + c).ToList();

            int pIndex = parameters.FindIndex(c => c == "@" + Config.CREATEDON_COLUMN.Name);
            if (pIndex >= 0)
            {
                var createdOn = Helper.GetDateTimeOrDatabaseDateTimeSQL(tableInfo.GetCreatedOn(enreplacedy), this, overrideCreatedUpdatedOn);
                if (createdOn is string)
                {
                    parameters[pIndex] = (string)createdOn;
                }
                else
                {
                    cmd.AddInParameter(parameters[pIndex], Config.CREATEDON_COLUMN.ColumnDbType, createdOn);
                }
                //parameters[pIndex] = (string)Helper.GetDateTimeOrDatabaseDateTimeSQL(tableInfo.GetCreatedOn(enreplacedy), this, overrideCreatedUpdatedOn);
            }

            pIndex = parameters.FindIndex(c => c == "@" + Config.UPDATEDON_COLUMN.Name);
            if (pIndex >= 0)
            {
                var updatedOn = Helper.GetDateTimeOrDatabaseDateTimeSQL(tableInfo.GetUpdatedOn(enreplacedy), this, overrideCreatedUpdatedOn);
                if (updatedOn is string)
                {
                    parameters[pIndex] = (string)updatedOn;
                }
                else
                {
                    cmd.AddInParameter(parameters[pIndex], Config.CREATEDON_COLUMN.ColumnDbType, updatedOn);
                }
                //parameters[pIndex] = (string)Helper.GetDateTimeOrDatabaseDateTimeSQL(tableInfo.GetUpdatedOn(enreplacedy), this, overrideCreatedUpdatedOn);
            }

            StringBuilder cmdText = new StringBuilder();
            cmdText.Append($"INSERT INTO {tableInfo.FullName} ({string.Join(",", columns)}) VALUES({string.Join(",", parameters)});");

            if (tableInfo.IsKeyIdenreplacedy() && isPrimaryKeyEmpty)
            {
                //add query to get inserted id
                cmdText.Append(LASTINSERTEDROWIDSQL);
            }

            //remove common columns and parameters already added above
            columns.RemoveAll(c => c == Config.CREATEDON_COLUMN.Name || c == Config.CREATEDBY_COLUMN.Name
                                    || c == Config.UPDATEDON_COLUMN.Name || c == Config.UPDATEDBY_COLUMN.Name
                                    || c == Config.VERSIONNO_COLUMN.Name || c == Config.ISACTIVE_COLUMN.Name);

            cmd.CommandType = CommandType.Text;
            cmd.CommandText = cmdText.ToString();

            for (int i = 0; i < columns.Count(); i++)
            {
                tableInfo.Columns.TryGetValue(columns[i], out ColumnAttribute columnInfo); //find column attribute

                DbType dbType = DbType.Object;
                object columnValue = null;

                if (columnInfo != null && columnInfo.GetMethod != null)
                {
                    dbType = columnInfo.ColumnDbType;
                    columnValue = columnInfo.GetAction(enreplacedy);

                    if (tableInfo.NeedsHistory) audit.AppendDetail(columns[i], columnValue, dbType, null);
                }
                cmd.AddInParameter("@" + columns[i], dbType, columnValue);
            }
        }

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

public string GetColumnAttribute(DbColumnInfo col) {
		var sb = new List<string>();

		if (GetCsName(col.Name) != col.Name)
			sb.Add("Name = \"" + col.Name + "\"");

		var dbinfo = fsql.CodeFirst.GetDbInfo(col.CsType);
		if (dbinfo != null && string.Compare(dbinfo.dbtypeFull.Replace("NOT NULL", "").Trim(), col.DbTypeTextFull, true) != 0)
			sb.Add("DbType = \"" + col.DbTypeTextFull + "\"");
		if (col.IsPrimary)
			sb.Add("IsPrimary = true");
		if (col.IsIdenreplacedy)
			sb.Add("IsIdenreplacedy = true");

		if (dbinfo != null && dbinfo.isnullable != col.IsNullable) {
			if (col.IsNullable && fsql.DbFirst.GetCsType(col).Contains("?") == false && col.CsType.IsValueType)
				sb.Add("IsNullable = true");
			if (col.IsNullable == false && fsql.DbFirst.GetCsType(col).Contains("?") == true)
				sb.Add("IsNullable = false");
		}
		if (sb.Any() == false) return null;
		return "[Column(" + string.Join(", ", sb) + ")]";
	}

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

public string GetTableAttribute()
	{
		var sb = new List<string>();

		if (GetCsName(this.FullTableName) != this.FullTableName)
		{
			if (this.FullTableName.IndexOf('.') == -1)
				sb.Add("Name = \"" + this.FullTableName + "\"");
			else
				sb.Add("Name = \"" + this.FullTableName + "\""); //Todo: QuoteSqlName
		}

		sb.Add("DisableSyncStructure = true");
		if (sb.Any() == false) return null;
		return "[Table(" + string.Join(", ", sb) + ")]";
	}

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

private string ResovleBatchInsert(IEnumerable<T> enreplacedys)
        {
            var table = GetTableMetaInfo().TableName;
            var filters = new GroupExpressionResovle(_filterExpression).Resovle().Split(',');
            var columns = GetColumnMetaInfos()
                .Where(a => !a.IsComplexType).ToList();
            var intcolumns = columns
                .Where(a => !filters.Contains(a.ColumnName) && !a.IsNotMapped && !a.IsIdenreplacedy)
                .ToList();
            var columnNames = string.Join(",", intcolumns.Select(s => s.ColumnName));
            if (_context.DbContextType == DbContextType.Mysql)
            {
                var buffer = new StringBuilder();
                buffer.Append($"INSERT INTO {table}({columnNames}) VALUES ");
                var serializer = GlobalSettings.EnreplacedyMapperProvider.GetDeserializer(typeof(T));
                var list = enreplacedys.ToList();
                for (var i = 0; i < list.Count; i++)
                {
                    var item = list[i];
                    var values = serializer(item);
                    buffer.Append("(");
                    for (var j = 0; j < intcolumns.Count; j++)
                    {
                        var column = intcolumns[j];
                        var value = values[column.CsharpName];
                        if (value == null)
                        {
                            buffer.Append(column.IsDefault ? "DEFAULT" : "NULL");
                        }
                        else if (column.CsharpType == typeof(bool) || column.CsharpType == typeof(bool?))
                        {
                            buffer.Append(Convert.ToBoolean(value) == true ? 1 : 0);
                        }
                        else if (column.CsharpType == typeof(DateTime) || column.CsharpType == typeof(DateTime?))
                        {
                            buffer.Append($"'{value}'");
                        }
                        else if (column.CsharpType.IsValueType || (Nullable.GetUnderlyingType(column.CsharpType)?.IsValueType == true))
                        {
                            buffer.Append(value);
                        }
                        else
                        {
                            var str = SqlEncoding(value.ToString());
                            buffer.Append($"'{str}'");
                        }
                        if (j + 1 < intcolumns.Count)
                        {
                            buffer.Append(",");
                        }
                    }
                    buffer.Append(")");
                    if (i + 1 < list.Count)
                    {
                        buffer.Append(",");
                    }
                }
                return buffer.Remove(buffer.Length - 1, 0).ToString();
            }
            throw new NotImplementedException();
        }

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

public static string ToProxy(this MethodInfo method)
        {
            if (method == null) return null;
            var sb = new StringBuilder();
            sb.Append("        public ");

            var returnType = method.ReturnType;
            var isNoResultAsync = returnType == typeof(Task) || returnType == typeof(ValueTask);
            var isGenericAsync = returnType.IsGenericType && (returnType.GetGenericTypeDefinition() == typeof(ValueTask<>) || returnType.GetGenericTypeDefinition() == typeof(Task<>));
            var isAsync = isGenericAsync || isNoResultAsync;

            if (isAsync)
                sb.Append("async ");

            var funcInfo = method.ToInterface(false);
            sb.AppendLine(funcInfo);
            sb.AppendLine("        {");

            var isResult = false;

            if (isAsync)
            {
                sb.AppendLine($"            await _context.BeforeAsync(typeof(RedisClient).GetMethod({method.Name}))");
            }
            else
            {
                sb.AppendLine($"            _context.Before(typeof(RedisClient).GetMethod({method.Name}))");
            }

            if (isAsync)
            {
                if (isNoResultAsync)
                    sb.Append("            await _redisClient.").Append(method.Name);
                else
                {
                    isResult = true;
                    sb.Append("            var result = await _redisClient.").Append(method.Name);
                }
            }
            else
            {
                if (returnType == typeof(void))
                {
                    sb.Append("            _redisClient.").Append(method.Name);
                }
                else
                {
                    isResult = true;
                    sb.Append("            var result = _redisClient.").Append(method.Name);
                }
            }

            var genericParameters = method.GetGenericArguments();
            if (method.DeclaringType.IsNested && method.DeclaringType.DeclaringType.IsGenericType)
            {
                var dic = genericParameters.ToDictionary(a => a.Name);
                foreach (var nestedGenericParameter in method.DeclaringType.DeclaringType.GetGenericArguments())
                    if (dic.ContainsKey(nestedGenericParameter.Name))
                        dic.Remove(nestedGenericParameter.Name);
                genericParameters = dic.Values.ToArray();
            }
            if (genericParameters.Any())
                sb.Append("<")
                    .Append(string.Join(", ", genericParameters.Select(a => a.DisplayCsharp())))
                    .Append(">");

            sb.Append("(").Append(string.Join(", ", method.GetParameters().Select(a => $" {a.Name}"))).AppendLine(");");

            if (isAsync)
            {
                sb.AppendLine($"            await _context.AfterAsync(typeof(RedisClient).GetMethod({method.Name}))");
            }
            else
            {
                sb.AppendLine($"            _context.After(typeof(RedisClient).GetMethod({method.Name}))");
            }

            if (isResult)
                sb.AppendLine("            return result;");

            sb.Append("        }\r\n\r\n");
            return sb.ToString();
        }

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

[Fact]
		public void Command()
		{
			string UFString(string text)
			{
				if (text.Length <= 1) return text.ToUpper();
				else return text.Substring(0, 1).ToUpper() + text.Substring(1, text.Length - 1);
			}

			var rt = rds.Command();
			var sb = string.Join("\r\n\r\n", (rt.Value).OrderBy(a1 => (a1 as List<object>)[0].ToString()).Select(a1 =>
			{
				var a = a1 as List<object>;
				var plen = int.Parse(a[1].ToString());
				var firstKey = int.Parse(a[3].ToString());
				var lastKey = int.Parse(a[4].ToString());
				var stepCount = int.Parse(a[5].ToString());
				var parms = "";
				if (plen > 1)
				{
					for (var x = 1; x < plen; x++)
					{
						if (x == firstKey) parms += "string key, ";
						else parms += "string parm, ";
					}
					parms = parms.Remove(parms.Length - 2);
				}
				if (plen < 0)
				{
					for (var x = 1; x < -plen; x++)
					{
						if (x == firstKey) parms += "string key, ";
						else parms += "string parm, ";
					}
					if (parms.Length > 0)
						parms = parms.Remove(parms.Length - 2);
				}
				
				return [email protected]"
//{string.Join(", ", a[2] as List<object>)}
//{string.Join(", ", a[6] as List<object>)}
public void {UFString(a[0].ToString())}({parms}) {{ }}";
			}));
		}

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

public string GetCsName(string name) {
		name = Regex.Replace(name.TrimStart('@', '.'), @"[^\w]", "_");
		name = char.IsLetter(name, 0) ? name : string.Concat("_", name);
		if (task.OptionsEnreplacedy01) name = UFString(name);
		if (task.OptionsEnreplacedy02) name = UFString(name.ToLower());
		if (task.OptionsEnreplacedy03) name = name.ToLower();
		if (task.OptionsEnreplacedy04) name = string.Join("", name.Split('_').Select(a => UFString(a)));
		return name;
	}

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

internal static string DisplayCsharp(this MethodInfo method, bool isOverride)
        {
            if (method == null) return null;
            var sb = new StringBuilder();
            if (method.IsPublic) sb.Append("public ");
            if (method.Isreplacedembly) sb.Append("internal ");
            if (method.IsFamily) sb.Append("protected ");
            if (method.IsPrivate) sb.Append("private ");
            if (method.IsPrivate) sb.Append("private ");
            if (method.IsStatic) sb.Append("static ");
            if (method.IsAbstract && method.DeclaringType.IsInterface == false) sb.Append("abstract ");
            if (method.IsVirtual && method.DeclaringType.IsInterface == false) sb.Append(isOverride ? "override " : "virtual ");
            sb.Append(method.ReturnType.DisplayCsharp()).Append(" ").Append(method.Name);

            var genericParameters = method.GetGenericArguments();
            if (method.DeclaringType.IsNested && method.DeclaringType.DeclaringType.IsGenericType)
            {
                var dic = genericParameters.ToDictionary(a => a.Name);
                foreach (var nestedGenericParameter in method.DeclaringType.DeclaringType.GetGenericArguments())
                    if (dic.ContainsKey(nestedGenericParameter.Name))
                        dic.Remove(nestedGenericParameter.Name);
                genericParameters = dic.Values.ToArray();
            }
            if (genericParameters.Any())
                sb.Append("<")
                    .Append(string.Join(", ", genericParameters.Select(a => a.DisplayCsharp())))
                    .Append(">");

            sb.Append("(").Append(string.Join(", ", method.GetParameters().Select(a => $"{a.ParameterType.DisplayCsharp()} {a.Name}"))).Append(")");
            return sb.ToString();
        }

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

public static KeyValuePair<string, int> SplitHost(string host)
        {
            if (string.IsNullOrWhiteSpace(host?.Trim()))
                return new KeyValuePair<string, int>("127.0.0.1", 6379);

            host = host.Trim();
            var ipv6 = Regex.Match(host, @"^\[([^\]]+)\]\s*(:\s*(\d+))?$");
            if (ipv6.Success) //ipv6+port 格式: [fe80::b164:55b3:4b4f:7ce6%15]:6379
                return new KeyValuePair<string, int>(ipv6.Groups[1].Value.Trim(), 
                    int.TryParse(ipv6.Groups[3].Value, out var tryint) && tryint > 0 ? tryint : 6379);

            var spt = (host ?? "").Split(':');
            if (spt.Length == 1) //ipv4 or domain
                return new KeyValuePair<string, int>(string.IsNullOrWhiteSpace(spt[0].Trim()) == false ? spt[0].Trim() : "127.0.0.1", 6379);

            if (spt.Length == 2) //ipv4:port or domain:port
            {
                if (int.TryParse(spt.Last().Trim(), out var testPort2))
                    return new KeyValuePair<string, int>(string.IsNullOrWhiteSpace(spt[0].Trim()) == false ? spt[0].Trim() : "127.0.0.1", testPort2);

                return new KeyValuePair<string, int>(host, 6379);
            }

            if (IPAddress.TryParse(host, out var tryip) && tryip.AddressFamily == AddressFamily.InterNetworkV6) //test ipv6
                return new KeyValuePair<string, int>(host, 6379);

            if (int.TryParse(spt.Last().Trim(), out var testPort)) //test ipv6:port
            {
                var testHost = string.Join(":", spt.Where((a, b) => b < spt.Length - 1));
                if (IPAddress.TryParse(testHost, out tryip) && tryip.AddressFamily == AddressFamily.InterNetworkV6)
                    return new KeyValuePair<string, int>(testHost, 6379);
            }

            return new KeyValuePair<string, int>(host, 6379);
        }

19 View Source File : GCodeParser.cs
License : MIT License
Project Creator : 3RD-Dimension

static void Parse(string line, int lineNumber)
		{
			MatchCollection matches = GCodeSplitter.Matches(line);

			List<Word> Words = new List<Word>(matches.Count);

			foreach (Match match in matches)
			{
				Words.Add(new Word() { Command = match.Groups[1].Value[0], Parameter = double.Parse(match.Groups[2].Value, Constants.DecimalParseFormat) });
			}

			for (int i = 0; i < Words.Count; i++)
			{
				if (Words[i].Command == 'N')
				{
					Words.RemoveAt(i--);
					continue;
				}

				if (IgnoreAxes.Contains(Words[i].Command) && Properties.Settings.Default.IgnoreAdditionalAxes)
				{
					Words.RemoveAt(i--);
					continue;
				}

				if (!ValidWords.Contains(Words[i].Command))
				{
					Warnings.Add($"ignoring unknown word (letter): \"{Words[i]}\". (line {lineNumber})");
					Words.RemoveAt(i--);
					continue;
				}

				if (Words[i].Command != 'F')
					continue;

				State.Feed = Words[i].Parameter;
				if (State.Unit == ParseUnit.Imperial)
					State.Feed *= 25.4;
				Words.RemoveAt(i--);
				continue;
			}

			for (int i = 0; i < Words.Count; i++)
			{
				if (Words[i].Command == 'M')
				{
					int param = (int)Words[i].Parameter;

					if (param != Words[i].Parameter || param < 0)
						throw new ParseException("M code can only have positive integer parameters", lineNumber);

					Commands.Add(new MCode() { Code = param, LineNumber = lineNumber });

					Words.RemoveAt(i);
					i--;
					continue;
				}

				if (Words[i].Command == 'S')
				{
					double param = Words[i].Parameter;

					if (param < 0)
						Warnings.Add($"spindle speed must be positive. (line {lineNumber})");

					Commands.Add(new Spindle() { Speed = Math.Abs(param), LineNumber = lineNumber });

					Words.RemoveAt(i);
					i--;
					continue;
				}

				if (Words[i].Command == 'G' && !MotionCommands.Contains(Words[i].Parameter))
				{
					#region UnitPlaneDistanceMode

					double param = Words[i].Parameter;

					if (param == 90)
					{
						State.DistanceMode = ParseDistanceMode.Absolute;
						Words.RemoveAt(i);
						i--;
						continue;
					}
					if (param == 91)
					{
						State.DistanceMode = ParseDistanceMode.Incremental;
						Words.RemoveAt(i);
						i--;
						continue;
					}
					if (param == 90.1)
					{
						State.ArcDistanceMode = ParseDistanceMode.Absolute;
						Words.RemoveAt(i);
						continue;
					}
					if (param == 91.1)
					{
						State.ArcDistanceMode = ParseDistanceMode.Incremental;
						Words.RemoveAt(i);
						i--;
						continue;
					}
					if (param == 21)
					{
						State.Unit = ParseUnit.Metric;
						Words.RemoveAt(i);
						i--;
						continue;
					}
					if (param == 20)
					{
						State.Unit = ParseUnit.Imperial;
						Words.RemoveAt(i);
						i--;
						continue;
					}
					if (param == 17)
					{
						State.Plane = ArcPlane.XY;
						Words.RemoveAt(i);
						i--;
						continue;
					}
					if (param == 18)
					{
						State.Plane = ArcPlane.ZX;
						Words.RemoveAt(i);
						i--;
						continue;
					}
					if (param == 19)
					{
						State.Plane = ArcPlane.YZ;
						Words.RemoveAt(i);
						i--;
						continue;
					}
					if (param == 4)
					{
						if (Words.Count >= 2 && Words[i + 1].Command == 'P')
						{
							if (Words[i + 1].Parameter < 0)
								Warnings.Add($"dwell time must be positive. (line {lineNumber})");

							Commands.Add(new Dwell() { Seconds = Math.Abs(Words[i + 1].Parameter), LineNumber = lineNumber });
							Words.RemoveAt(i + 1);
							Words.RemoveAt(i);
							i--;
							continue;
						}
					}

					Warnings.Add($"ignoring unknown command G{param}. (line {lineNumber})");
					Words.RemoveAt(i--);
					#endregion
				}
			}

			if (Words.Count == 0)
				return;

			int MotionMode = State.LastMotionMode;

			if (Words.First().Command == 'G')
			{
				MotionMode = (int)Words.First().Parameter;
				State.LastMotionMode = MotionMode;
				Words.RemoveAt(0);
			}

			if (MotionMode < 0)
				throw new ParseException("no motion mode active", lineNumber);

			double UnitMultiplier = (State.Unit == ParseUnit.Metric) ? 1 : 25.4;

			Vector3 EndPos = State.Position;

			if (State.DistanceMode == ParseDistanceMode.Incremental && State.PositionValid.Any(isValid => !isValid))
			{
				throw new ParseException("incremental motion is only allowed after an absolute position has been established (eg. with \"G90 G0 X0 Y0 Z5\")", lineNumber);
			}

			if ((MotionMode == 2 || MotionMode == 3) && State.PositionValid.Any(isValid => !isValid))
			{
				throw new ParseException("arcs (G2/G3) are only allowed after an absolute position has been established (eg. with \"G90 G0 X0 Y0 Z5\")", lineNumber);
			}

			#region FindEndPos
			{
				int Incremental = (State.DistanceMode == ParseDistanceMode.Incremental) ? 1 : 0;

				for (int i = 0; i < Words.Count; i++)
				{
					if (Words[i].Command != 'X')
						continue;
					EndPos.X = Words[i].Parameter * UnitMultiplier + Incremental * EndPos.X;
					Words.RemoveAt(i);
					State.PositionValid[0] = true;
					break;
				}

				for (int i = 0; i < Words.Count; i++)
				{
					if (Words[i].Command != 'Y')
						continue;
					EndPos.Y = Words[i].Parameter * UnitMultiplier + Incremental * EndPos.Y;
					Words.RemoveAt(i);
					State.PositionValid[1] = true;
					break;
				}

				for (int i = 0; i < Words.Count; i++)
				{
					if (Words[i].Command != 'Z')
						continue;
					EndPos.Z = Words[i].Parameter * UnitMultiplier + Incremental * EndPos.Z;
					Words.RemoveAt(i);
					State.PositionValid[2] = true;
					break;
				}
			}
			#endregion

			if (MotionMode != 0 && State.Feed <= 0)
			{
				throw new ParseException("feed rate undefined", lineNumber);
			}

			if (MotionMode == 1 && State.PositionValid.Any(isValid => !isValid))
			{
				Warnings.Add($"a feed move is used before an absolute position is established, height maps will not be applied to this motion. (line {lineNumber})");
			}

			if (MotionMode <= 1)
			{
				if (Words.Count > 0)
					Warnings.Add($"motion command must be last in line (ignoring unused words {string.Join(" ", Words)} in block). (line {lineNumber})");

				Line motion = new Line();
				motion.Start = State.Position;
				motion.End = EndPos;
				motion.Feed = State.Feed;
				motion.Rapid = MotionMode == 0;
				motion.LineNumber = lineNumber;
				State.PositionValid.CopyTo(motion.PositionValid, 0);

				Commands.Add(motion);
				State.Position = EndPos;
				return;
			}

			double U, V;

			bool IJKused = false;

			switch (State.Plane)
			{
				default:
					U = State.Position.X;
					V = State.Position.Y;
					break;
				case ArcPlane.YZ:
					U = State.Position.Y;
					V = State.Position.Z;
					break;
				case ArcPlane.ZX:
					U = State.Position.Z;
					V = State.Position.X;
					break;
			}

			#region FindIJK
			{
				int ArcIncremental = (State.ArcDistanceMode == ParseDistanceMode.Incremental) ? 1 : 0;

				for (int i = 0; i < Words.Count; i++)
				{
					if (Words[i].Command != 'I')
						continue;

					switch (State.Plane)
					{
						case ArcPlane.XY:
							U = Words[i].Parameter * UnitMultiplier + ArcIncremental * State.Position.X;
							break;
						case ArcPlane.YZ:
							throw new ParseException("current plane is YZ, I word is invalid", lineNumber);
						case ArcPlane.ZX:
							V = Words[i].Parameter * UnitMultiplier + ArcIncremental * State.Position.X;
							break;
					}

					IJKused = true;
					Words.RemoveAt(i);
					break;
				}

				for (int i = 0; i < Words.Count; i++)
				{
					if (Words[i].Command != 'J')
						continue;

					switch (State.Plane)
					{
						case ArcPlane.XY:
							V = Words[i].Parameter * UnitMultiplier + ArcIncremental * State.Position.Y;
							break;
						case ArcPlane.YZ:
							U = Words[i].Parameter * UnitMultiplier + ArcIncremental * State.Position.Y;
							break;
						case ArcPlane.ZX:
							throw new ParseException("current plane is ZX, J word is invalid", lineNumber);
					}

					IJKused = true;
					Words.RemoveAt(i);
					break;
				}

				for (int i = 0; i < Words.Count; i++)
				{
					if (Words[i].Command != 'K')
						continue;

					switch (State.Plane)
					{
						case ArcPlane.XY:
							throw new ParseException("current plane is XY, K word is invalid", lineNumber);
						case ArcPlane.YZ:
							V = Words[i].Parameter * UnitMultiplier + ArcIncremental * State.Position.Z;
							break;
						case ArcPlane.ZX:
							U = Words[i].Parameter * UnitMultiplier + ArcIncremental * State.Position.Z;
							break;
					}

					IJKused = true;
					Words.RemoveAt(i);
					break;
				}
			}
			#endregion

			#region ResolveRadius
			for (int i = 0; i < Words.Count; i++)
			{
				if (Words[i].Command != 'R')
					continue;

				if (IJKused)
					throw new ParseException("both IJK and R notation used", lineNumber);

				if (State.Position == EndPos)
					throw new ParseException("arcs in R-notation must have non-coincident start and end points", lineNumber);

				double Radius = Words[i].Parameter * UnitMultiplier;

				if (Radius == 0)
					throw new ParseException("radius can't be zero", lineNumber);

				double A, B;

				switch (State.Plane)
				{
					default:
						A = EndPos.X;
						B = EndPos.Y;
						break;
					case ArcPlane.YZ:
						A = EndPos.Y;
						B = EndPos.Z;
						break;
					case ArcPlane.ZX:
						A = EndPos.Z;
						B = EndPos.X;
						break;
				}

				A -= U;     //(AB) = vector from start to end of arc along the axes of the current plane
				B -= V;

				//see grbl/gcode.c
				double h_x2_div_d = 4.0 * (Radius * Radius) - (A * A + B * B);
				if (h_x2_div_d < 0)
				{
					throw new ParseException("arc radius too small to reach both ends", lineNumber);
				}

				h_x2_div_d = -Math.Sqrt(h_x2_div_d) / Math.Sqrt(A * A + B * B);

				if (MotionMode == 3 ^ Radius < 0)
				{
					h_x2_div_d = -h_x2_div_d;
				}

				U += 0.5 * (A - (B * h_x2_div_d));
				V += 0.5 * (B + (A * h_x2_div_d));

				Words.RemoveAt(i);
				break;
			}
			#endregion

			if (Words.Count > 0)
				Warnings.Add($"motion command must be last in line (ignoring unused words {string.Join(" ", Words)} in block). (line {lineNumber})");

			Arc arc = new Arc();
			arc.Start = State.Position;
			arc.End = EndPos;
			arc.Feed = State.Feed;
			arc.Direction = (MotionMode == 2) ? ArcDirection.CW : ArcDirection.CCW;
			arc.U = U;
			arc.V = V;
			arc.LineNumber = lineNumber;
			arc.Plane = State.Plane;

			Commands.Add(arc);
			State.Position = EndPos;
			return;
		}

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 : LoremFuzzer.cs
License : Apache License 2.0
Project Creator : 42skillz

public string GenerateParagraph(int? nbOfSentences = null)
        {
            nbOfSentences = nbOfSentences ?? 5;

            var sentences = new List<string>();

            for (var i = 0; i < nbOfSentences.Value; i++)
            {
                var nbWords = _fuzzer.GenerateInteger(MinNumberOfWordsInASentence, 10);
                var sentence = GenerateSentence(nbWords);
                sentences.Add(sentence);
            }

            var paragraph = string.Join(" ", sentences);

            return paragraph;
        }

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

public override string ToString() => $"{count}, {minId}, {maxId}, {string.Join(", ", consumers?.Select(a => a.ToString()))}";

19 View Source File : DuplicationException.cs
License : Apache License 2.0
Project Creator : 42skillz

private static string GenerateErrorMessage(Type typeRequested, int maxAttemptsToFindNotAlreadyProvidedValue, SortedSet<object> alreadyProvidedValues)
        {
            //return $"Couldn't find a non-already provided value of {typeRequested} after {maxAttemptsToFindNotAlreadyProvidedValue} attempts. Already provided values: {string.Join(", ", alreadyProvidedValues) }. In your case, try to increase the value of the {nameof(Fuzzer.MaxFailingAttemptsForNoDuplication)} property for your Fuzzer.";
            var errorMessage = [email protected]"Couldn't find a non-already provided value of {typeRequested} after {maxAttemptsToFindNotAlreadyProvidedValue} attempts. Already provided values: {string.Join(", ", alreadyProvidedValues) }. You can either:
- Generate a new specific fuzzer to ensure no duplication is provided for a sub-group of fuzzed values (anytime you want through the {nameof(IFuzz.GenerateNoDuplicationFuzzer)}() method of your current Fuzzer instance. E.g.: var tempFuzzer = fuzzer.{nameof(IFuzz.GenerateNoDuplicationFuzzer)}();)
- Increase the value of the {nameof(Fuzzer.MaxFailingAttemptsForNoDuplication)} property for your {nameof(IFuzz)} instance.";
            return errorMessage;
        }

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

private void Initialize(IDbCommand cmd, string sql, object parameter, int? commandTimeout = null, CommandType? commandType = null)
        {
            var dbParameters = new List<IDbDataParameter>();
            cmd.Transaction = _transaction;
            cmd.CommandText = sql;
            if (commandTimeout.HasValue)
            {
                cmd.CommandTimeout = commandTimeout.Value;
            }
            if (commandType.HasValue)
            {
                cmd.CommandType = commandType.Value;
            }
            if (parameter is IDbDataParameter)
            {
                dbParameters.Add(parameter as IDbDataParameter);
            }
            else if (parameter is IEnumerable<IDbDataParameter> parameters)
            {
                dbParameters.AddRange(parameters);
            }
            else if (parameter is Dictionary<string, object> keyValues)
            {
                foreach (var item in keyValues)
                {
                    var param = CreateParameter(cmd, item.Key, item.Value);
                    dbParameters.Add(param);
                }
            }
            else if (parameter != null)
            {
                var handler = GlobalSettings.EnreplacedyMapperProvider.GetDeserializer(parameter.GetType());
                var values = handler(parameter);
                foreach (var item in values)
                {
                    var param = CreateParameter(cmd, item.Key, item.Value);
                    dbParameters.Add(param);
                }
            }
            if (dbParameters.Count > 0)
            {
                foreach (IDataParameter item in dbParameters)
                {
                    if (item.Value == null)
                    {
                        item.Value = DBNull.Value;
                    }
                    var pattern = [email protected]"in\s+([\@,\:,\?]?{item.ParameterName})";
                    var options = RegexOptions.IgnoreCase | RegexOptions.Singleline | RegexOptions.Multiline;
                    if (cmd.CommandText.IndexOf("in", StringComparison.OrdinalIgnoreCase) != -1 && Regex.IsMatch(cmd.CommandText, pattern, options))
                    {
                        var name = Regex.Match(cmd.CommandText, pattern, options).Groups[1].Value;
                        var list = new List<object>();
                        if (item.Value is IEnumerable<object> || item.Value is Array)
                        {
                            list = (item.Value as IEnumerable).Cast<object>().Where(a => a != null && a != DBNull.Value).ToList();
                        }
                        else
                        {
                            list.Add(item.Value);
                        }
                        if (list.Count() > 0)
                        {
                            cmd.CommandText = Regex.Replace(cmd.CommandText, name, $"({string.Join(",", list.Select(s => $"{name}{list.IndexOf(s)}"))})");
                            foreach (var iitem in list)
                            {
                                var key = $"{item.ParameterName}{list.IndexOf(iitem)}";
                                var param = CreateParameter(cmd, key, iitem);
                                cmd.Parameters.Add(param);
                            }
                        }
                        else
                        {
                            cmd.CommandText = Regex.Replace(cmd.CommandText, name, $"(SELECT 1 WHERE 1 = 0)");
                        }
                    }
                    else
                    {
                        cmd.Parameters.Add(item);
                    }
                }
            }
            if (Logging != null)
            {
                var parameters = new Dictionary<string, object>();
                foreach (IDbDataParameter item in cmd.Parameters)
                {
                    parameters.Add(item.ParameterName, item.Value);
                }
                Logging.Invoke(cmd.CommandText, parameters, commandTimeout, commandType);
            }
        }

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

protected AuthenticationHeaderValue GetAuthorizationHeader(string uri, HttpMethod method)
        {
            string nonce = DateTime.Now.Ticks.ToString();
            string timestamp = DateTime.Now.ToUnixTimestamp().ToString();

            List<string> authParams = new List<string>();
            authParams.Add("oauth_consumer_key=" + ConsumerKey);
            authParams.Add("oauth_nonce=" + nonce);
            authParams.Add("oauth_signature_method=HMAC-SHA1");
            authParams.Add("oauth_timestamp=" + timestamp);
            authParams.Add("oauth_token=" + AccessToken);
            authParams.Add("oauth_version=1.0");

            SplitUri(uri, out string url, out string[] queryParams);

            List<string> requestParams = new List<string>(authParams);
            requestParams.AddRange(queryParams);
            requestParams.Sort();

            string signatureBaseString = string.Join("&", requestParams);
            signatureBaseString = string.Concat(method.Method.ToUpper(), "&", Uri.EscapeDataString(url), "&", Uri.EscapeDataString(signatureBaseString));

            string signature = GetSignature(signatureBaseString);

            string hv = string.Join(", ", authParams.Select(x => x.Replace("=", " = \"") + '"'));
            hv += $", oauth_signature=\"{Uri.EscapeDataString(signature)}\"";      

            return new AuthenticationHeaderValue("OAuth", hv);
        }

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

public override string ToString() => $"{name}, {last_delivered_id}, {pel_count}, [{string.Join("], [", pending?.Select(a => a?.ToString()))}], [{string.Join("], [", consumers?.Select(a => a?.ToString()))}]";

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

public async Task<Dictionary<UserProfilePropertyTypes,string>> GetCustomerInfo(string userId,IList<UserProfilePropertyTypes> properties = null)
        {
            var url = ApiUri + $"{userId}?access_token={PageToken}";

            if (properties != null && properties.Any())
            {
                url = url + "&fields=" + string.Join(",", properties.Select(x=>x.ToEnumString()));
            }

            var result = await GetAsync<Dictionary<string,string>>(url);

            var returnDic = new Dictionary<UserProfilePropertyTypes, string>();
            foreach (var keyValue in result)
            {
                returnDic.Add(keyValue.Key.ToEnum<UserProfilePropertyTypes>(),keyValue.Value);
            }

            return returnDic;
        }

19 View Source File : Form1.cs
License : MIT License
Project Creator : 1y0n

private string Handle_Payload()
        {
            //对用户输入的payload进行一些转换处理,方便下一步的加密
            string raw_input = textBox1.Text.Trim().Replace("\r\n", "").Replace("\n", "").Replace("\r", ""); //支持多种linux win换行符
            string payload_pattern_csharp = @"\{(.+?)\}";
            string payload_pattern_c = @"=.*"";$";
            string[] raw_payload_array;
            if (Regex.IsMatch(raw_input, payload_pattern_c))
            {
                //c语言格式的shellcode,转成 csharp 格式
                raw_input = raw_input.Replace("\"", "").Replace("\\", ",0").Replace(";", "").Replace("=", "{").Replace("{,", "{ ") + " }";
            }
            string raw_payload = Regex.Matches(raw_input, payload_pattern_csharp)[0].Value.Replace("{", "").Replace("}", "").Trim();
            raw_payload = raw_payload.TrimStart(',');
            raw_payload_array = raw_payload.Split(',');
            List<byte> byte_payload_list = new List<byte>();

            foreach (string i in raw_payload_array)
            {
                byte_payload_list.Add(string_to_int(i));
            }
            byte[] payload_result = byte_payload_list.ToArray();

            //加密payload并转换为字符串,准备写入文件
            byte[] encrypted_payload = Encrypter.Encrypt(KEY, payload_result);
            string string_encrypted_payload = string.Join(",", encrypted_payload);
            //MessageBox.Show(string_encrypted_payload);
            return string_encrypted_payload;
        }

19 View Source File : NotchSolutionDebugger.cs
License : MIT License
Project Creator : 5argon

void Update()
    {
        sb.Clear();
        ClearRects();

        switch (menu)
        {
            case Menu.Home:
                export.gameObject.SetActive(true);
                sb.AppendLine($"<b>-- PLEASE ROTATE THE DEVICE TO GET BOTH ORIENTATION'S DETAILS! --</b>\n");

                var safeArea = RelativeToReal(NotchSolutionUtility.ShouldUseNotchSimulatorValue ? storedSimulatedSafeAreaRelative : NotchSolutionUtility.ScreenSafeAreaRelative);

                PlaceRect(safeArea, Color.red);
                if (Screen.orientation != NotchSolutionUtility.GetCurrentOrientation())
                    safeArea.Set(Screen.width - safeArea.x, Screen.height - safeArea.y, safeArea.width, safeArea.height);
                sb.AppendLine($"Safe area : {safeArea}\n");

#if UNITY_2019_2_OR_NEWER
#if UNITY_EDITOR
                var relativeCutouts = NotchSolutionUtility.ShouldUseNotchSimulatorValue ? storedSimulatedCutoutsRelative : NotchSolutionUtility.ScreenCutoutsRelative;
                List<Rect> rectCutouts = new List<Rect>();
                foreach (Rect rect in relativeCutouts) rectCutouts.Add(RelativeToReal(rect));
                var cutouts = rectCutouts.ToArray();
#else
                var cutouts = Screen.cutouts;
#endif
                foreach (Rect r in cutouts) PlaceRect(r, Color.blue);

                if (Screen.orientation != NotchSolutionUtility.GetCurrentOrientation())
                {
                    foreach (Rect rect in cutouts) rect.Set(Screen.width - rect.x, Screen.height - rect.y, rect.width, rect.height);
                }
                sb.AppendLine($"Cutouts : {string.Join(" / ", cutouts.Select(x => x.ToString()))} \n");
#endif

                sb.AppendLine($"Current resolution : {Screen.currentResolution}\n");
                sb.AppendLine($"All Resolutions : {string.Join(" / ", Screen.resolutions.Select(x => x.ToString()))}\n");
                sb.AppendLine($"DPI : {Screen.dpi} WxH : {Screen.width}x{Screen.height} Orientation : {Screen.orientation}\n");
                var joinedProps = string.Join(" / ", typeof(SystemInfo).GetProperties(BindingFlags.Public | BindingFlags.Static).Select(x => $"{x.Name} : {x.GetValue(null)}"));
                sb.AppendLine(joinedProps);

                break;
            case Menu.Extracting:
                var screen = device.Screens.FirstOrDefault();
                export.gameObject.SetActive(false);

                if (screen.orientations.Count == 4)
                {
                    string path = Application.persistentDataPath + "/" + device.Meta.friendlyName + ".device.json";
                    System.IO.File.WriteAllText(path, JsonUtility.ToJson(device));
                    sb.AppendLine("<b>Done</b>");
                    sb.AppendLine("");
                    sb.AppendLine($"File saved at <i>{path}</i>");
                    StartCoroutine(exportDone());
                }
                else sb.AppendLine("Extracting...");

                break;
        }
        debugText.text = sb.ToString();
    }

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

public override string ToString() => $"{key}, {string.Join("], [", entries.Select(a => a?.ToString()))}";

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

private static StatementSyntax MakeThrowSyntax(Location location, ExpressionSyntax condition, string msg, string expr)
        {
            // message, expression, file, position, width
            string file = location.SourceTree.FilePath;

            ArgumentSyntax[] argsSyntax =
            {
                F.Argument(F.LiteralExpression(K.StringLiteralExpression, F.Literal(msg))),
                F.Argument(F.LiteralExpression(K.StringLiteralExpression, F.Literal(expr))),
                F.Argument(file == null ? F.LiteralExpression(K.NullLiteralExpression) : F.LiteralExpression(K.StringLiteralExpression, F.Literal(file))),
                F.Argument(F.LiteralExpression(K.NumerireplacederalExpression, F.Literal(location.SourceSpan.Start))),
                F.Argument(F.LiteralExpression(K.NumerireplacederalExpression, F.Literal(location.SourceSpan.Length)))
            };

            return F.IfStatement(
                condition,
                F.ParseStatement($"throw new {typeof(replacedertionException).FullName}({string.Join<ArgumentSyntax>(", ", argsSyntax)});")
            );
        }

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

public async Task NodeMonitor(CancellationToken cancellationToken)
        {
            Logger.LogTrace("Start refresh service status,waiting for locking...");
            using (await AsyncLock.LockAsync(cancellationToken))
            {
                if (cancellationToken.IsCancellationRequested)
                    return;

                foreach (var service in ServiceNodes)
                {
                    Logger.LogTrace($"Service {service.Key} refreshing...");
                    try
                    {
                        var healthNodes = await QueryServiceAsync(service.Key, cancellationToken);
                        if (cancellationToken.IsCancellationRequested)
                            break;

                        var leavedNodes = service.Value.Where(p => healthNodes.All(a => a.ServiceId != p.ServiceId))
                            .Select(p => p.ServiceId).ToArray();
                        if (leavedNodes.Any())
                        {
                            //RemoveNode(service.Key, leavedNodes);
                            if (!ServiceNodes.TryGetValue(service.Key, out var services)) return;
                            services.RemoveAll(p => leavedNodes.Any(n => n == p.ServiceId));
                            OnNodeLeave?.Invoke(service.Key, leavedNodes);
                            Logger.LogTrace($"These nodes are gone:{string.Join(",", leavedNodes)}");
                        }

                        var addedNodes = healthNodes.Where(p =>
                                service.Value.All(e => e.ServiceId != p.ServiceId)).Select(p =>
                                new ServiceNodeInfo(p.ServiceId, p.Address, p.Port, p.Weight, p.EnableTls, p.Meta))
                            .ToList();

                        if (addedNodes.Any())
                        {
                            //AddNode(service.Key, addedNodes);
                            if (ServiceNodes.TryGetValue(service.Key, out var services))
                                services.AddRange(addedNodes);
                            else
                                ServiceNodes.TryAdd(service.Key, addedNodes);

                            OnNodeJoin?.Invoke(service.Key, addedNodes);

                            Logger.LogTrace(
                                $"New nodes added:{string.Join(",", addedNodes.Select(p => p.ServiceId))}");
                        }
                    }
                    catch
                    {
                        // ignored
                    }
                }
                Logger.LogTrace("Complete refresh.");
            }
        }

19 View Source File : WorkbookStream.cs
License : Apache License 2.0
Project Creator : aaaddress1

public string ToDisplayString()
        {
            return string.Join("\n",_biffRecords.Select(record => record.ToHexDumpString()));
        }

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

public string GetTableAttribute() {
		var sb = new List<string>();

		if (GetCsName(this.FullTableName) != this.FullTableName)
			sb.Add("Name = \"" + this.FullTableName + "\"");

		if (sb.Any() == false) return null;
		return "[Table(" + string.Join(", ", sb) + ")]";
	}

19 View Source File : Form1.cs
License : MIT License
Project Creator : 1y0n

private string Generate_JS_XSL(string type)
        {
            //1. 生成一个 dll 文件
            string target_arch = " /platform:x86 /optimize ";
            if (radioButton2.Checked)
            {
                target_arch = " /platform:x64 /optimize";
            }

            KEY = Random_Key();
            List<string> temp_list = new List<string>();
            foreach (byte i in KEY)
            {
                temp_list.Add("0x" + i.ToString("X2"));
            }
            KEY_String = string.Join(",", temp_list);

            
            Compiler compiler = new Compiler();
            TP_VirtualAlloc_DLL vad = new TP_VirtualAlloc_DLL(KEY_String, Handle_Payload());
            compiler.compileToExe(vad.GetCode(), KEY_String, Global_Var.dll_path, target_arch, "library");
            

            //2. 通过 DotNetToJscript 转换成 js
            string js_result = DotNetToJScript.Generate();

            if (js_result != null)
            {
                if (type == ".js")
                {
                    return js_result;
                }
                else 
                {
                    TP_XSL xsl = new TP_XSL();
                    return xsl.GetCode(js_result);
                }
            }
            else
            {
                return null;
            }
        }

19 View Source File : CelesteNetClientModule.cs
License : MIT License
Project Creator : 0x0ade

protected override void CreateModMenuSectionHeader(TextMenu menu, bool inGame, EventInstance snapshot) {
            base.CreateModMenuSectionHeader(menu, inGame, snapshot);

            CelesteNetModShareComponent sharer = Context?.Get<CelesteNetModShareComponent>();
            if (sharer != null && !inGame) {
                List<EverestModuleMetadata> requested;
                lock (sharer.Requested)
                    requested = new List<EverestModuleMetadata>(sharer.Requested);

                if (requested.Count != 0) {
                    TextMenu.Item item;
                    menu.Add(item = new TextMenu.Button("modoptions_celestenetclient_recommended".DialogClean()).Pressed(() => {
                        f_OuiDependencyDownloader_MissingDependencies.SetValue(null, requested);
                        m_Overworld_Goto_OuiDependencyDownloader.Invoke(Engine.Scene, Dummy<object>.EmptyArray);
                    }));

                    item.AddDescription(
                        menu,
                        "modoptions_celestenetclient_recommendedhint".DialogClean()
                        .Replace("((list))", string.Join(", ", requested.Select(r => r.DLL)))
                    );
                }
            }
        }

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

private void RefreshNodes(string serviceName, List<ServiceNodeInfo> currentNodes)
        {
            if (ServiceNodes.TryGetValue(serviceName, out var nodes))
            {
                if (!currentNodes.Any())
                    nodes.Clear();

                var leavedNodes = nodes.Where(p => currentNodes.All(c => c.ServiceId != p.ServiceId)).Select(p => p.ServiceId).ToList();
                if (leavedNodes.Any())
                {
                    Logger.LogTrace($"These nodes are gone:{string.Join(",", leavedNodes)}");
                    OnNodeLeave?.Invoke(serviceName, leavedNodes);
                    nodes.RemoveAll(p => currentNodes.All(c => c.ServiceId != p.ServiceId));
                }

                var addedNodes = currentNodes.FindAll(p => nodes.All(c => c.ServiceId != p.ServiceId));
                if (addedNodes.Any())
                {
                    nodes.AddRange(addedNodes);
                    Logger.LogTrace(
                        $"New nodes added:{string.Join(",", addedNodes.Select(p => p.ServiceId))}");
                    OnNodeJoin?.Invoke(serviceName, addedNodes);
                }
            }
            else
            {
                if (!currentNodes.Any())
                    ServiceNodes.TryAdd(serviceName, currentNodes);
            }
        }

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

private string ResovleColumns()
        {
            if (_selectExpression == null)
            {
                var filters = new GroupExpressionResovle(_filterExpression)
                    .Resovle().Split(',');
                var columns = GetColumnMetaInfos()
                    .Where(a => !filters.Contains(a.ColumnName) && !a.IsNotMapped)
                    .Select(s => s.ColumnName != s.CsharpName ? $"{s.ColumnName} AS {s.CsharpName}" : s.CsharpName);
                return string.Join(",", columns);
            }
            else
            {
                return new SelectExpressionResovle(_selectExpression).Resovle();
            }
        }

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

internal void SetHost(string host)
        {
            if (string.IsNullOrEmpty(host?.Trim())) {
                _ip = "127.0.0.1";
                _port = 6379;
                return;
            }
            host = host.Trim();
            var ipv6 = Regex.Match(host, @"^\[([^\]]+)\]\s*(:\s*(\d+))?$");
            if (ipv6.Success) //ipv6+port 格式: [fe80::b164:55b3:4b4f:7ce6%15]:6379
            {
                _ip = ipv6.Groups[1].Value.Trim();
                _port = int.TryParse(ipv6.Groups[3].Value, out var tryint) && tryint > 0 ? tryint : 6379;
                return;
            }
            var spt = (host ?? "").Split(':');
            if (spt.Length == 1) //ipv4 or domain
            {
                _ip = string.IsNullOrEmpty(spt[0].Trim()) == false ? spt[0].Trim() : "127.0.0.1";
                _port = 6379;
                return;
            }
            if (spt.Length == 2) //ipv4:port or domain:port
            {
                if (int.TryParse(spt.Last().Trim(), out var testPort2))
                {
                    _ip = string.IsNullOrEmpty(spt[0].Trim()) == false ? spt[0].Trim() : "127.0.0.1";
                    _port = testPort2;
                    return;
                }
                _ip = host;
                _port = 6379;
                return;
            }
            if (IPAddress.TryParse(host, out var tryip) && tryip.AddressFamily == AddressFamily.InterNetworkV6) //test ipv6
            {
                _ip = host;
                _port = 6379;
                return;
            }
            if (int.TryParse(spt.Last().Trim(), out var testPort)) //test ipv6:port
            {
                var testHost = string.Join(":", spt.Where((a, b) => b < spt.Length - 1));
                if (IPAddress.TryParse(testHost, out tryip) && tryip.AddressFamily == AddressFamily.InterNetworkV6)
                {
                    _ip = testHost;
                    _port = 6379;
                    return;
                }
            }
            _ip = host;
            _port = 6379;
        }

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

public static string ToMethod(this MethodInfo method)
        {
            if (method == null) return null;
            var sb = new StringBuilder();
            sb.Append("        public static ");

            var returnType = method.ReturnType;
            var isNoResultAsync = returnType == typeof(Task) || returnType == typeof(ValueTask);
            var isGenericAsync = returnType.IsGenericType && (returnType.GetGenericTypeDefinition() == typeof(ValueTask<>) || returnType.GetGenericTypeDefinition() == typeof(Task<>));
            var isAsync = isGenericAsync || isNoResultAsync;

            var isResult = false;

            if (isAsync)
                sb.Append("async ");

            var funcInfo = method.ToInterface(false);
            sb.AppendLine(funcInfo);
            sb.AppendLine("        {");

            if (isAsync)
            {
                if (isNoResultAsync)
                    sb.Append("            await _redisClient.").Append(method.Name);
                else
                {
                    isResult = true;
                    sb.Append("            var result = await _redisClient.").Append(method.Name);
                }
            }
            else
            {
                if (returnType == typeof(void))
                {
                    sb.Append("            _redisClient.").Append(method.Name);
                }
                else
                {
                    isResult = true;
                    sb.Append("            var result = _redisClient.").Append(method.Name);
                }
            }

            var genericParameters = method.GetGenericArguments();
            if (method.DeclaringType.IsNested && method.DeclaringType.DeclaringType.IsGenericType)
            {
                var dic = genericParameters.ToDictionary(a => a.Name);
                foreach (var nestedGenericParameter in method.DeclaringType.DeclaringType.GetGenericArguments())
                    if (dic.ContainsKey(nestedGenericParameter.Name))
                        dic.Remove(nestedGenericParameter.Name);
                genericParameters = dic.Values.ToArray();
            }
            if (genericParameters.Any())
                sb.Append("<")
                    .Append(string.Join(", ", genericParameters.Select(a => a.DisplayCsharp())))
                    .Append(">");

            sb.Append("(").Append(string.Join(", ", method.GetParameters().Select(a => $" {a.Name}"))).AppendLine(");");

            if (isResult)
                sb.AppendLine("            return result;");

            sb.Append("        }\r\n\r\n");
            return sb.ToString();
        }

See More Examples