System.Collections.Generic.IEnumerable.Any()

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

13798 Examples 7

19 Source : TaskAgentHttpClientBase.cs
with MIT License
from actions

public virtual Task<TaskAgent> GetAgentAsync(
            int poolId,
            int agentId,
            bool? includeCapabilities = null,
            bool? includereplacedignedRequest = null,
            bool? includeLastCompletedRequest = null,
            IEnumerable<string> propertyFilters = null,
            object userState = null,
            CancellationToken cancellationToken = default)
        {
            HttpMethod httpMethod = new HttpMethod("GET");
            Guid locationId = new Guid("e298ef32-5878-4cab-993c-043836571f42");
            object routeValues = new { poolId = poolId, agentId = agentId };

            List<KeyValuePair<string, string>> queryParams = new List<KeyValuePair<string, string>>();
            if (includeCapabilities != null)
            {
                queryParams.Add("includeCapabilities", includeCapabilities.Value.ToString());
            }
            if (includereplacedignedRequest != null)
            {
                queryParams.Add("includereplacedignedRequest", includereplacedignedRequest.Value.ToString());
            }
            if (includeLastCompletedRequest != null)
            {
                queryParams.Add("includeLastCompletedRequest", includeLastCompletedRequest.Value.ToString());
            }
            if (propertyFilters != null && propertyFilters.Any())
            {
                queryParams.Add("propertyFilters", string.Join(",", propertyFilters));
            }

            return SendAsync<TaskAgent>(
                httpMethod,
                locationId,
                routeValues: routeValues,
                version: new ApiResourceVersion(6.0, 2),
                queryParameters: queryParams,
                userState: userState,
                cancellationToken: cancellationToken);
        }

19 Source : FlagsEnum.cs
with MIT License
from actions

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

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

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

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

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

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

                return mappings;
            });

            var values = stringValue.Split(s_enumSeparatorCharArray);

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

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

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

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

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

19 Source : VssFileStorage.cs
with MIT License
from actions

protected Dictionary<string, JRaw> LoadFile()
            {
                Dictionary<string, JRaw> settings = null;
                if (File.Exists(m_filePath))
                {
                    settings = LoadFile(m_filePath);
                }
                if ((settings == null || !settings.Any()) && File.Exists(m_bckUpFilePath))
                {
                    settings = LoadFile(m_bckUpFilePath);
                }
                return settings ?? new Dictionary<string, JRaw>(PathComparer);
            }

19 Source : VssFileStorage.cs
with MIT License
from actions

protected void SaveFile(IDictionary<string, JRaw> originalSettings, IDictionary<string, JRaw> newSettings)
            {
                string newContent = JValue.Parse(JsonConvert.SerializeObject(newSettings)).ToString(Formatting.Indented);
                if (originalSettings.Any())
                {
                    // during testing, creating this backup provided reliability in the event of aborted threads, and
                    // crashed processes.  With this, I was not able to simulate a case where corruption happens, but there is no
                    // 100% gaurantee against corruption.
                    string originalContent = JValue.Parse(JsonConvert.SerializeObject(originalSettings)).ToString(Formatting.Indented);
                    SaveFile(m_bckUpFilePath, originalContent);
                }
                SaveFile(m_filePath, newContent);
                if (File.Exists(m_bckUpFilePath))
                {
                    File.Delete(m_bckUpFilePath);
                }
            }

19 Source : TaskAgentHttpClientBase.cs
with MIT License
from actions

public virtual Task<List<TaskAgentPool>> GetAgentPoolsAsync(
            string poolName = null,
            IEnumerable<string> properties = null,
            TaskAgentPoolType? poolType = null,
            object userState = null,
            CancellationToken cancellationToken = default)
        {
            HttpMethod httpMethod = new HttpMethod("GET");
            Guid locationId = new Guid("a8c47e17-4d56-4a56-92bb-de7ea7dc65be");

            List<KeyValuePair<string, string>> queryParams = new List<KeyValuePair<string, string>>();
            if (poolName != null)
            {
                queryParams.Add("poolName", poolName);
            }
            if (properties != null && properties.Any())
            {
                queryParams.Add("properties", string.Join(",", properties));
            }
            if (poolType != null)
            {
                queryParams.Add("poolType", poolType.Value.ToString());
            }

            return SendAsync<List<TaskAgentPool>>(
                httpMethod,
                locationId,
                version: new ApiResourceVersion(5.1, 1),
                queryParameters: queryParams,
                userState: userState,
                cancellationToken: cancellationToken);
        }

19 Source : DictionaryExtensions.cs
with MIT License
from actions

public static Lazy<TDictionary> SetRangeIfRangeNotNullOrEmpty<K, V, TDictionary>(this Lazy<TDictionary> lazyDictionary, IEnumerable<KeyValuePair<K, V>> keyValuePairs)
            where TDictionary : IDictionary<K, V>
        {
            if (keyValuePairs != null && keyValuePairs.Any())
            {
                lazyDictionary.Value.SetRange(keyValuePairs);
            }

            return lazyDictionary;
        }

19 Source : UriExtensions.cs
with MIT License
from actions

public static void AddMultiple<T>(this IList<KeyValuePair<String, String>> collection, String key, IEnumerable<T> values, Func<T, String> convert)
        {
            ArgumentUtility.CheckForNull(collection, "collection");
            ArgumentUtility.CheckStringForNullOrEmpty(key, "name");

            if (convert == null) convert = (val) => val.ToString();

            if (values != null && values.Any())
            {
                StringBuilder newValue = new StringBuilder();
                KeyValuePair<String, String> matchingKvp = collection.FirstOrDefault(kvp => kvp.Key.Equals(key));
                if (matchingKvp.Key == key)
                {
                    collection.Remove(matchingKvp);
                    newValue.Append(matchingKvp.Value);
                }

                foreach (var value in values)
                {
                    if (newValue.Length > 0)
                    {
                        newValue.Append(",");
                    }
                    newValue.Append(convert(value));
                }

                collection.Add(new KeyValuePair<String, String>(key, newValue.ToString()));
            }
        }

19 Source : TaskAgentHttpClientBase.cs
with MIT License
from actions

