string.Join(string, string[], int, int)

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

9741 Examples 7

19 View Source File : VxFormGroup.cs
License : MIT License
Project Creator : Aaltuj

internal static void Add(string fieldIdentifier, VxFormGroup group, object modelInstance, VxFormLayoutOptions options)
        {
            // TODO: EXPANDO switch
            var prop = modelInstance.GetType().GetProperty(fieldIdentifier);
            var layoutAttr = prop.GetCustomAttribute<VxFormElementLayoutAttribute>();
            var allRowLayoutAttributes = VxHelpers.GetAllAttributes<VxFormRowLayoutAttribute>(prop.DeclaringType);

            // If no attribute is found use the name of the property
            if (layoutAttr == null)
                layoutAttr = new VxFormElementLayoutAttribute()
                {
                    Label = GetLabel(fieldIdentifier, modelInstance)
                };

            PatchLayoutWithBuiltInAttributes(layoutAttr, prop);


            // Check if row already exists
            var foundRow = group.Rows.Find(value => value.Id == layoutAttr.RowId.ToString());

            if (foundRow == null)
            {
                foundRow = VxFormRow.Create(layoutAttr, allRowLayoutAttributes.Find(x => x.Id == layoutAttr.RowId), options);
                group.Rows.Add(foundRow); ;
            }

            var formColumn = VxFormElementDefinition.Create(fieldIdentifier, layoutAttr, modelInstance, options);
            VxFormRow.AddColumn(foundRow, formColumn, options);

            // WHen there is a VxFormRowLayout found use the name if specified, this also sets the row to combined labels
            if (options.LabelOrientation == LabelOrientation.LEFT && foundRow.RowLayoutAttribute?.Label == null)
                foundRow.Label = string.Join(", ", foundRow.Columns.ConvertAll(x => x.RenderOptions.Label));

        }

19 View Source File : BaseReturnsMethodProvider.cs
License : MIT License
Project Creator : Abc-Arbitrage

protected override bool AddLookupItems(CSharpCodeCompletionContext context, IItemsCollector collector)
		{
			var identifier = context.TerminatedContext.TreeNode as IIdentifier;
			var expression = identifier.GetParentSafe<IReferenceExpression>();

			if (expression == null)
			{
				return false;
			}

			if (!(expression.ConditionalQualifier is IInvocationExpression invocation))
			{
				return false;
			}

			var solution = context.BasicContext.Solution;
			var methodIdentifier = solution.GetComponent<IMoqMethodIdentifier>();

			if (methodIdentifier.IsMoqCallbackMethod(invocation))
			{
				invocation = invocation.InvokedExpression?.FirstChild as IInvocationExpression;
			}

			var mockedMethod = GetMockedMethodFromSetupMethod(solution, invocation);

			if (mockedMethod == null || mockedMethod.Parameters.Count == 0 || mockedMethod.ReturnType.IsVoid())
			{
				return false;
			}

			var types = GetMockedMethodParameterTypes(solution, invocation);
			var variablesName = mockedMethod.Parameters.Select(p => p.ShortName);
			var proposedCallback = $"Returns<{string.Join(",", types)}>(({string.Join(",", variablesName)}) => )";

			var item = CSharpLookupItemFactory.Instance.CreateKeywordLookupItem(context,
				proposedCallback,
				TailType.None,
				PsiSymbolsThemedIcons.Method.Id);

			item.SetInsertCaretOffset(-1);
			item.SetReplaceCaretOffset(-1);
			item.WithInitializedRanges(context.CompletionRanges, context.BasicContext);
			item.SetTopPriority();
			collector.Add(item);

			return true;
		}

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

public static string GetLyricsHash(this IBeatmapLevel level)
        {
            string id = string.Join(", ", level.songName, level.songAuthorName, level.songSubName, level.beatsPerMinute, level.songDuration, level.songTimeOffset);

            return Convert.ToBase64String(Encoding.UTF8.GetBytes(id));
        }

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

public async Task<IActionResult> OnPostAsync([FromBody] SendVerifyEmailDto dto)
        {
            if (!ModelState.IsValid)
            {
                return await Task.FromResult(new JsonResult(new
                {
                    Status = false,
                    ErrorMessage = ModelState.Where(e => e.Value.Errors.Count > 0).Select(e => e.Value.Errors.First().ErrorMessage).First()
                }));
            }

            var userId = _accountContext.UserId;

            var command = new SendVerifyEmailCommand(dto.Email);
            await _bus.SendCommand(command);

            if (_notifications.HasNotifications())
            {
                var errorMessage = string.Join("��", _notifications.GetNotifications().Select(x => x.Content));
                return await Task.FromResult(new JsonResult(new
                {
                    status = false,
                    errorMessage
                }));
            }

            return await Task.FromResult(new JsonResult(new
            {
                status = true
            }));

        }

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

public async Task<IActionResult> OnPostAsync([FromBody]PlayerCreateDto dto)
        {
            if (!ModelState.IsValid)
            {
                return await Task.FromResult(new JsonResult(new
                {
                    Status = false,
                    ErrorMessage = ModelState.Where(e => e.Value.Errors.Count > 0).Select(e => e.Value.Errors.First().ErrorMessage).First()
                }));
            }

            var userId = _accountContext.UserId;

            var command = new CreateCommand(dto.Name, dto.Gender, userId, dto.Str, dto.Con, dto.Dex, dto.Int);
            await _bus.SendCommand(command);

            if (_notifications.HasNotifications())
            {
                var errorMessage = string.Join(";", _notifications.GetNotifications().Select(x => x.Content));
                return await Task.FromResult(new JsonResult(new
                {
                    status = false,
                    errorMessage
                }));
            }

            return await Task.FromResult(new JsonResult(new
            {
                status = true
            }));

        }

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

public static void WriteSuricataFileResult(Options o, Dictionary<string, List<string>> techniques)
        {
            try
            {

                var entries = techniques
                    .ToList()
                    .Select(entry => new
                    {
                        techniqueID = entry.Key,
                        score = entry.Value.Count,
                        comment = (o.NoComment) ? null : string.Join(Environment.NewLine, entry.Value.Select(x => x.Split("/").Last()))
                    });

                string filename = o.OutFile.EndsWith(".json") ? "suricata-coverage.json" : $"{o.OutFile}.json";
                File.WriteAllText(filename, JsonConvert.SerializeObject(new
                {
                    domain = "mitre-enterprise",
                    name = "Suricata rules coverage",
                    gradient = new
                    {
                        colors = new[] { "#a0eab5", "#0f480f" },
                        maxValue = techniques
                            .Values
                            .Max(x => x.Count),
                        minValue = 0
                    },
                    version = "4.2",
                    techniques = entries
                }, Formatting.Indented, new JsonSerializerSettings
                {
                    NullValueHandling = NullValueHandling.Ignore
                }));
                Console.WriteLine($"[*] Layer file written in {filename} ({entries.Count()} techniques covered)");
            }
            catch (Exception e)
            {
                Console.WriteLine("Problem writing to file: " + e.Message);
            }
        }

19 View Source File : MoneyFile.cs
License : Microsoft Public License
Project Creator : AArnott

internal void RereplacedignCategory(IEnumerable<int> oldCategoryIds, int? newId)
	{
		string sql = [email protected]"UPDATE ""{nameof(Transaction)}""
SET ""{nameof(Transaction.CategoryId)}"" = ?
WHERE ""{nameof(Transaction.CategoryId)}"" IN ({string.Join(", ", oldCategoryIds.Select(c => c.ToString(CultureInfo.InvariantCulture)))})";
		this.connection.Execute(sql, newId);
	}

19 View Source File : CosmosResourceTokenBroker.cs
License : MIT License
Project Creator : 1iveowl