public virtual Task<List<TaskAgent>> GetAgentsAsync(
            int poolId,
            string agentName = null,
            bool? includeCapabilities = null,
            bool? includereplacedignedRequest = null,
            bool? includeLastCompletedRequest = null,
            IEnumerable<string> propertyFilters = null,
            IEnumerable<string> demands = null,
            object userState = null,
            CancellationToken cancellationToken = default)
        {
            HttpMethod httpMethod = new HttpMethod("GET");
            Guid locationId = new Guid("e298ef32-5878-4cab-993c-043836571f42");
            object routeValues = new { poolId = poolId };

            List<KeyValuePair<string, string>> queryParams = new List<KeyValuePair<string, string>>();
            if (agentName != null)
            {
                queryParams.Add("agentName", agentName);
            }
            if (includeCapabilities != null)
            {
                queryParams.Add("includeCapabilities", includeCapabilities.Value.ToString());
            }
            if (includereplacedignedRequest != null)
            {
                queryParams.Add("includereplacedignedRequest", includereplacedignedRequest.Value.ToString());
            }
            if (includeLastCompletedRequest != null)
            {
                queryParams.Add("includeLastCompletedRequest", includeLastCompletedRequest.Value.ToString());
            }
            if (propertyFilters != null && propertyFilters.Any())
            {
                queryParams.Add("propertyFilters", string.Join(",", propertyFilters));
            }
            if (demands != null && demands.Any())
            {
                queryParams.Add("demands", string.Join(",", demands));
            }

            return SendAsync<List<TaskAgent>>(
                httpMethod,
                locationId,
                routeValues: routeValues,
                version: new ApiResourceVersion(6.0, 2),
                queryParameters: queryParams,
                userState: userState,
                cancellationToken: cancellationToken);
        }

19 Source : ServerDataProvider.cs
with MIT License
from actions

public async Task<ApiResourceLocationCollection> GetResourceLocationsAsync(CancellationToken cancellationToken = default(CancellationToken))
        {
            if (m_resourceLocations == null)
            {
                IEnumerable<ServiceDefinition> definitions = await FindServiceDefinitionsAsync(null).ConfigureAwait(false);

                if (definitions != null)
                {
                    IEnumerable<ServiceDefinition> resourceLocationDefinitions = definitions.Where(x => x.ResourceVersion > 0);

                    if (resourceLocationDefinitions.Any())
                    {
                        ApiResourceLocationCollection resourceLocations = new ApiResourceLocationCollection();

                        foreach (ServiceDefinition definition in resourceLocationDefinitions)
                        {
                            resourceLocations.AddResourceLocation(ApiResourceLocation.FromServiceDefinition(definition));
                        }

                        m_resourceLocations = resourceLocations;
                    }
                }
            }

            return m_resourceLocations;
        }

19 Source : WrappedException.cs
with MIT License
from actions

private void TryWrapCustomProperties(Exception exception)
        {
            var customPropertiesWithDataMemberAttribute = GetCustomPropertiesInfo();

            if (customPropertiesWithDataMemberAttribute.Any())
            {
                this.CustomProperties = new Dictionary<string, object>();
            }

            foreach (var customProperty in customPropertiesWithDataMemberAttribute)
            {
                try
                {
                    this.CustomProperties.Add(customProperty.Name, customProperty.GetValue(exception));
                }
                catch
                {
                    // skip this property
                }
            }
        }

19 Source : BankIdRecommendedUserMessage.cs
with MIT License
from ActiveLogin

public MessageShortName GetMessageShortNameForCollectResponse(
            CollectStatus collectStatus,
            CollectHintCode hintCode,
            bool authPersonalIdenreplacedyNumberProvided,
            bool accessedFromMobileDevice,
            bool usingQrCode)
        {
            var mapping = CollectResponseMappings
                            .Where(x => !x.CollectStatuses.Any() || x.CollectStatuses.Contains(collectStatus))
                            .Where(x => !x.CollectHintCodes.Any() || x.CollectHintCodes.Contains(hintCode))
                            .Where(x => x.AuthPersonalIdenreplacedyNumberProvided == null || x.AuthPersonalIdenreplacedyNumberProvided == authPersonalIdenreplacedyNumberProvided)
                            .Where(x => x.AccessedFromMobileDevice == null || x.AccessedFromMobileDevice == accessedFromMobileDevice)
                            .Where(x => x.UsingQrCode == null || x.UsingQrCode == usingQrCode)
                            .FirstOrDefault(x => x.MessageShortName != MessageShortName.Unknown);

            return mapping?.MessageShortName ?? MessageShortName.RFA22;
        }

19 Source : BankIdRecommendedUserMessage.cs
with MIT License
from ActiveLogin

public MessageShortName GetMessageShortNameForErrorResponse(ErrorCode errorCode)
        {
            var mapping = ErrorResponseMappings
                            .Where(x => !x.ErrorCodes.Any() || x.ErrorCodes.Contains(errorCode))
                            .FirstOrDefault(x => x.MessageShortName != MessageShortName.Unknown);

            return mapping?.MessageShortName ?? MessageShortName.RFA22;
        }

19 Source : BankIdLauncher.cs
with MIT License
from ActiveLogin

private static string GetQueryString(Dictionary<string, string> queryStringParams)
        {
            if (!queryStringParams.Any())
            {
                return string.Empty;
            }

            var queryBuilder = new QueryBuilder(queryStringParams);
            return queryBuilder.ToQueryString().ToString();
        }

19 Source : CodeFixVerifier.cs
with GNU General Public License v3.0
from Acumatica

private async Task VerifyFixAsync(string language, Diagnosticreplacedyzer replacedyzer, CodeFixProvider codeFixProvider, 
										  string oldSource, string newSource, bool allowNewCompilerDiagnostics, int codeFixIndex = 0)
		{
			var doreplacedent = CreateDoreplacedent(oldSource, language);
			var replacedyzerDiagnostics = await GetSortedDiagnosticsFromDoreplacedentsAsync(replacedyzer, new[] { doreplacedent }, checkOnlyFirstDoreplacedent: true).ConfigureAwait(false);
			var compilerDiagnostics = await GetCompilerDiagnosticsAsync(doreplacedent).ConfigureAwait(false);
			var attempts = replacedyzerDiagnostics.Length;

			for (int i = 0; i < attempts; ++i)
			{
				var actions = new List<CodeAction>();
				var context = new CodeFixContext(doreplacedent, replacedyzerDiagnostics[0], (a, d) => actions.Add(a), CancellationToken.None);
				await codeFixProvider.RegisterCodeFixesAsync(context).ConfigureAwait(false);

				if (!actions.Any())
				{
					break;
				}

				doreplacedent = await ApplyCodeActionAsync(doreplacedent, actions.ElementAt(codeFixIndex)).ConfigureAwait(false);
				
				replacedyzerDiagnostics = await GetSortedDiagnosticsFromDoreplacedentsAsync(replacedyzer, new[] { doreplacedent }, checkOnlyFirstDoreplacedent: true).ConfigureAwait(false);

				var newCompilerDiagnostics = GetNewDiagnostics(compilerDiagnostics, await GetCompilerDiagnosticsAsync(doreplacedent).ConfigureAwait(false));

				//check if applying the code fix introduced any new compiler diagnostics
				if (!allowNewCompilerDiagnostics && newCompilerDiagnostics.Any())
				{
					// Format and get the compiler diagnostics again so that the locations make sense in the output
					doreplacedent = doreplacedent.WithSyntaxRoot(Formatter.Format(await doreplacedent.GetSyntaxRootAsync().ConfigureAwait(false), 
						Formatter.Annotation, doreplacedent.Project.Solution.Workspace));
					newCompilerDiagnostics = GetNewDiagnostics(compilerDiagnostics, await GetCompilerDiagnosticsAsync(doreplacedent).ConfigureAwait(false));

					replacedert.True(false,
						string.Format("Fix introduced new compiler diagnostics:\r\n{0}\r\n\r\nNew doreplacedent:\r\n{1}\r\n",
							string.Join("\r\n", newCompilerDiagnostics.Select(d => d.ToString())),
							(await doreplacedent.GetSyntaxRootAsync().ConfigureAwait(false)).ToFullString()));
				}

				//check if there are replacedyzer diagnostics left after the code fix
				if (!replacedyzerDiagnostics.Any())
				{
					break;
				}
			}

			//after applying all of the code fixes, compare the resulting string to the inputted one
			var actual = await GetStringFromDoreplacedentAsync(doreplacedent).ConfigureAwait(false);
			replacedert.Equal(newSource, actual);
		}

19 Source : DiagnosticVerifier.cs
with GNU General Public License v3.0
from Acumatica

private static void VerifyDiagnosticResults(IEnumerable<Diagnostic> actualResults, Diagnosticreplacedyzer replacedyzer, params DiagnosticResult[] expectedResults)
		{
			int expectedCount = expectedResults.Count();
			int actualCount = actualResults.Count();

			if (expectedCount != actualCount)
			{
				string diagnosticsOutput = actualResults.Any() ? FormatDiagnostics(replacedyzer, actualResults.ToArray()) : "    NONE.";
                
				replacedert.True(false,
					string.Format("Mismatch between number of diagnostics returned, expected \"{0}\" actual \"{1}\"\r\n\r\nDiagnostics:\r\n{2}\r\n", expectedCount, actualCount, diagnosticsOutput));
			}

			for (int i = 0; i < expectedResults.Length; i++)
			{
				var actual = actualResults.ElementAt(i);
				var expected = expectedResults[i];

				if (expected.Line == -1 && expected.Column == -1)
				{
					if (actual.Location != Location.None)
					{
						replacedert.True(false,
							string.Format("Expected:\nA project diagnostic with No location\nActual:\n{0}",
							FormatDiagnostics(replacedyzer, actual)));
					}
				}
				else
				{
					VerifyDiagnosticLocation(replacedyzer, actual, actual.Location, expected.Locations.First());
					var additionalLocations = actual.AdditionalLocations.ToArray();

					if (additionalLocations.Length != expected.Locations.Length - 1)
					{
						replacedert.True(false,
							string.Format("Expected {0} additional locations but got {1} for Diagnostic:\r\n    {2}\r\n",
								expected.Locations.Length - 1, additionalLocations.Length,
								FormatDiagnostics(replacedyzer, actual)));
					}

					for (int j = 0; j < additionalLocations.Length; ++j)
					{
						VerifyDiagnosticLocation(replacedyzer, actual, additionalLocations[j], expected.Locations[j + 1]);
					}
				}

				if (actual.Id != expected.Id)
				{
					replacedert.True(false,
						string.Format("Expected diagnostic id to be \"{0}\" was \"{1}\"\r\n\r\nDiagnostic:\r\n    {2}\r\n",
							expected.Id, actual.Id, FormatDiagnostics(replacedyzer, actual)));
				}

				if (actual.Severity != expected.Severity)
				{
					replacedert.True(false,
						string.Format("Expected diagnostic severity to be \"{0}\" was \"{1}\"\r\n\r\nDiagnostic:\r\n    {2}\r\n",
							expected.Severity, actual.Severity, FormatDiagnostics(replacedyzer, actual)));
				}

				if (actual.GetMessage() != expected.Message)
				{
					replacedert.True(false,
						string.Format("Expected diagnostic message to be \"{0}\" was \"{1}\"\r\n\r\nDiagnostic:\r\n    {2}\r\n",
							expected.Message, actual.GetMessage(), FormatDiagnostics(replacedyzer, actual)));
				}
			}
		}

19 Source : AopSubscriberAttribute.cs
with MIT License
from ad313

public string GetKey(string key, Dictionary<string, object> dic)
        {
            if (dic == null || !dic.Any())
                return key;

            if (!MapDictionary.TryGetValue(GetMapDictionaryKey(), out Dictionary<string, string> mapDic))
                return key.FillValue(dic);

            return ParamsHelper.FillParamValues(key, mapDic, dic);
        }

19 Source : MemoryEventBusProvider.cs
with MIT License
from ad313

private async Task PushToErrorQueueAsync<T>(string channel, List<T> data)
        {
            if (data == null || !data.Any())
                return;

            var queue = GetErrorQueue(channel);

            foreach (var item in data)
            {
                await queue.Writer.WriteAsync(_serializerProvider.SerializeBytes(item));
            }
        }

19 Source : TypeFinder.cs
with MIT License
from ad313

public List<Type> FindAllInterface(List<replacedembly> replacedemblies = null)
        {
            replacedemblies ??= Getreplacedemblies();

            if (replacedemblies == null || !replacedemblies.Any())
                return new List<Type>();

            return replacedemblies.SelectMany(d => d.GetTypes().Where(t => t.IsInterface)).ToList();
        }

19 Source : RabbitMqEventBusProvider.cs
with MIT License
from ad313

public void SubscribeQueue<T>(string key, int length, int delay, ExceptionHandlerEnum exceptionHandler, Func<List<T>, Task> handler,
            Func<Exception, List<T>, Task> error = null, Func<Task> completed = null)
        {
            if (length <= 0)
                throw new Exception("length must be greater than zero");

            SubscribeBroadcastInternal<T>(key, async msg =>
            {
                while (true)
                {
                    List<T> data = null;
                    Exception ex = null;
                    var isCompleted = false;

                    try
                    {
                        data = await GetQueueItemsAsync<T>(key, length);
                        if (!data.Any())
                        {
                            isCompleted = true;
                            return;
                        }

                        await handler.Invoke(data);
                    }
                    catch (Exception e)
                    {
                        ex = e;

                        if (await HandleException(key, exceptionHandler, data, e))
                            return;
                    }
                    finally
                    {
                        if (ex != null && error != null)
                            await HandleError(key, data, error, ex);

                        if (completed != null && isCompleted)
                            await HandleCompleted(key, completed);
                    }

                    if (isCompleted)
                        break;

                    if (delay > 0)
                        await Task.Delay(delay);
                }
            }, true);

            _lockObjectDictionary.TryAdd(key, new AsyncLock());
        }