[FunctionName("CosmosResourceTokenBroker")]
        public async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = "broker")] HttpRequest req,
            ILogger log)
        {

            // Extracting the Access Token from the http request from the client
            string accessToken = null;

            try
            {
                accessToken = req?.Headers?["Authorization"].ToString()?.Replace("Bearer ", string.Empty);

                if (string.IsNullOrEmpty(accessToken))
                {
                    return LogErrorAndReturnBadObjectResult("Access token is missing", log);
                }
            }
            catch (Exception ex)
            {
                return LogErrorAndReturnBadObjectResult("Unable to read Authorization header", log, ex);
            }


            // Decrypting and reading the Access Token
            JwtSecurityToken token = null;

            try
            {
                var handler = new JwtSecurityTokenHandler();

                token = handler.ReadJwtToken(accessToken);
                
                log.Log(LogLevel.Information, $"Jwt: {token}");

                if (!handler.CanValidateToken)
                {
                    return LogErrorAndReturnBadObjectResult($"Unable to validate token: {accessToken}", log);
                }
            }
            catch (Exception ex)
            {
                return LogErrorAndReturnBadObjectResult($"Unable to read JWT token: {accessToken}", log, ex);
            }

#if DEBUG
            var expires = token.ValidTo;

            var ignoreExpires = req?.Headers?["IgnoreExpires"].ToString().ToLower() == "true";

            if (DateTime.UtcNow > expires && !ignoreExpires)
            {
                return LogErrorAndReturnBadObjectResult("The access token have expired. " +
                                                        "Note this error is for debug mode only, for use when testing. " +
                                                        "In production access token validity is handled by Azure Functions configuration.", log);
            }
#endif

            // Getting the user object id from the Access Token
            var userObjectId = token?.Subject;

            if (string.IsNullOrEmpty(userObjectId))
            {
                return LogErrorAndReturnBadObjectResult("No subject defined in access token", log);
            }

            // Getting the permission scope from the Access Token to determine the permission mode.
            var accessTokenScopes = token?.Claims.FirstOrDefault(c => c.Type.ToLowerInvariant() == "scp")?.Value.Split(' ');

            if (!accessTokenScopes?.Any() ?? false)
            {
                return LogErrorAndReturnBadObjectResult("No scopes defined", log);
            }


            // Extracting the known scopes only.
            var permissionScopes = accessTokenScopes?.Select(scope => KnownPermissionScopes?.FirstOrDefault(ks => ks?.Scope == scope));
            
            if (!permissionScopes?.Any() ?? false)
            {
                return LogErrorAndReturnBadObjectResult($"No known scopes: " +
                                                        $"{string.Join(", ", accessTokenScopes)}. " +
                                                        $"Known scopes are: " +
                                                        $"{string.Join(", ", KnownPermissionScopes.Select(ks => ks.Scope))}", log);
            }

            try
            {

                await using var brokerService = new ResourceTokenBrokerService(_cosmosHostUrl, _cosmosKey, _cosmosDatabaseId, _cosmosCollectionId);

                // Getting the Resource Permission Tokens
                var permissionToken = await brokerService.Get(userObjectId, permissionScopes);

                return (IActionResult) new JsonResult(permissionToken, new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All });
            }
            catch (Exception ex)
            {
                return LogErrorAndReturnBadObjectResult($"Unable to acquire resource token from Cosmos DB " +
                                                        $"for user with id: {userObjectId} " +
                                                        $"for permission scopes: {string.Join(", ", permissionScopes)}.", log, ex);
            }
        }

19 View Source File : GracefulChaosMonkey.cs
License : MIT License
Project Creator : abdullin

public  async Task Run(SimControl plan) {
            plan.StartServices();

            var deathPool = plan.Cluster.Machines
                .Select(p => p.Key)
                .Where(ApplyToMachines)
                .ToArray();


            plan.Cluster.Routes.Select(p => p.Key);
            
            plan.Debug(LogType.RuntimeInfo,  $"Monkey has plans for {string.Join(", ", deathPool)}");

            while (true) {
                await plan.Delay(DelayBetweenStrikes(plan.Rand));

                var candidate = deathPool[plan.Rand.Next(0, deathPool.Length)];
                var grace = plan.Rand.Next(0, 5).Sec();
                var wipe = plan.Rand.Next(0, 3) == 1;

                if (wipe) {
                    plan.Debug(LogType.Fault,  $"CHAOS MONKEY KILL {candidate}");
                    await plan.StopServices(s => s.Machine == candidate, grace: grace);
                    plan.WipeStorage(candidate);
                } else {
                    plan.Debug(LogType.Fault, $"CHAOS MONKEY REBOOT {candidate}");
                    await plan.StopServices(s => s.Machine == candidate, grace: grace);
                }

                await plan.Delay(plan.Rand.Next(2, 10).Sec());
                plan.Debug(LogType.Fault, $"CHAOS MONKEY START {candidate}");
                plan.StartServices(s => s.Machine == candidate);
            }
        }

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

async Task<int> DbContextBetchUpdatePrivAsync(EnreplacedyState[] ups, bool isLiveUpdate) {
			if (ups.Any() == false) return 0;
			var uplst1 = ups[ups.Length - 1];
			var uplst2 = ups.Length > 1 ? ups[ups.Length - 2] : null;

			if (_states.TryGetValue(uplst1.Key, out var lstval1) == false) return -999;
			var lstval2 = default(EnreplacedyState);
			if (uplst2 != null && _states.TryGetValue(uplst2.Key, out lstval2) == false) throw new Exception($"特别错误:更新失败,数据未被跟踪:{_fsql.GetEnreplacedyString(_enreplacedyType, uplst2.Value)}");

			var cuig1 = _fsql.CompareEnreplacedyValueReturnColumns(_enreplacedyType, uplst1.Value, lstval1.Value, true);
			var cuig2 = uplst2 != null ? _fsql.CompareEnreplacedyValueReturnColumns(_enreplacedyType, uplst2.Value, lstval2.Value, true) : null;

			List<EnreplacedyState> data = null;
			string[] cuig = null;
			if (uplst2 != null && string.Compare(string.Join(",", cuig1), string.Join(",", cuig2)) != 0) {
				//最后一个不保存
				data = ups.ToList();
				data.RemoveAt(ups.Length - 1);
				cuig = cuig2;
			} else if (isLiveUpdate) {
				//立即保存
				data = ups.ToList();
				cuig = cuig1;
			}

			if (data?.Count > 0) {

				if (cuig.Length == _table.Columns.Count)
					return ups.Length == data.Count ? -998 : -997;

				var updateSource = data.Select(a => a.Value).ToArray();
				var update = this.OrmUpdate(null).SetSource(updateSource).IgnoreColumns(cuig);

				var affrows = await update.ExecuteAffrowsAsync();

				foreach (var newval in data) {
					if (_states.TryGetValue(newval.Key, out var tryold))
						_fsql.MapEnreplacedyValue(_enreplacedyType, newval.Value, tryold.Value);
					if (newval.OldValue != null)
						_fsql.MapEnreplacedyValue(_enreplacedyType, newval.Value, newval.OldValue);
				}
				return affrows;
			}

			//等待下次对比再保存
			return 0;
		}

19 View Source File : PlantumlStructure.cs
License : MIT License
Project Creator : 8T4

private static string ToPumlString(this DeploymentNode deployment, int concat = 0)
        {
            var stream = new StringBuilder();
            var spaces = SpaceMethods.Indent(concat);

            if (concat == 0)
            {
                stream.AppendLine();
            }

            if (deployment.Properties != null)
            {
                foreach (var (key, value) in deployment.Properties)
                {
                    stream.AppendLine($"{spaces}AddProperty(\"{key}\", \"{value}\")");
                }
            }

            stream.AppendLine(deployment.Tags is null
                ? $"{spaces}Deployment_Node({deployment.Alias}, \"{deployment.Label}\", \"{deployment.Description}\") {{"
                : $"{spaces}Deployment_Node({deployment.Alias}, \"{deployment.Label}\", \"{deployment.Description}\", $tags=\"{string.Join(',', deployment.Tags)}\") {{");

            if (deployment.Nodes != null)
            {
                foreach (var node in deployment.Nodes)
                {
                    stream.AppendLine($"{node.ToPumlString(concat + SpaceMethods.TabSize)}");
                }
            }

            if (deployment.Container != null)
            {
                stream.AppendLine(SpaceMethods.Indent(concat) + deployment.Container.ToPumlString());
            }

            stream.Append(spaces + "}");

            return stream.ToString();
        }

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