19 Source : RabbitMqEventBusProvider.cs
with MIT License
from ad313

private async Task PushToQueueAsync<T>(string key, List<T> data, int length = 1000)
        {
            if (data == null || !data.Any())
                return;

            var queueName = GetChannelQueueKey(key);
            await PushToQueueAsyncMethod(queueName, data, length);
        }

19 Source : RabbitMqEventBusProvider.cs
with MIT License
from ad313

private async Task PushToErrorQueueAsync<T>(string key, List<T> data, int length = 10000)
        {
            if (data == null || !data.Any())
                return;

            var queueName = GetChannelErrorQueueKey(key);
            await PushToQueueAsyncMethod(queueName, data, length);
        }

19 Source : RabbitMqEventBusProvider.cs
with MIT License
from ad313

private async Task PushToQueueAsyncMethod<T>(string queueName, List<T> data, int length = 10000)
        {
            if (data == null || !data.Any())
                return;

            var channel = _rabbitMqClientProvider.GetChannel();
            channel.QueueDeclare(queueName, true, false, false, null);

            //持久化
            var properties = channel.BasicProperties();

            if (data.Count > length)
            {
                foreach (var list in Helpers.SplitList(data, length))
                {
                    foreach (var item in list)
                    {
                        channel.BasicPublish("", queueName, properties, _serializerProvider.SerializeBytes(item));
                    }
                    await Task.Delay(10);
                }
            }
            else
            {
                foreach (var item in data)
                {
                    channel.BasicPublish("", queueName, properties, _serializerProvider.SerializeBytes(item));
                }
            }

            _rabbitMqClientProvider.ReturnChannel(channel);
        }

19 Source : MemoryEventBusProvider.cs
with MIT License
from ad313

public async Task PublishQueueAsync<T>(string key, List<T> message)
        {
            if (message == null || !message.Any())
                return;

            await PushToQueueAsync(key, message);
            await PublishAsync(key, new EventMessageModel<T>());
        }

19 Source : MemoryEventBusProvider.cs
with MIT License
from ad313

public void SubscribeQueue<T>(string key, int length, int delay, ExceptionHandlerEnum exceptionHandler, Func<List<T>, Task> handler, Func<Exception, List<T>, Task> error = null, Func<Task> completed = null)
        {
            if (length <= 0)
                throw new Exception("length must be greater than zero");

            Subscribe<T>(key, async msg =>
            {
                if (!IsEnable(key))
                {
                    Console.WriteLine($"{DateTime.Now} 频道【{key}】 已关闭消费");
                    return;
                }

                var pages = GetTotalPagesFromQueue(key, length);

                var needGc = pages * length > 1000;

                while (pages > 0)
                {
                    var data = await GetQueueItemsAsync<T>(key, length);
                    if (!data.Any())
                        break;

                    Exception ex = null;

                    try
                    {
                        await handler.Invoke(data);
                    }
                    catch (Exception e)
                    {
                        ex = e;

                        if (await HandleException(key, exceptionHandler, data, e))
                        {
                            pages = 1;
                            return;
                        }
                    }
                    finally
                    {
                        if (ex != null && error != null)
                            await HandleError(key, data, error, ex);

                        if (completed != null && pages == 1)
                            await HandleCompleted(key, completed);
                    }

                    pages--;

                    if (pages == 0 && needGc)
                    {
                        GC.Collect();
                        Console.WriteLine("---------------gc-----------------");
                    }

                    if (delay > 0)
                        await Task.Delay(delay);
                }
            });
        }

19 Source : MemoryEventBusProvider.cs
with MIT License
from ad313

public async Task SubscribeQueueTest<T>(string key, int length, int delay, ExceptionHandlerEnum exceptionHandler, Func<List<T>, Task> handler,
            Func<Exception, List<T>, Task> error = null, Func<Task> completed = null)
        {
            if (length <= 0)
                throw new Exception("length must be greater than zero");

            if (delay <= 0)
                throw new Exception("delay must be greater than zero");

            await SubscribeTest<T>(key, async msg =>
            {
                var pages = GetTotalPagesFromQueue(key, length);

                while (pages > 0)
                {
                    var data = await GetQueueItemsAsync<T>(key, length);
                    if (!data.Any())
                        break;

                    Exception ex = null;

                    try
                    {
                        await handler.Invoke(data);
                    }
                    catch (Exception e)
                    {
                        ex = e;

                        if (await HandleException(key, exceptionHandler, data, e))
                        {
                            pages = 1;
                            return;
                        }
                    }
                    finally
                    {
                        if (ex != null && error != null)
                            await HandleError(key, data, error, ex);

                        if (completed != null && pages == 1)
                            await HandleCompleted(key, completed);
                    }

                    pages--;

                    await Task.Delay(delay);
                }
            });
        }

19 Source : SerializerProvider.cs
with MIT License
from ad313

public T Deserialize<T>(byte[] bytes)
        {
            return bytes == null || !bytes.Any() ? default : JsonSerializer.Deserialize<T>(bytes);
        }

19 Source : SerializerProvider.cs
with MIT License
from ad313

public object Deserialize(byte[] bytes, Type type)
        {
            return bytes == null || !bytes.Any() ? default : JsonSerializer.Deserialize(bytes, type);
        }

19 Source : RedisEventBusProvider.cs
with MIT License
from ad313

public void SubscribeQueue<T>(string key, int length, int delay, ExceptionHandlerEnum exceptionHandler, Func<List<T>, Task> handler,
            Func<Exception, List<T>, Task> error = null, Func<Task> completed = null)
        {
            if (length <= 0)
                throw new Exception("length must be greater than zero");

            SubscribeInternal<T>(key, async msg =>
            {
                var pages = GetTotalPagesFromQueue(key, length);

                while (pages > 0)
                {
                    var data = await GetQueueItemsAsync<T>(key, length);
                    if (!data.Any())
                        break;

                    Exception ex = null;

                    try
                    {
                        await handler.Invoke(data);
                    }
                    catch (Exception e)
                    {
                        ex = e;

                        if (await HandleException(key, exceptionHandler, data, e))
                        {
                            pages = 1;
                            return;
                        }
                    }
                    finally
                    {
                        if (ex != null && error != null)
                            await HandleError(key, data, error, ex);

                        if (completed != null && pages == 1)
                            await HandleCompleted(key, completed);
                    }

                    pages--;

                    if (delay > 0)
                        await Task.Delay(delay);
                }
            }, true);
        }

19 Source : RedisEventBusProvider.cs
with MIT License
from ad313

private async Task PushToQueueAsync<T>(string channel, List<T> data, int length = 500)
        {
            if (data == null || !data.Any())
                return;

            var key = GetChannelQueueKey(channel);

            if (data.Count > length)
            {
                foreach (var list in Helpers.SplitList(data, length))
                {
                    await RedisHelper.LPushAsync(key, list.ToArray());
                    await Task.Delay(10);
                }
            }
            else
            {
                await RedisHelper.LPushAsync(key, data.ToArray());
            }
        }

19 Source : RedisEventBusProvider.cs
with MIT License
from ad313

private async Task PushToErrorQueueAsync<T>(string channel, List<T> data)
        {
            if (data == null || !data.Any())
                return;

            var key = GetChannelErrorQueueKey(channel);
            await RedisHelper.LPushAsync(key, data.ToArray());
        }

19 Source : MemoryEventBusProvider.cs
with MIT License
from ad313

private async Task PushToQueueAsync<T>(string channel, List<T> data, int length = 10000)
        {
            if (data == null || !data.Any())
                return;

            var queue = GetQueue(channel);

            var type = typeof(T);

            if (data.Count > length)
            {
                foreach (var list in Helpers.SplitList(data, length))
                {
                    foreach (var item in list)
                    {
                        await queue.Writer.WriteAsync(_serializerProvider.SerializeBytes(item, type));
                    }

                    await Task.Delay(10);
                }
            }
            else
            {
                foreach (var item in data)
                {
                    await queue.Writer.WriteAsync(_serializerProvider.SerializeBytes(item, type));
                }
            }
        }

19 Source : LoadedNodeManager.cs
with GNU General Public License v3.0
from Adam-Wilkinson

public void PlaceNode(IEnumerable<string> catagoryPath, INodeContainer node)
            {
                if (!catagoryPath.Any() || catagoryPath.First() == null || catagoryPath.First() == "")
                {
                    Nodes.Add(node);
                }
                else
                {
                    if (!SubCatagories.ContainsKey(catagoryPath.First()))
                    {
                        SubCatagories.Add(catagoryPath.First(), new NodeCatagories(SubCatagories.Count));
                    }

                    SubCatagories[catagoryPath.First()].PlaceNode(catagoryPath.Skip(1), node);
                }
            }

19 Source : InbuiltPluginFinder.cs
with GNU General Public License v3.0
from Adam-Wilkinson

private static DirectoryInfo GetSolutionFileFolder(string rootPath)
        {
            DirectoryInfo directory = new FileInfo(rootPath).Directory;
            while (directory != null && !directory.GetFiles("*.sln").Any())
            {
                directory = directory.Parent;
            }

            return directory;
        }

19 Source : TreeCodeTemplate.custom.cs
with MIT License
from adamant

private bool IsNewDefinition(GrammarRule rule, GrammarProperty property)
        {
            return BaseProperties(rule, property.Name).Any();
        }

19 Source : ConformanceTests.cs
with MIT License
from adamant

[Theory]
        [MemberData(nameof(GetConformanceTestCases))]
        public void Test_cases(TestCase testCase)
        {
            // Setup
            var codeFile = CodeFile.Load(testCase.FullCodePath);
            var code = codeFile.Code.Text;
            var compiler = new AdamantCompiler()
            {
                SaveLivenessreplacedysis = true,
                SaveReachabilityGraphs = true,
            };
            var references = new Dictionary<Name, PackageIL>();

            // Reference Standard Library
            var stdLibPackage = CompileStdLib(compiler);
            references.Add("adamant.stdlib", stdLibPackage);

            try
            {
                // replacedyze
                var package = compiler.CompilePackage("testPackage", codeFile.Yield(),
                    references.ToFixedDictionary());

                // Check for compiler errors
                replacedert.NotNull(package.Diagnostics);
                var diagnostics = package.Diagnostics;
                var errorDiagnostics = CheckErrorsExpected(testCase, codeFile, code, diagnostics);

                // Disreplacedemble
                var ilreplacedembler = new ILreplacedembler();
                testOutput.WriteLine(ilreplacedembler.Disreplacedemble(package));

                // We got only expected errors, but need to not go on to emit code
                if (errorDiagnostics.Any())
                    return;

                // Emit Code
                var codePath = Path.ChangeExtension(testCase.FullCodePath, "c");
                EmitCode(package, stdLibPackage, codePath);

                // Compile Code to Executable
                var exePath = CompileToExecutable(codePath);

                // Execute and check results
                var process = Execute(exePath);

                process.WaitForExit();
                var stdout = process.StandardOutput.ReadToEnd();
                testOutput.WriteLine("stdout:");
                testOutput.WriteLine(stdout);
                replacedert.Equal(ExpectedOutput(code, "stdout", testCase.FullCodePath), stdout);
                var stderr = process.StandardError.ReadToEnd();
                testOutput.WriteLine("stderr:");
                testOutput.WriteLine(stderr);
                replacedert.Equal(ExpectedOutput(code, "stderr", testCase.FullCodePath), stderr);
                replacedert.Equal(ExpectedExitCode(code), process.ExitCode);
            }
            catch (FatalCompilationErrorException ex)
            {
                var diagnostics = ex.Diagnostics;
                CheckErrorsExpected(testCase, codeFile, code, diagnostics);
            }
        }

19 Source : ConformanceTests.cs
with MIT License
from adamant

private List<Diagnostic> CheckErrorsExpected(
            TestCase testCase,
            CodeFile codeFile,
            string code,
            FixedList<Diagnostic> diagnostics)
        {
            // Check for compiler errors
            var expectCompileErrors = ExpectCompileErrors(code);
            var expectedCompileErrorLines = ExpectedCompileErrorLines(codeFile, code);

            if (diagnostics.Any())
            {
                testOutput.WriteLine("Compiler Errors:");
                foreach (var diagnostic in diagnostics)
                {
                    testOutput.WriteLine(
                        $"{testCase.RelativeCodePath}:{diagnostic.StartPosition.Line}:{diagnostic.StartPosition.Column} {diagnostic.Level} {diagnostic.ErrorCode}");
                    testOutput.WriteLine(diagnostic.Message);
                }

                testOutput.WriteLine("");
            }

            var errorDiagnostics = diagnostics
                .Where(d => d.Level >= DiagnosticLevel.CompilationError).ToList();

            if (expectedCompileErrorLines.Any())
            {
                foreach (var expectedCompileErrorLine in expectedCompileErrorLines)
                {
                    // replacedert a single error on the given line
                    var errorsOnLine = errorDiagnostics.Count(e =>
                        e.StartPosition.Line == expectedCompileErrorLine);
                    replacedert.True(errorsOnLine == 1,
                        $"Expected one error on line {expectedCompileErrorLine}, found {errorsOnLine}");
                }
            }

            if (expectCompileErrors)
                replacedert.True(errorDiagnostics.Any(), "Expected compilation errors and there were none");
            else
                foreach (var error in errorDiagnostics)
                {
                    var errorLine = error.StartPosition.Line;
                    if (expectedCompileErrorLines.All(line => line != errorLine))
                        replacedert.True(false, $"Unexpected error on line {error.StartPosition.Line}");
                }

            return errorDiagnostics;
        }