public async Task<IActionResult> OnPostAsync([FromBody]UserLoginDto dto)
        {
            if (!ModelState.IsValid)
            {
                return await Task.FromResult(new JsonResult(new
                {
                    Status = false,
                    ErrorMessage = ModelState.Where(e => e.Value.Errors.Count > 0).Select(e => e.Value.Errors.First().ErrorMessage).First()
                }));
            }

            var userId = _accountContext.UserId;

            var command = new LoginCommand(dto.Email, dto.Preplacedword);
            await _bus.SendCommand(command);

            if (_notifications.HasNotifications())
            {
                var errorMessage = string.Join(";", _notifications.GetNotifications().Select(x => x.Content));
                return await Task.FromResult(new JsonResult(new
                {
                    status = false,
                    errorMessage
                }));
            }

            return await Task.FromResult(new JsonResult(new
            {
                status = true
            }));

        }

19 View Source File : CommandFlagsTests.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 = cli.Command();
			//var rt = cli.CommandInfo("mset", "mget", "set", "get", "rename");
			var flags = new List<string>();
			var flags7 = new List<string>();
			var diccmd = new Dictionary<string, (string[], string[])>();

			var sb = string.Join("\r\n\r\n", (rt).OrderBy(a1 => (a1 as object[])[0].ToString()).Select(a1 =>
			{
				var a = a1 as object[];
				var cmd = a[0].ToString();
				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 aflags = (a[2] as object[]).Select(a => a.ToString()).ToArray();
				var fopts = (a[6] as object[]).Select(a => a.ToString()).ToArray();
				flags.AddRange(aflags);
				flags7.AddRange(fopts);

				diccmd.Add(cmd.ToUpper(), (aflags, fopts));

				var parms = "";
				if (plen > 1)
				{
					for (var x = 1; x < plen; x++)
					{
						if (x == firstKey) parms += "string key, ";
						else parms += $"string arg{x}, ";
					}
					parms = parms.Remove(parms.Length - 2);
				}
				if (plen < 0)
				{
					for (var x = 1; x < -plen; x++)
					{
						if (x == firstKey)
						{
							if (firstKey != lastKey) parms += "string[] keys, ";
							else parms += "string key, ";
						}
						else
						{
							if (firstKey != lastKey) parms += $"string[] arg{x}, ";
							else parms += $"string arg{x}, ";
						}
					}
					if (parms.Length > 0)
						parms = parms.Remove(parms.Length - 2);
				}

				return [email protected]"
//{string.Join(", ", a[2] as object[])}
//{string.Join(", ", a[6] as object[])}
public void {UFString(cmd)}({parms}) {{ }}";
			}));
			flags = flags.Distinct().ToList();
			flags7 = flags7.Distinct().ToList();


			var sboptions = new StringBuilder();
            foreach (var cmd in CommandSets._allCommands)
            {
                if (diccmd.TryGetValue(cmd, out var tryv))
                {
                    sboptions.Append([email protected]"
[""{cmd}""] = new CommandSets(");

                    for (var x = 0; x < tryv.Item1.Length; x++)
                    {
                        if (x > 0) sboptions.Append(" | ");
                        sboptions.Append($"ServerFlag.{tryv.Item1[x].Replace("readonly", "@readonly")}");
                    }

                    sboptions.Append(", ");
                    for (var x = 0; x < tryv.Item2.Length; x++)
                    {
                        if (x > 0) sboptions.Append(" | ");
                        sboptions.Append($"ServerTag.{tryv.Item2[x].TrimStart('@').Replace("string", "@string")}");
                    }

                    sboptions.Append(", LocalStatus.none),");
                }
                else
                {
                    sboptions.Append([email protected]"
[""{cmd}""] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none), ");
                }
            }

            var optioncode = sboptions.ToString();
		}

19 View Source File : GithubManager.cs
License : GNU General Public License v3.0
Project Creator : a4004

public static HttpStatusCode MakeApiRequestGet(out string content, string url, params string[] args)
        {
            HttpClient httpClient = new HttpClient();

            HttpRequestMessage httpRequest = new HttpRequestMessage()
            {
                RequestUri = new Uri(args == null ? url : $"{url}?{string.Join("&", args)}"),
                Method = HttpMethod.Get,
                Version = HttpVersion.Version11
            };

            httpRequest.Headers.Add("Accept", "application/json");
            httpRequest.Headers.Add("User-Agent", $"N2D22webAPI/{Environment.OSVersion.VersionString}");

            HttpResponseMessage httpResponse = httpClient.SendAsync(httpRequest,
                HttpCompletionOption.ResponseContentRead).GetAwaiter().GetResult();

            content = httpResponse.Content.ReadreplacedtringAsync().GetAwaiter().GetResult();

            Program.Debug("github", $"Request {(args == null ? url : $"{url}?{string.Join("&", args)}")}");
            Program.Debug("github", $"Headers\r\n\t{string.Join("\t", httpRequest.Headers.ToString().Split('\n')).Replace("\r", "\r\n")}");
            Program.Debug("github", $"Status Code {httpResponse.StatusCode} ({(int)httpResponse.StatusCode})", 
                httpResponse.StatusCode == HttpStatusCode.OK ? Event.Success : Event.Warning);

            return httpResponse.StatusCode;
        }

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

public IList<RouteInfo> GetAllRouteInfo()
        {
            List<RouteInfo> list = new List<RouteInfo>();

            var routeCollection = this.actionDescriptorCollectionProvider.ActionDescriptors.Items;
            foreach (ActionDescriptor route in routeCollection)
            {
                RouteInfo info = new RouteInfo();

                // Area
                if (route.RouteValues.ContainsKey("area"))
                {
                    info.Area = route.RouteValues["area"];
                }

                // Path and Invocation of Razor Pages
                if (route is PageActionDescriptor)
                {
                    var e = route as PageActionDescriptor;
                    info.Path = e.ViewEnginePath;
                    info.Namespace = e.RelativePath;
                }

                // Path of Route Attribute
                if (route.AttributeRouteInfo != null)
                {
                    var e = route;
                    info.Path = $"/{e.AttributeRouteInfo.Template}";
                    this.AddParameters(info, e);
                }

                if (route is ControllerActionDescriptor)
                {
                    var e = route as ControllerActionDescriptor;
                    info.ControllerName = e.ControllerName;
                    info.ActionName = e.ActionName;

                    info.Namespace = e.ControllerTypeInfo.AsType().Namespace;
                    if (string.IsNullOrEmpty(e.AttributeRouteInfo?.Template))
                    {
                        if (!string.IsNullOrEmpty(info.Area))
                        {
                            info.Path = $"/{info.Area}";
                        }

                        info.Path += $"/{e.ControllerName}/{e.ActionName}";
                    }

                    this.AddParameters(info, e);
                }

                // Extract HTTP Verb
                if (route.ActionConstraints != null && route.ActionConstraints.Select(t => t.GetType()).Contains(typeof(HttpMethodActionConstraint)))
                {
                    if (route.ActionConstraints.FirstOrDefault(a => a.GetType() == typeof(HttpMethodActionConstraint)) is HttpMethodActionConstraint httpMethodAction)
                    {
                        info.HttpMethods = string.Join(",", httpMethodAction.HttpMethods);
                    }
                }

                list.Add(info);
            }

            return list;
        }

19 View Source File : UtilitiesTests.cs
License : Microsoft Public License
Project Creator : AArnott

[Fact]
	public void BinarySearch_VaryingLengthsAndIndexes()
	{
		const int MaxLength = 5;
		List<int> list = new(MaxLength);
		for (int length = 1; length <= MaxLength; length++)
		{
			list.Clear();
			for (int i = 0; i < length; i++)
			{
				list.Add(1 + (i * 2));
			}

			this.Logger.WriteLine("Testing with a length of: {0}", length);
			for (int value = list[0] - 1; value <= list[^1] + 1; value++)
			{
				this.Logger.WriteLine($"Searching for a position for {value} amongst: {{ {string.Join(", ", list)} }}");
				replacedert.Equal(list.BinarySearch(value), Utilities.BinarySearch(list, value));
			}
		}
	}

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

public IEnumerable<string> SeatNames(PricingCategory pricingCategory)
        {
            var suggestionsMade = ForCategory[pricingCategory];
            return suggestionsMade.Select(s => string.Join("-", s.SeatNames()));
        }

19 View Source File : BaseCallbackMethodProvider.cs
License : MIT License
Project Creator : Abc-Arbitrage

protected override bool AddLookupItems(CSharpCodeCompletionContext context, IItemsCollector collector)
		{
			var identifier = context.TerminatedContext.TreeNode as IIdentifier;
			var expression = identifier.GetParentSafe<IReferenceExpression>();

			if (expression == null)
			{
				return false;
			}

			if (!(expression.ConditionalQualifier is IInvocationExpression invocation))
			{
				return false;
			}

			var solution = context.BasicContext.Solution;
			var methodIdentifier = solution.GetComponent<IMoqMethodIdentifier>();

			if (methodIdentifier.IsMoqReturnMethod(invocation))
			{
				invocation = invocation.InvokedExpression?.FirstChild as IInvocationExpression;
			}

			var mockedMethod = GetMockedMethodFromSetupMethod(solution, invocation);

			if (mockedMethod == null || mockedMethod.Parameters.Count == 0)
			{
				return false;
			}

			var types = GetMockedMethodParameterTypes(solution, invocation);
			var variablesName = mockedMethod.Parameters.Select(p => p.ShortName);
			var proposedCallback = $"Callback<{string.Join(",", types)}>(({string.Join(",", variablesName)}) => {{}})";

			var item = CSharpLookupItemFactory.Instance.CreateKeywordLookupItem(context,
				proposedCallback,
				TailType.None,
				PsiSymbolsThemedIcons.Method.Id);

			item.SetInsertCaretOffset(-2);
			item.SetReplaceCaretOffset(-2);
			item.WithInitializedRanges(context.CompletionRanges, context.BasicContext);
			item.SetTopPriority();
			collector.Add(item);

			return true;
		}

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

private static string RowDataToString(IReadOnlyList<TestMergeDataRow> data)
            => string.Join(';', data.Select(d=>$"{d.Id},{d.Value},{d.Version}"));

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

public void WriteDefinition(XshdSyntaxDefinition definition)
		{
			if (definition == null)
				throw new ArgumentNullException("definition");
			writer.WriteStartElement("SyntaxDefinition", Namespace);
			if (definition.Name != null)
				writer.WriteAttributeString("name", definition.Name);
			if (definition.Extensions != null)
				writer.WriteAttributeString("extensions", string.Join(";", definition.Extensions.ToArray()));

			definition.AcceptElements(this);

			writer.WriteEndElement();
		}

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

public override string ToString() => string.Join(Environment.NewLine, Clauses.Select(x => (object)x.ToString()).ToArray());

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

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

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 : ForgotPassword.cshtml.cs
License : GNU Lesser General Public License v3.0
Project Creator : 8720826

public async Task<IActionResult> OnPostAsync([FromBody]SendResetEmailDto dto)
        {
            if (!ModelState.IsValid)
            {
                return await Task.FromResult(new JsonResult(new
                {
                    Status = false,
                    ErrorMessage = ModelState.Where(e => e.Value.Errors.Count > 0).Select(e => e.Value.Errors.First().ErrorMessage).First()
                }));
            }

            var userId = _accountContext.UserId;

            var command = new SendResetEmailCommand(dto.Email);
            await _bus.SendCommand(command);

            if (_notifications.HasNotifications())
            {
                var errorMessage = string.Join(";", _notifications.GetNotifications().Select(x => x.Content));
                return await Task.FromResult(new JsonResult(new
                {
                    status = false,
                    errorMessage
                }));
            }

            return await Task.FromResult(new JsonResult(new
            {
                status = true
            }));

        }

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 : Join.cshtml.cs
License : GNU Lesser General Public License v3.0
Project Creator : 8720826

public async Task<IActionResult> OnGetAsync(int playerId = 0)
        {
            if (playerId == 0)
            {
                return Content("请重新进入游戏");
            }

            var command = new JoinGameCommand(_account.UserId, playerId);
            await _bus.SendCommand(command);

            if (_notifications.HasNotifications())
            {
                var errorMessage = string.Join(";", _notifications.GetNotifications().Select(x => x.Content));
                return Content(errorMessage);
            }

            return RedirectToPage("/Game/Index");

        }

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

public async Task<IActionResult> OnPostAsync([FromBody]ModifyPreplacedwordDto dto)
        {
            if (!ModelState.IsValid)
            {
                return await Task.FromResult(new JsonResult(new
                {
                    Status = false,
                    ErrorMessage = ModelState.Where(e => e.Value.Errors.Count > 0).Select(e => e.Value.Errors.First().ErrorMessage).First()
                }));
            }

            var userId = _accountContext.UserId;

            var command = new ModifyPreplacedwordCommand(userId, dto.Preplacedword, dto.NewPreplacedword);
            await _bus.SendCommand(command);

            if (_notifications.HasNotifications())
            {
                var errorMessage = string.Join(";", _notifications.GetNotifications().Select(x => x.Content));
                return await Task.FromResult(new JsonResult(new
                {
                    status = false,
                    errorMessage
                }));
            }

            return await Task.FromResult(new JsonResult(new
            {
                status = true
            }));

        }

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

int DbContextBetchUpdatePriv(EnreplacedyState[] ups, bool isLiveUpdate) {
			if (ups.Any() == false) return 0;
			var uplst1 = ups[ups.Length - 1];
			var uplst2 = ups.Length > 1 ? ups[ups.Length - 2] : null;

			if (_states.TryGetValue(uplst1.Key, out var lstval1) == false) return -999;
			var lstval2 = default(EnreplacedyState);
			if (uplst2 != null && _states.TryGetValue(uplst2.Key, out lstval2) == false) throw new Exception($"特别错误:更新失败,数据未被跟踪:{_fsql.GetEnreplacedyString(_enreplacedyType, uplst2.Value)}");

			var cuig1 = _fsql.CompareEnreplacedyValueReturnColumns(_enreplacedyType, uplst1.Value, lstval1.Value, true);
			var cuig2 = uplst2 != null ? _fsql.CompareEnreplacedyValueReturnColumns(_enreplacedyType, uplst2.Value, lstval2.Value, true) : null;

			List<EnreplacedyState> data = null;
			string[] cuig = null;
			if (uplst2 != null && string.Compare(string.Join(",", cuig1), string.Join(",", cuig2)) != 0) {
				//最后一个不保存
				data = ups.ToList();
				data.RemoveAt(ups.Length - 1);
				cuig = cuig2;
			} else if (isLiveUpdate) {
				//立即保存
				data = ups.ToList();
				cuig = cuig1;
			}

			if (data?.Count > 0) {

				if (cuig.Length == _table.Columns.Count)
					return ups.Length == data.Count ? -998 : -997;

				var updateSource = data.Select(a => a.Value).ToArray();
				var update = this.OrmUpdate(null).SetSource(updateSource).IgnoreColumns(cuig);

				var affrows = update.ExecuteAffrows();

				foreach (var newval in data) {
					if (_states.TryGetValue(newval.Key, out var tryold))
						_fsql.MapEnreplacedyValue(_enreplacedyType, newval.Value, tryold.Value);
					if (newval.OldValue != null)
						_fsql.MapEnreplacedyValue(_enreplacedyType, newval.Value, newval.OldValue);
				}
				return affrows;
			}

			//等待下次对比再保存
			return 0;
		}

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

public async Task<IActionResult> OnPostAsync([FromBody]ResetPreplacedwordDto dto)
        {
            if (!ModelState.IsValid)
            {
                return await Task.FromResult(new JsonResult(new
                {
                    Status = false,
                    ErrorMessage = ModelState.Where(e => e.Value.Errors.Count > 0).Select(e => e.Value.Errors.First().ErrorMessage).First()
                }));
            }

            var userId = _accountContext.UserId;

            var command = new ResetPreplacedwordCommand(dto.Email, dto.Preplacedword, dto.Code);
            await _bus.SendCommand(command);

            if (_notifications.HasNotifications())
            {
                var errorMessage = string.Join(";", _notifications.GetNotifications().Select(x => x.Content));
                return await Task.FromResult(new JsonResult(new
                {
                    status = false,
                    errorMessage
                }));
            }

            return await Task.FromResult(new JsonResult(new
            {
                status = true
            }));

        }

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

private static string GetCrefNamespace(string cref, string @namespace)
        {
            IList<string> sameString = new List<string>();
            var splitNamespace = @namespace.Split('.');
            var splitCref = cref.Split('.');
            int minLength = Math.Min(splitNamespace.Length, splitCref.Length);
            for (int i = 0; i < minLength; i++)
            {
                if (splitCref[i] == splitNamespace[i])
                {
                    sameString.Add(splitCref[i]);
                }
                else
                {
                    break;
                }
            }

            cref = cref.Substring(string.Join('.', sameString).Length + 1);
            return cref;
        }

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

public async Task<IActionResult> OnPostAsync([FromBody]VerifyEmailDto dto)
        {
            if (!ModelState.IsValid)
            {
                return await Task.FromResult(new JsonResult(new
                {
                    Status = false,
                    ErrorMessage = ModelState.Where(e => e.Value.Errors.Count > 0).Select(e => e.Value.Errors.First().ErrorMessage).First()
                }));
            }

            var userId = _accountContext.UserId;

            var command = new VerifyEmailCommand(dto.Email,dto.Code);
            await _bus.SendCommand(command);

            if (_notifications.HasNotifications())
            {
                var errorMessage = string.Join(";", _notifications.GetNotifications().Select(x => x.Content));
                return await Task.FromResult(new JsonResult(new
                {
                    status = false,
                    errorMessage
                }));
            }

            return await Task.FromResult(new JsonResult(new
            {
                status = true
            }));

        }

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

public static void WriteSigmaFileResult(Options o, int gradientMax, int ruleCount, Dictionary<string, List<string>> techniques)
        {
            try
            {
                var entries = techniques
                    .ToList()
                    .Select(entry => new
                    {
                        techniqueID = entry.Key,
                        score = entry.Value.Count,
                        comment = (o.NoComment) ? null : string.Join(Environment.NewLine, entry.Value.Select(x => x.Split("/").Last()))
                    });

                string filename = o.OutFile.EndsWith(".json") ? "sigma-coverage.json" : $"{o.OutFile}.json";
                File.WriteAllText(filename, JsonConvert.SerializeObject(new
                {
                    domain = "mitre-enterprise",
                    name = "Sigma signatures coverage",
                    gradient = new
                    {
                        colors = new[] { "#a0eab5", "#0f480f" },
                        maxValue = gradientMax,
                        minValue = 0
                    },
                    version = "4.2",
                    techniques = entries
                }, Formatting.Indented, new JsonSerializerSettings
                {
                    NullValueHandling = NullValueHandling.Ignore
                }));
                Console.WriteLine($"[*] Layer file written in {filename} ({ruleCount} rules)");
            }
            catch (Exception e)
            {
                Console.WriteLine("Problem writing to file: " + e.Message);
            }
        }

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

private static string MakePairListString(IEnumerable<WexPair> pairlist)
        {
            return string.Join("-", pairlist.Select(WexPairHelper.ToString).ToArray());
        }

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

protected string BuildIndexName(IExprTableFullName tableIn, IndexMeta index)
        {
            if (index.Name != null && !string.IsNullOrEmpty(index.Name))
            {
                return index.Name;
            }

            var table = tableIn.AsExprTableFullName();

            var schemaName = table.DbSchema != null ? this.Options.MapSchema(table.DbSchema.Schema.Name) + "_" : null;

            var columns = string.Join("_", index.Columns.Select(c => c.Column.ColumnName.Name + (c.Descending ? "_DESC" : null)));

            return $"IX_{schemaName}{table.TableName.Name}_{columns}";
        }

19 View Source File : VxFormValidationCssClassProviderBase.cs
License : MIT License
Project Creator : Aaltuj

public override string GetFieldCssClreplaced(EditContext editContext, in FieldIdentifier fieldIdentifier)
        {
            var cssClreplacedName = base.GetFieldCssClreplaced(editContext, fieldIdentifier);


            // If we can find a [VxFormValidationCssClreplaced], use it
            var propertyInfo = fieldIdentifier.Model.GetType().GetProperty(fieldIdentifier.FieldName);
            if (propertyInfo != null && editContext.IsModified(fieldIdentifier))
            {
                var customValidationClreplacedName = (VxFormCssClreplacedAttribute)propertyInfo
                    .GetCustomAttributes(typeof(VxFormCssClreplacedAttribute), true)
                    .FirstOrDefault();

                if (customValidationClreplacedName == null && CssClreplacedAttribute != null)
                    customValidationClreplacedName = CssClreplacedAttribute;

                if (FormLayoutOptions.VisualValidationPolicy == VisualFeedbackValidationPolicy.VALID_AND_INVALID)
                {
                    cssClreplacedName = string.Join(' ', cssClreplacedName.Split(' ').Select(token => token switch
                    {
                        "valid" => customValidationClreplacedName.Valid ?? token,
                        "invalid" => customValidationClreplacedName.Invalid ?? token,
                        _ => token,
                    }));
                }
                else if (FormLayoutOptions.VisualValidationPolicy == VisualFeedbackValidationPolicy.ONLY_INVALID)
                {
                    cssClreplacedName = string.Join(' ', cssClreplacedName.Split(' ').Select(token => token switch
                    {
                        "valid" => "",
                        "invalid" => customValidationClreplacedName.Invalid ?? token,
                        _ => token,
                    }));
                }

19 View Source File : SlnWriter.cs
License : MIT License
Project Creator : 3F

protected void Validate(IEnumerable<ISection> sections)
        {
            var coh = GetSlnHandlers(sections)
                        .Where(s => s.CoHandlers != null && s.CoHandlers.Count > 0)
                        .ToDictionary(key => key.GetType(), value => value.CoHandlers);

            foreach(var h in Handlers)
            {
                if(coh.ContainsKey(h.Key))
                {
                    if(coh[h.Key].Except(Handlers.Keys).Count() != coh[h.Key].Count) {
                        throw new CoHandlerRuleException(
                            $"Only parent handler is allowed '{h.Key}' <- {String.Join(", ", coh[h.Key].Select(c => c.Name))}"
                        );
                    }
                    continue;
                }

                if(coh.Where(v => v.Value.Contains(h.Key))
                        .Select(v => v.Key)
                        .Except(Handlers.Keys).Count() > 0)
                {
                    throw new CoHandlerRuleException($"Define parent handler instead of '{h.Key}'.");
                }
            }
        }

19 View Source File : Dialog_Exchenge.cs
License : Apache License 2.0
Project Creator : AantCoder

public void DoWindowOrders(Rect inRect)
        {
            if (OrdersGrid == null && Orders != null && Orders.Count > 0)
            {
                //инициализация
                OrdersGrid = new GridBox<OrderTrade>();
                //Transferables = GameUtils.DistinctThings(AllThings);
                //var dicMaxCount = Transferables.ToDictionary(t => t, t => t.MaxCount);
                OrdersGrid.DataSource = Orders;
                OrdersGrid.LineHeight = 24f;
                OrdersGrid.ShowSelected = true;
                OrdersGrid.Tooltip = null;
                OrdersGrid.OnClick += (int line, OrderTrade item) =>
                {
                    SetEditOrder(item);
                    if (EditOrderIsMy)
                        EditOrderreplacedle = "OCity_Dialog_Exchenge_Edit".Translate();
                    else
                        EditOrderreplacedle = "OCity_Dialog_Exchenge_Viewing_Orders".Translate() + item.Owner.Login;
                };
                OrdersMenu = null;
                OrdersGrid.OnDrawLine = (int line, OrderTrade item, Rect rectLine) =>
                {
                    bool showTop = line == 0; //при выводе таблицы, рисуем с первой же строкой
                    Text.WordWrap = false;
                    Text.Anchor = TextAnchor.MiddleLeft;
                    try
                    {
                        float currentWidth = rectLine.width;

                        //Галочка частное
                        var rect2 = new Rect(rectLine.x + rectLine.width - 24f, rectLine.y, 24f, rectLine.height);
                        currentWidth -= 24f;
                        var flag = item.PrivatPlayers == null || item.PrivatPlayers.Count == 0;
                        TooltipHandler.TipRegion(rect2, flag
                            ? "OCity_Dialog_Exchenge_Deal_Open_Everyone".Translate()
                            : "OCity_Dialog_Exchenge_Deal_Open_Specific".Translate(string.Join(", ", item.PrivatPlayers.Select(p => p.Login).ToArray())));
                        Widgets.Checkbox(rect2.position, ref flag, 24f, false);

                        //Ник продавца
                        rect2 = new Rect(rectLine.x + currentWidth - 200f, rectLine.y, 200f, rectLine.height);
                        if (showTop)
                        {
                            OrdersMenu = new Dictionary<Rect, string>();
                            var rect2t = new Rect(rect2.x, 0f, rect2.width, rect2.height);
                            OrdersMenu.Add(rect2t, "OCity_Dialog_Exchenge_Seller".Translate());
                        }
                        currentWidth -= 200f;
                        TooltipHandler.TipRegion(rect2, item.Owner.Login + Environment.NewLine + "OCity_Dialog_Exchenge_BeenOnline".Translate() + item.Owner.LastSaveTime.ToGoodUtcString());
                        Widgets.Label(rect2, item.Owner.Login);

                        //Расстояние где торгуют (todo), название места
                        rect2 = new Rect(rectLine.x + currentWidth - 200f, rectLine.y, 200f, rectLine.height);
                        if (showTop)
                        {
                            var rect2t = new Rect(rect2.x, 0f, rect2.width, rect2.height);
                            OrdersMenu.Add(rect2t, "OCity_Dialog_Exchenge_Location".Translate());
                        }
                        currentWidth -= 200f;

                        string text = "";
                        if (item.Place.DayPath > 0)
                        {
                            text = item.Place.DayPath.ToStringDecimalIfSmall() + "OCity_Dialog_Exchenge_Days".Translate();
                        }
                        text += "OCity_Dialog_Exchenge_In".Translate() + item.Place.Name;

                        TooltipHandler.TipRegion(rect2, "OCity_Dialog_Exchenge_Location_Goods".Translate() + Environment.NewLine + text);
                        Widgets.Label(rect2, text);

                        //Кол-во повторов
                        rect2 = new Rect(rectLine.x + currentWidth - 60f, rectLine.y, 60f, rectLine.height);
                        if (showTop)
                        {
                            var rect2t = new Rect(rect2.x, 0f, rect2.width, rect2.height);
                            OrdersMenu.Add(rect2t, "OCity_Dialog_Exchenge_Number".Translate());
                        }
                        currentWidth -= 60f;
                        text = item.CountReady.ToString();
                        TooltipHandler.TipRegion(rect2, "OCity_Dialog_Exchenge_Max_Repereplacedion_Transaction".Translate() + Environment.NewLine + text);
                        Widgets.Label(rect2, text);

                        //Иконки и перечень (описание в подсказке)
                        rect2 = new Rect(rectLine.x, rectLine.y, currentWidth / 2f, rectLine.height); //от 0 до половины остатка
                        if (showTop)
                        {
                            var rect2t = new Rect(rect2.x, 0f, rect2.width, rect2.height);
                            OrdersMenu.Add(rect2t, "OCity_Dialog_Exchenge_Acquire".Translate());
                        }
                        var rect3 = new Rect(rect2.x, rect2.y, rectLine.height, rectLine.height);
                        for (int i = 0; i < item.SellThings.Count; i++)
                        {
                            var th = item.SellThings[i];
                            GameUtils.DravLineThing(rect3, th, false);
                            var textCnt = item.SellThings[i].Count.ToString();
                            var textCntW = Text.CalcSize(textCnt).x;
                            Widgets.Label(new Rect(rect3.xMax, rect3.y, textCntW, rect3.height), textCnt);
                            TooltipHandler.TipRegion(new Rect(rect3.x, rect3.y, rect3.width + textCntW, rect3.height), th.LabelText);
                            rect3.x += rectLine.height + textCntW + 2f;
                        }

                        //"-" Иконки и перечень что просят
                        rect2 = new Rect(rectLine.x + rect2.width, rectLine.y, currentWidth - rect2.width, rectLine.height); //от конца прошлого до остатка
                        if (showTop)
                        {
                            var rect2t = new Rect(rect2.x, 0f, rect2.width, rect2.height);
                            OrdersMenu.Add(rect2t, "OCity_Dialog_Exchenge_GiveTo".Translate());
                        }
                        //Дальше отличается от блока выше только SellThings -> BuyThings
                        rect3 = new Rect(rect2.x, rect2.y, rectLine.height, rectLine.height);
                        for (int i = 0; i < item.BuyThings.Count; i++)
                        {
                            var th = item.BuyThings[i];
                            GameUtils.DravLineThing(rect3, th, false);
                            var textCnt = item.BuyThings[i].Count.ToString();
                            var textCntW = Text.CalcSize(textCnt).x;
                            Widgets.Label(new Rect(rect3.xMax, rect3.y, textCntW, rect3.height), textCnt);
                            TooltipHandler.TipRegion(new Rect(rect3.x, rect3.y, rect3.width + textCntW, rect3.height), th.LabelText);
                            rect3.x += rectLine.height + textCntW + 2f;
                        }
                    }
                    catch (Exception e)
                    {
                        Log.Error(e.ToString());
                    }
                    Text.WordWrap = true;
                };
            }

            //заголовок
            Rect rect = new Rect(inRect.x, inRect.y, inRect.width, 24f);
            inRect.yMin += rect.height;
            Text.Font = GameFont.Tiny; // высота Tiny 18
            Text.Anchor = TextAnchor.MiddleCenter;
            Widgets.Label(rect, (Orders == null || Orders.Count == 0) ? "OCity_Dialog_Exchenge_No_Warrants".Translate() : "OCity_Dialog_Exchenge_Active_Orders".Translate(Orders.Count.ToString()));

            //кнопка "Выбрать"
            rect.xMin += inRect.width - 140f;
            Text.Anchor = TextAnchor.MiddleCenter;
            if (Widgets.ButtonText(rect.ContractedBy(1f), "OCity_Dialog_Exchenge_Update".Translate(), true, false, true))
            {
                SoundDefOf.Tick_High.PlayOneShotOnCamera(null);

                UpdateOrders();
                return;
            }

            //заголовок таблицы
            var rectTop = new Rect(inRect.x, inRect.y, inRect.width, 18f);
            inRect.yMin += rectTop.height;
            if (OrdersMenu != null)
            {
                Text.Anchor = TextAnchor.MiddleCenter;
                foreach (var om in OrdersMenu)
                {
                    var rect2t = new Rect(om.Key.x, rectTop.y, om.Key.width, rectTop.height);
                    Widgets.Label(rect2t, om.Value);
                }
            }

            //всё что ниже это грид
            Text.Font = GameFont.Tiny;
            Text.Anchor = TextAnchor.MiddleLeft;
            Widgets.DrawMenuSection(inRect);

            if (OrdersGrid == null) return;

            OrdersGrid.Area = inRect.ContractedBy(5f);
            OrdersGrid.Drow();
        }

19 View Source File : EntityDescriptor.cs
License : MIT License
Project Creator : 17MKH

private void SetTableName()
    {
        var tableArr = EnreplacedyType.GetCustomAttribute<TableAttribute>(false);
        if (tableArr != null && tableArr.Name.NotNull())
        {
            TableName = tableArr.Name;
        }
        else
        {
            //去掉Enreplacedy后缀
            TableName = Name;

            //给表名称添加分隔符
            if (DbContext.Options.TableNameSeparator.NotNull())
            {
                var matchs = Regex.Matches(TableName, "[A-Z][^A-Z]+");
                TableName = string.Join(DbContext.Options.TableNameSeparator, matchs);
            }
        }

        var setPrefix = tableArr?.SetPrefix ?? true;
        //设置前缀
        if (setPrefix && DbContext.Options.TableNamePrefix.NotNull())
        {
            TableName = DbContext.Options.TableNamePrefix + TableName;
        }

        //设置自动创建表
        AutoCreate = tableArr?.AutoCreate ?? true;

        //表名称小写
        if (DbContext.Adapter.SqlLowerCase)
        {
            TableName = TableName.ToLower();
        }
    }

19 View Source File : MoneyFile.cs
License : Microsoft Public License
Project Creator : AArnott

private static string SqlJoinConditionWithOperator(string op, IEnumerable<string> constraints) => string.Join($" {op} ", constraints.Select(c => $"({c})"));

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 : BaseItIsAnyParameterProvider.cs
License : MIT License
Project Creator : Abc-Arbitrage

protected override bool AddLookupItems(CSharpCodeCompletionContext context, IItemsCollector collector)
		{
			var identifier = context.TerminatedContext.TreeNode as IIdentifier;
			var mockedMethodArgument = identifier.GetParentSafe<IReferenceExpression>().GetParentSafe<ICSharpArgument>();

			var mockedMethodInvocationExpression =
				mockedMethodArgument?.GetParentSafe<IArgumentList>().GetParentSafe<IInvocationExpression>();

			var methodInvocation = mockedMethodInvocationExpression?.GetParentSafe<ILambdaExpression>()
				.GetParentSafe<IArgument>()
				.GetParentSafe<IArgumentList>()
				.GetParentSafe<IInvocationExpression>();

			if (methodInvocation == null)
			{
				return false;
			}

			var methodIdentifier = context.BasicContext.Solution.GetComponent<IMoqMethodIdentifier>();
			var isSetup = IsSetupMethod(methodIdentifier, methodInvocation);
            var isVerify = IsVerifyMethod(methodIdentifier, methodInvocation);

			if (!isSetup && !isVerify)
			{
				return false;
			}

			var argumentIndex = mockedMethodArgument.IndexOf();

			if (context.ExpectedTypesContext != null)
			{
				foreach (var expectedType in context.ExpectedTypesContext.ExpectedITypes)
				{
					if (expectedType.Type == null)
					{
						continue;
					}

					var typeName = expectedType.Type.GetPresentableName(CSharpLanguage.Instance);
					var proposedCompletion = context.IsQualified ? $"IsAny<{typeName}>()" : $"It.IsAny<{typeName}>()";
					AddLookup(context, collector, proposedCompletion);
				}
			}

			if (argumentIndex != 0 || mockedMethodInvocationExpression.Reference == null || context.IsQualified)
			{
				return true;
			}

			var candidates = mockedMethodInvocationExpression.InvocationExpressionReference.GetCandidates();
			foreach (var candidate in candidates)
            {
                var method = candidate.GetDeclaredElement() as IMethod;
                var subsreplacedution = candidate.GetSubsreplacedution();

				if (method == null || method.Parameters.Count <= 1)
					continue;

                var parameter = method.Parameters.Select(x => GereplacedIsAny(x, subsreplacedution));
                var proposedCompletion = string.Join(", ", parameter);
                AddLookup(context, collector, proposedCompletion, isSetup ? 2 : 1);
			}

			return false;
		}

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

public override void Wipe(string uid) {
            using UserDataBatchContext batch = OpenBatch();
            using MiniCommand mini = new(this) {
                SqliteOpenMode.ReadWrite,
                string.Join('\n', GetAllTables().Select(table => [email protected]"
                    DELETE
                    FROM [{table}]
                    WHERE uid = $uid;
                ")),
                { "$uid", uid },
            };
            mini.Run();
        }

19 View Source File : CsharpMemberProvider.cs
License : MIT License
Project Creator : Abc-Arbitrage

public Dictionary<string, string> GetClreplacedFields(IClreplacedBody clreplacedBody, PsiLanguageType languageType)
        {
            var dic = new Dictionary<string, string>();
            var fields = clreplacedBody.FieldDeclarations.Select(x => x.TypeUsage.FirstChild as IReferenceName).Where(x => x != null && x.ShortName == "Mock").ToArray();

            foreach (var referenceName in fields)
            {
                var types = referenceName.TypeArguments.Select(x => x.GetPresentableName(languageType, DeclaredElementPresenterTextStyles.Empty).Text);
                var strType = string.Join(",", types);
                var mockType = GetGenericMock(strType);
                var field = (IFieldDeclaration)referenceName.Parent.NextSibling.NextSibling;

                if (!dic.ContainsKey(mockType))
                    dic.Add(mockType, field.DeclaredName);
            }

            return dic;
        }

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

protected override void Initialize(CSharpCompilation oldCompilation, CancellationToken _)
        {
            OptimizationLevel compilationConfiguration = oldCompilation.Options.OptimizationLevel;
            DebugCometaryAttribute attribute = Attribute;

            if (compilationConfiguration == OptimizationLevel.Debug && !attribute.RunInDebug)
                return;
            if (compilationConfiguration == OptimizationLevel.Release && !attribute.RunInRelease)
                return;

            string typeName = attribute.MainClreplacedName ?? DebugCometaryAttribute.DefaultMainClreplacedName;

            if (replacedembly.GetEntryreplacedembly().GetType(typeName) != null)
                return;

            CSharpCompilation EditCompilation(CSharpCompilation compilation, CancellationToken cancellationToken)
            {
                CSharpCompilationOptions options = compilation.Options;
                CSharpCompilationOptions newOptions = options
                    .WithOutputKind(OutputKind.ConsoleApplication)
                    .WithMainTypeName(typeName);

                // - Make the compilation an application, allowing its execution.
                // - Redirect the entry point to the automatically generated clreplaced.
                compilation = compilation.WithOptions(newOptions);

                // Create the entry point:
                string errorFile = Path.GetTempFileName();

                CSharpSyntaxTree generatedSyntaxTree = (CSharpSyntaxTree)CSharpSyntaxTree.ParseText(GetSourceText(attribute.DisplayEndOfCompilationMessage, errorFile), cancellationToken: cancellationToken);
                CompilationUnitSyntax generatedRoot = generatedSyntaxTree.GetCompilationUnitRoot(cancellationToken);

                ClreplacedDeclarationSyntax clreplacedSyntax = (ClreplacedDeclarationSyntax)generatedRoot.Members.Last();
                ClreplacedDeclarationSyntax originalClreplacedSyntax = clreplacedSyntax;

                // Edit the generated syntax's name, if needed.
                if (typeName != DebugCometaryAttribute.DefaultMainClreplacedName)
                {
                    clreplacedSyntax = clreplacedSyntax.WithIdentifier(F.Identifier(typeName));
                }

                // Change the filename and arguments.
                SyntaxList<MemberDeclarationSyntax> members = clreplacedSyntax.Members;

                FieldDeclarationSyntax WithValue(FieldDeclarationSyntax node, string value)
                {
                    VariableDeclaratorSyntax variableSyntax = node.Declaration.Variables[0];
                    LiteralExpressionSyntax valueSyntax = F.LiteralExpression(
                        SyntaxKind.StringLiteralExpression,
                        F.Literal(value)
                    );

                    return node.WithDeclaration(
                        node.Declaration.WithVariables(node.Declaration.Variables.Replace(
                            variableSyntax, variableSyntax.WithInitializer(F.EqualsValueClause(valueSyntax))
                        ))
                    );
                }

                FieldDeclarationSyntax WithBoolean(FieldDeclarationSyntax node, bool value)
                {
                    VariableDeclaratorSyntax variableSyntax = node.Declaration.Variables[0];
                    LiteralExpressionSyntax valueSyntax = F.LiteralExpression(value ? SyntaxKind.TrueLiteralExpression : SyntaxKind.FalseLiteralExpression);

                    return node.WithDeclaration(
                        node.Declaration.WithVariables(node.Declaration.Variables.Replace(
                            variableSyntax, variableSyntax.WithInitializer(F.EqualsValueClause(valueSyntax))
                        ))
                    );
                }

                for (int i = 0; i < members.Count; i++)
                {
                    FieldDeclarationSyntax field = members[i] as FieldDeclarationSyntax;

                    if (field == null)
                        continue;

                    string fieldName = field.Declaration.Variables[0].Identifier.Text;

                    switch (fieldName)
                    {
                        case "References":
                            field = WithValue(field, string.Join(";", compilation.References.OfType<PortableExecutableReference>().Select(x => x.FilePath)));
                            break;
                        case "Files":
                            field = WithValue(field, string.Join(";", compilation.SyntaxTrees.Select(x => x.FilePath)));
                            break;
                        case "replacedemblyName":
                            field = WithValue(field, compilation.replacedemblyName);
                            break;
                        case "ErrorFile":
                            field = WithValue(field, errorFile);
                            break;
                        case "Written":
                            field = WithBoolean(field, OutputAllTreesAttribute.Instance != null);
                            break;
                        case "BreakAtEnd":
                            field = WithBoolean(field, attribute.DisplayEndOfCompilationMessage);
                            break;
                        case "BreakAtStart":
                            field = WithBoolean(field, attribute.BreakDuringStart);
                            break;
                        default:
                            continue;
                    }

                    members = members.Replace(members[i], field);
                }

                // Return the modified compilation.
                return compilation.AddSyntaxTrees(
                    generatedSyntaxTree
                        .WithCometaryOptions(this)
                        .WithRoot(
                            generatedRoot.WithMembers(generatedRoot.Members.Replace(originalClreplacedSyntax, clreplacedSyntax.WithMembers(members))
                        )
                    )
                );
            }

            CompilationPipeline += EditCompilation;
        }

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 : CelesteNetTCPUDPConnection.cs
License : MIT License
Project Creator : 0x0ade

public void WriteTeapot(string[] features, uint token) {
            lock (TCPWriter) {
                using (StreamWriter writer = new(TCPWriterStream, CelesteNetUtils.UTF8NoBOM, 1024, true))
                    writer.Write(string.Format(CelesteNetUtils.HTTPTeapot, string.Join(CelesteNetUtils.ConnectionFeatureSeparator, features), token));
                TCPWriterStream.Flush();
            }
        }

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

public static async Task RunGenTablesOptions(GenTablesOptions options)
        {
            ILogger logger = new DefaultLogger(Console.Out, options.Verbosity);

            logger.LogMinimal("Table proxy clreplacedes generation is running...");

            string directory = EnsureDirectory(options.OutputDir, logger, "Output", true);

            if (string.IsNullOrEmpty(options.ConnectionString))
            {
                throw new SqExpressCodeGenException("Connection string cannot be empty");
            }
            logger.LogNormal("Checking existing code...");
            IReadOnlyDictionary<TableRef, ClreplacedDeclarationSyntax> existingCode = ExistingCodeExplorer.FindTableDescriptors(directory, DefaultFileSystem.Instance);
            if(logger.IsNormalOrHigher) logger.LogNormal(existingCode.Count > 0
                ? $"Found {existingCode.Count} already existing table descriptor clreplacedes."
                : "No table descriptor clreplacedes found.");

            var sqlManager = CreateDbManager(options);

            logger.LogNormal("Connecting to database...");

            var connectionTest = await sqlManager.TryOpenConnection();
            if (!string.IsNullOrEmpty(connectionTest))
            {
                throw new SqExpressCodeGenException(connectionTest);
            }

            logger.LogNormal("Success!");

            var tables = await sqlManager.SelectTables();

            if(logger.IsNormalOrHigher)
            {
                logger.LogNormal(tables.Count > 0
                    ? $"Found {tables.Count} tables."
                    : "No tables found in the database.");

                if (logger.IsDetailed)
                {
                    foreach (var tableModel in tables)
                    {
                        Console.WriteLine($"{tableModel.DbName} ({tableModel.Name})");
                        foreach (var tableModelColumn in tableModel.Columns)
                        {
                            Console.WriteLine($"- {tableModelColumn.DbName.Name} {tableModelColumn.ColumnType.GetType().Name}{(tableModelColumn.Pk.HasValue ? " (PK)":null)}{(tableModelColumn.Fk != null ? $" (FK: {string.Join(';', tableModelColumn.Fk.Select(f=>f.ToString()))})" : null)}");
                        }
                    }
                }
            }

            logger.LogNormal("Code generation...");
            IReadOnlyDictionary<TableRef, TableModel> tableMap = tables.ToDictionary(t => t.DbName);

            var tableClreplacedGenerator = new TableClreplacedGenerator(tableMap, options.Namespace, existingCode);

            foreach (var table in tables)
            {
                string filePath = Path.Combine(directory, $"{table.Name}.cs");

                if(logger.IsDetailed) logger.LogDetailed($"{table.DbName} to \"{filePath}\".");

                var text = tableClreplacedGenerator.Generate(table, out var existing).ToFullString();
                await File.WriteAllTextAsync(filePath, text);

                if (logger.IsDetailed) logger.LogDetailed(existing ? "Existing file updated." : "New file created.");
            }

            var allTablePath = Path.Combine(directory, "AllTables.cs");

            if (logger.IsDetailed) logger.LogDetailed($"AllTables to \"{allTablePath}\".");

            await File.WriteAllTextAsync(allTablePath, TableListClreplacedGenerator.Generate(allTablePath, tables, options.Namespace, options.TableClreplacedPrefix, DefaultFileSystem.Instance).ToFullString());

            logger.LogMinimal("Table proxy clreplacedes generation successfully completed!");
        }

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

private static MemoryStream Compile(string replacedemblyName, IEnumerable<SyntaxTree> trees, IEnumerable<MetadataReference> references)
        {
            var compilation = CSharpCompilation.Create(replacedemblyName, trees, references, new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));
            var stream = new MemoryStream();
            var result = compilation.Emit(stream);
            if (!result.Success)
            {
                throw new Exception("Generate dynamic proxy failed:\n" + string.Join(";\n", result.Diagnostics.Select(i => i.ToString())));
            }
            stream.Seek(0, SeekOrigin.Begin);
            return stream;
        }

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 : Reg.cshtml.cs
License : GNU Lesser General Public License v3.0
Project Creator : 8720826

public async Task<IActionResult> OnPostAsync([FromBody]UserRegDto dto)
        {

            if (!ModelState.IsValid)
            {
                return await Task.FromResult(new JsonResult(new
                {
                    Status = false,
                    ErrorMessage = ModelState.Where(e => e.Value.Errors.Count > 0).Select(e => e.Value.Errors.First().ErrorMessage).First()
                }));
            }

            var userId = _accountContext.UserId;

            var command = new RegCommand(dto.Email, dto.Preplacedword);
            await _bus.SendCommand(command);

            if (_notifications.HasNotifications())
            {
                var errorMessage = string.Join(";", _notifications.GetNotifications().Select(x => x.Content));
                return await Task.FromResult(new JsonResult(new
                {
                    status = false,
                    errorMessage
                }));
            }

            return await Task.FromResult(new JsonResult(new
            {
                status = true
            }));

        }

See More Examples