19 Source : SolutionDirectory.cs
with MIT License
from adamant

public static string Get()
        {
            var directory = Directory.GetCurrentDirectory() ?? throw new InvalidOperationException("Could not get current directory");
            while (directory != null && !Directory.GetFiles(directory, "*.sln", SearchOption.TopDirectoryOnly).Any())
            {
                directory = Path.GetDirectoryName(directory) ?? throw new InvalidOperationException("Null directory name");
            }
            return directory ?? throw new InvalidOperationException("Compiler is confused, this can't be null");
        }

19 Source : TypeExtensions.cs
with MIT License
from adamant

public static bool HasCustomAttribute<TAttribute>(this Type type)
        {
            return type.GetCustomAttributes(true).OfType<TAttribute>().Any();
        }

19 Source : DmnDefinitionFactory.cs
with MIT License
from adamecr

protected static void AddNewRequiredInputs(IReadOnlyCollection<DmnVariableDefinition> newInputs, List<DmnVariableDefinition> requiredInputs)
        {
            if (requiredInputs == null) throw Logger.Fatal<ArgumentNullException>($"{nameof(requiredInputs)} is null.");
            if (newInputs == null || !newInputs.Any()) return;

            foreach (var requiredInput in newInputs)
            {
                if (!requiredInputs.Exists(i => i.Name == requiredInput.Name))
                    requiredInputs.Add(requiredInput);
            }
        }

19 Source : AssemblyExtensions.cs
with MIT License
from adamfisher

public static Stream GetEmbeddedResourceStream(this replacedembly replacedembly, string resourceFileName)
        {
            var resourceNames = replacedembly.GetManifestResourceNames();

            var resourcePaths = resourceNames
                .Where(x => x.EndsWith(resourceFileName, StringComparison.OrdinalIgnoreCase))
                .ToArray();

            if (!resourcePaths.Any())
            {
                throw new Exception($"Resource ending with {resourceFileName} not found.");
            }

            if (resourcePaths.Count() > 1)
            {
                throw new Exception($"Multiple resources ending with {resourceFileName} found: {Environment.NewLine}{string.Join(Environment.NewLine, resourcePaths)}");
            }

            return replacedembly.GetManifestResourceStream(resourcePaths.Single());
        }

19 Source : ArgsParser.cs
with Apache License 2.0
from adamralph

public static (IReadOnlyList<string> Targets, Options Options, IReadOnlyList<string> UnknownOptions, bool showHelp) Parse(IReadOnlyCollection<string> args)
        {
            var helpArgs = args.Where(arg => helpOptions.Contains(arg, StringComparer.OrdinalIgnoreCase));
            var nonHelpArgs = args.Where(arg => !helpOptions.Contains(arg, StringComparer.OrdinalIgnoreCase));

            var targets = nonHelpArgs.Where(arg => !arg.StartsWith("-", StringComparison.Ordinal)).ToList();

            var nonTargets = nonHelpArgs.Where(arg => arg.StartsWith("-", StringComparison.Ordinal));

            var optionArgs = nonTargets.Where(arg => !helpOptions.Contains(arg, StringComparer.OrdinalIgnoreCase)).Select(arg => (arg, true));
            var result = OptionsReader.Read(optionArgs);
            var options = new Options
            {
                Clear = result.Clear,
                DryRun = result.DryRun,
                Host = result.Host,
                ListDependencies = result.ListDependencies,
                ListInputs = result.ListInputs,
                ListTargets = result.ListTargets,
                ListTree = result.ListTree,
                NoColor = result.NoColor,
                NoExtendedChars = result.NoExtendedChars,
                Parallel = result.Parallel,
                SkipDependencies = result.SkipDependencies,
                Verbose = result.Verbose,
            };

            return (targets, options, result.UnknownOptions, helpArgs.Any());
        }

19 Source : Repository.cs
with Apache License 2.0
from adamralph

public Version GetVersion(string tagPrefix, VersionPart autoIncrement, string defaultPreReleasePhase, ILogger log)
        {
            var commit = this.head;

            if (commit == null)
            {
                var version = new Version(defaultPreReleasePhase);

                log.Info($"No commits found. Using default version {version}.");

                return version;
            }

            var tagsAndVersions = this.tags
                .Select(tag => (tag, Version.ParseOrDefault(tag.Name, tagPrefix)))
                .OrderBy(tagAndVersion => tagAndVersion.Item2)
                .ThenBy(tagsAndVersion => tagsAndVersion.tag.Name)
                .ToList();

            var commitsChecked = new HashSet<string>();
            var count = 0;
            var height = 0;
            var candidates = new List<Candidate>();
            var commitsToCheck = new Stack<(Commit, int, Commit)>();
            Commit previousCommit = null;

            if (log.IsTraceEnabled)
            {
                log.Trace($"Starting at commit {commit.ShortSha} (height {height})...");
            }

            while (true)
            {
                var parentCount = 0;

                if (commitsChecked.Add(commit.Sha))
                {
                    ++count;

                    var commitTagsAndVersions = tagsAndVersions.Where(tagAndVersion => tagAndVersion.tag.Sha == commit.Sha).ToList();
                    var foundVersion = false;

                    foreach (var (tag, commitVersion) in commitTagsAndVersions)
                    {
                        var candidate = new Candidate { Commit = commit, Height = height, Tag = tag.Name, Version = commitVersion, Index = candidates.Count };

                        foundVersion = foundVersion || candidate.Version != null;

                        if (log.IsTraceEnabled)
                        {
                            log.Trace($"Found {(candidate.Version == null ? "non-" : null)}version tag {candidate}.");
                        }

                        candidates.Add(candidate);
                    }

                    if (!foundVersion)
                    {
                        if (log.IsTraceEnabled)
                        {
                            var parentIndex = 0;
                            Commit firstParent = null;

                            foreach (var parent in commit.Parents)
                            {
                                switch (parentIndex)
                                {
                                    case 0:
                                        firstParent = parent;
                                        break;
                                    case 1:
                                        log.Trace($"History diverges from {commit.ShortSha} (height {height}) to:");
                                        log.Trace($"- {firstParent.ShortSha} (height {height + 1})");
                                        goto default;
                                    default:
                                        log.Trace($"- {parent.ShortSha} (height {height + 1})");
                                        break;
                                }

                                ++parentIndex;
                                parentCount = parentIndex;
                            }
                        }

                        foreach (var parent in ((IEnumerable<Commit>)commit.Parents).Reverse())
                        {
                            commitsToCheck.Push((parent, height + 1, commit));
                        }

                        if (commitsToCheck.Count == 0 || commitsToCheck.Peek().Item2 <= height)
                        {
                            var candidate = new Candidate { Commit = commit, Height = height, Tag = null, Version = new Version(defaultPreReleasePhase), Index = candidates.Count };

                            if (log.IsTraceEnabled)
                            {
                                log.Trace($"Found root commit {candidate}.");
                            }

                            candidates.Add(candidate);
                        }
                    }
                }
                else
                {
                    if (log.IsTraceEnabled)
                    {
                        log.Trace($"History converges from {previousCommit.ShortSha} (height {height - 1}) back to previously seen commit {commit.ShortSha} (height {height}). Abandoning path.");
                    }
                }

                if (commitsToCheck.Count == 0)
                {
                    break;
                }

                if (log.IsTraceEnabled)
                {
                    previousCommit = commit;
                }

                var oldHeight = height;
                Commit child;
                (commit, height, child) = commitsToCheck.Pop();

                if (log.IsTraceEnabled)
                {
                    if (parentCount > 1)
                    {
                        log.Trace($"Following path from {child.ShortSha} (height {height - 1}) through first parent {commit.ShortSha} (height {height})...");
                    }
                    else if (height <= oldHeight)
                    {
                        if (commitsToCheck.Any() && commitsToCheck.Peek().Item2 == height)
                        {
                            log.Trace($"Backtracking to {child.ShortSha} (height {height - 1}) and following path through next parent {commit.ShortSha} (height {height})...");
                        }
                        else
                        {
                            log.Trace($"Backtracking to {child.ShortSha} (height {height - 1}) and following path through last parent {commit.ShortSha} (height {height})...");
                        }
                    }
                }
            }

            log.Debug($"{count:N0} commits checked.");

            var orderedCandidates = candidates.OrderBy(candidate => candidate.Version).ThenByDescending(candidate => candidate.Index).ToList();

            var tagWidth = log.IsDebugEnabled ? orderedCandidates.Max(candidate => candidate.Tag?.Length ?? 2) : 0;
            var versionWidth = log.IsDebugEnabled ? orderedCandidates.Max(candidate => candidate.Version?.ToString().Length ?? 4) : 0;
            var heightWidth = log.IsDebugEnabled ? orderedCandidates.Max(candidate => candidate.Height).ToString(CultureInfo.CurrentCulture).Length : 0;

            if (log.IsDebugEnabled)
            {
                foreach (var candidate in orderedCandidates.Take(orderedCandidates.Count - 1))
                {
                    log.Debug($"Ignoring {candidate.ToString(tagWidth, versionWidth, heightWidth)}.");
                }
            }

            var selectedCandidate = orderedCandidates.Last();

            if (selectedCandidate.Tag == null)
            {
                log.Info($"No commit found with a valid SemVer 2.0 version{(tagPrefix == null ? null : $" prefixed with '{tagPrefix}'")}. Using default version {selectedCandidate.Version}.");
            }

            log.Info($"Using{(log.IsDebugEnabled && orderedCandidates.Count > 1 ? "    " : " ")}{selectedCandidate.ToString(tagWidth, versionWidth, heightWidth)}.");

            return selectedCandidate.Version.WithHeight(selectedCandidate.Height, autoIncrement, defaultPreReleasePhase);
        }

19 Source : Logging.cs
with GNU General Public License v3.0
from AdamWhiteHat

public static void LogMessage(string message, params object[] args)
		{
			LogMessage(args.Any() ? string.Format(message, args) : string.IsNullOrWhiteSpace(message) ? "(empty)" : message);
		}

19 Source : Serialization.Save.cs
with GNU General Public License v3.0
from AdamWhiteHat

public static void AppendList(GNFS gnfs, List<Relation> roughRelations)
                    {
                        if (roughRelations != null && roughRelations.Any())
                        {
                            string filename = Path.Combine(gnfs.SaveLocations.SaveDirectory, $"{nameof(RelationContainer.RoughRelations)}.json");
                            string json = JsonConvert.SerializeObject(roughRelations, Formatting.Indented);
                            json = json.Replace("[", "").Replace("]", ",");
                            File.AppendAllText(filename, json);
                            roughRelations.ForEach(rel => rel.IsPersisted = true);
                        }
                    }

19 Source : Serialization.Save.cs
with GNU General Public License v3.0
from AdamWhiteHat

public static void SingleSolution(GNFS gnfs, List<Relation> solution)
                    {
                        if (solution.Any())
                        {
                            solution.ForEach(rel => rel.IsPersisted = true);
                            Save.Object(solution, Path.Combine(gnfs.SaveLocations.SaveDirectory, $"{nameof(RelationContainer.FreeRelations)}_{gnfs.CurrentRelationsProgress.FreeRelationsCounter}.json"));
                            gnfs.CurrentRelationsProgress.FreeRelationsCounter += 1;
                        }
                    }

19 Source : FactorPairCollection.cs
with GNU General Public License v3.0
from AdamWhiteHat

public static List<FactorPair> FindPolynomialRootsInRange(CancellationToken cancelToken, Polynomial polynomial, IEnumerable<BigInteger> primes, BigInteger rangeFrom, BigInteger rangeTo, int totalFactorPairs)
        {
            List<FactorPair> result = new List<FactorPair>();

            BigInteger r = rangeFrom;
            IEnumerable<BigInteger> modList = primes.AsEnumerable();
            while (!cancelToken.IsCancellationRequested && r < rangeTo && result.Count < totalFactorPairs)
            {
                // Finds p such that ƒ(r) ≡ 0 (mod p)
                List<BigInteger> roots = GetRootsMod(polynomial, r, modList);
                if (roots.Any())
                {
                    result.AddRange(roots.Select(p => new FactorPair(p, r)));
                }
                r++;
            }

            return result.OrderBy(tup => tup.P).ToList();
        }

19 Source : FactorizationFactory.cs
with GNU General Public License v3.0
from AdamWhiteHat

public static IEnumerable<BigInteger> GetPrimeFactorCollection(BigInteger value, BigInteger maxValue)
		{
			if (value == 0)
			{
				return new BigInteger[] { };
			}

			List<BigInteger> factors = new List<BigInteger>();

			BigInteger toFactor = value;
			if (toFactor < 0)
			{
				//factors.Add(-1);
				toFactor = BigInteger.Abs(toFactor);
			}

			if (toFactor < 2)
			{
				if (toFactor == 1)
				{
					return new BigInteger[] { toFactor };
				}
			}

			if (PrimeFactory.IsPrime(toFactor))
			{
				factors.Add(toFactor);
				return factors;
			}

			foreach (BigInteger prime in PrimeFactory.GetPrimesTo(maxValue))
			{
				while (toFactor % prime == 0)
				{
					toFactor /= prime;
					factors.Add(prime);

					if (BigInteger.Abs(toFactor) == 1)
					{
						break;
					}
				}

				if (BigInteger.Abs(toFactor) == 1)
				{
					break;
				}
			}

			if (BigInteger.Abs(toFactor) != 1)
			{
				if (PrimeFactory.IsPrime(toFactor))
				{
					factors.Add(toFactor);
				}

				return factors;
			}
			else if (!factors.Any())
			{
				return new BigInteger[] { };
			}
			else
			{
				return factors;
			}
		}

19 Source : RxContentPage.cs
with MIT License
from adospace

public void Add(VisualNode child)
        {
            if (child is IRxView && _contents.OfType<IRxView>().Any())
                throw new InvalidOperationException("Content already set");

            _contents.Add(child);
        }

19 Source : SchemaPage.cs
with MIT License
from adoprog

private string GetFromFormFields(Item item)
    {
      var sb = new StringBuilder();
      var fieldItems = item.Axes.GetDescendants().Where(x => x.IsDerived(InputFieldTemplateId));
      sb.Append($@"{{ {Environment.NewLine}  ""type"": ""object"",{Environment.NewLine}  ""properties"": {{ ");
      var fieldDescriptors = new List<string>();
      foreach (var fieldItem in fieldItems)
      {
        fieldDescriptors.Add(
          $"{Environment.NewLine}\"{HttpUtility.JavaScriptStringEncode(fieldItem["replacedle"])}\": {{\"type\": \"string\"}}");
      }

      if (fieldDescriptors.Any())
      {
        sb.Append(fieldDescriptors.Aggregate((i, j) => i + "," + j));
      }

      sb.Append(Environment.NewLine + "  } " + Environment.NewLine + "}");
      return sb.ToString();
    }

19 Source : MonkeyStore.cs
with MIT License
from adenearnshaw

private List<Monkey> GetMonkeys()
        {
            var monkeys = LoadMonkeyData();

            if (monkeys.Any())
                return monkeys;


            monkeys.Add(new Monkey
            {
                Id = "monkey_001",
                Name = "Baboon",
                Location = "Africa & Asia",
                Details = "Baboons are African and Arabian Old World monkeys belonging to the genus Papio, part of the subfamily Cercopithecinae.",
                Image = "http://upload.wikimedia.org/wikipedia/commons/thumb/f/fc/Papio_anubis_%28Serengeti%2C_2009%29.jpg/200px-Papio_anubis_%28Serengeti%2C_2009%29.jpg"
            });

            monkeys.Add(new Monkey
            {
                Id = "monkey_002",
                Name = "Capuchin Monkey",
                Location = "Central & South America",
                Details = "The capuchin monkeys are New World monkeys of the subfamily Cebinae. Prior to 2011, the subfamily contained only a single genus, Cebus.",
                Image = "http://upload.wikimedia.org/wikipedia/commons/thumb/4/40/Capuchin_Costa_Rica.jpg/200px-Capuchin_Costa_Rica.jpg"
            });

            monkeys.Add(new Monkey
            {
                Id = "monkey_003",
                Name = "Blue Monkey",
                Location = "Central and East Africa",
                Details = "The blue monkey or diademed monkey is a species of Old World monkey native to Central and East Africa, ranging from the upper Congo River basin east to the East African Rift and south to northern Angola and Zambia",
                Image = "http://upload.wikimedia.org/wikipedia/commons/thumb/8/83/BlueMonkey.jpg/220px-BlueMonkey.jpg"
            });


            monkeys.Add(new Monkey
            {
                Id = "monkey_004",
                Name = "Squirrel Monkey",
                Location = "Central & South America",
                Details = "The squirrel monkeys are the New World monkeys of the genus Saimiri. They are the only genus in the subfamily Saimirinae. The name of the genus Saimiri is of Tupi origin, and was also used as an English name by early researchers.",
                Image = "http://upload.wikimedia.org/wikipedia/commons/thumb/2/20/Saimiri_sciureus-1_Luc_Viatour.jpg/220px-Saimiri_sciureus-1_Luc_Viatour.jpg"
            });

            monkeys.Add(new Monkey
            {
                Id = "monkey_005",
                Name = "Golden Lion Tamarin",
                Location = "Brazil",
                Details = "The golden lion tamarin also known as the golden marmoset, is a small New World monkey of the family Callitrichidae.",
                Image = "http://upload.wikimedia.org/wikipedia/commons/thumb/8/87/Golden_lion_tamarin_portrait3.jpg/220px-Golden_lion_tamarin_portrait3.jpg"
            });

            monkeys.Add(new Monkey
            {
                Id = "monkey_006",
                Name = "Howler Monkey",
                Location = "South America",
                Details = "Howler monkeys are among the largest of the New World monkeys. Fifteen species are currently recognised. Previously clreplacedified in the family Cebidae, they are now placed in the family Atelidae.",
                Image = "http://upload.wikimedia.org/wikipedia/commons/thumb/0/0d/Alouatta_guariba.jpg/200px-Alouatta_guariba.jpg"
            });

            monkeys.Add(new Monkey
            {
                Id = "monkey_007",
                Name = "replacedanese Macaque",
                Location = "replacedan",
                Details = "The replacedanese macaque, is a terrestrial Old World monkey species native to replacedan. They are also sometimes known as the snow monkey because they live in areas where snow covers the ground for months each",
                Image = "http://upload.wikimedia.org/wikipedia/commons/thumb/c/c1/Macaca_fuscata_fuscata1.jpg/220px-Macaca_fuscata_fuscata1.jpg"
            });

            monkeys.Add(new Monkey
            {
                Id = "monkey_008",
                Name = "Mandrill",
                Location = "Southern Cameroon, Gabon, Equatorial Guinea, and Congo",
                Details = "The mandrill is a primate of the Old World monkey family, closely related to the baboons and even more closely to the drill. It is found in southern Cameroon, Gabon, Equatorial Guinea, and Congo.",
                Image = "http://upload.wikimedia.org/wikipedia/commons/thumb/7/75/Mandrill_at_san_francisco_zoo.jpg/220px-Mandrill_at_san_francisco_zoo.jpg"
            });

            monkeys.Add(new Monkey
            {
                Id = "monkey_009",
                Name = "Proboscis Monkey",
                Location = "Borneo",
                Details = "The proboscis monkey or long-nosed monkey, known as the bekantan in Malay, is a reddish-brown arboreal Old World monkey that is endemic to the south-east Asian island of Borneo.",
                Image = "http://upload.wikimedia.org/wikipedia/commons/thumb/e/e5/Proboscis_Monkey_in_Borneo.jpg/250px-Proboscis_Monkey_in_Borneo.jpg"
            });

            SaveMonkeyData(monkeys);
            return monkeys;
        }

See More Examples